diff --git a/.gitignore b/.gitignore index 81e05ca00..7e62017a4 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ bin MagicMC +.externalToolBuilders/ /Plugins/Mineplex.Core/.externalToolBuilders/Core Builder.launch /Plugins/Mineplex.AntiCheat diff --git a/Patches/Bukkit-Patches/0032-Add-Elytra.patch b/Patches/Bukkit-Patches/0032-Add-Elytra.patch new file mode 100644 index 000000000..5334a8345 --- /dev/null +++ b/Patches/Bukkit-Patches/0032-Add-Elytra.patch @@ -0,0 +1,21 @@ +From 32269ec951791791fe8553f0939c6eaa2b6b472b Mon Sep 17 00:00:00 2001 +From: libraryaddict +Date: Wed, 30 Dec 2015 19:57:10 +1300 +Subject: [PATCH] Add Elytra + + +diff --git a/src/main/java/org/bukkit/Material.java b/src/main/java/org/bukkit/Material.java +index 0fb2605..bc930d1 100644 +--- a/src/main/java/org/bukkit/Material.java ++++ b/src/main/java/org/bukkit/Material.java +@@ -443,6 +443,7 @@ public enum Material { + JUNGLE_DOOR_ITEM(429), + ACACIA_DOOR_ITEM(430), + DARK_OAK_DOOR_ITEM(431), ++ ELYTRA(443), + GOLD_RECORD(2256, 1), + GREEN_RECORD(2257, 1), + RECORD_3(2258, 1), +-- +1.9.5.msysgit.0 + diff --git a/Patches/Bukkit-Patches/0033-Levitation-potion-effect.patch b/Patches/Bukkit-Patches/0033-Levitation-potion-effect.patch new file mode 100644 index 000000000..d30465337 --- /dev/null +++ b/Patches/Bukkit-Patches/0033-Levitation-potion-effect.patch @@ -0,0 +1,46 @@ +From 24a5d0cfe1d62e2ff6a3a0a279c63b038a134629 Mon Sep 17 00:00:00 2001 +From: libraryaddict +Date: Wed, 30 Dec 2015 21:05:47 +1300 +Subject: [PATCH] Levitation potion effect + + +diff --git a/src/main/java/org/bukkit/potion/PotionEffectType.java b/src/main/java/org/bukkit/potion/PotionEffectType.java +index 4919d59..e75aa18 100644 +--- a/src/main/java/org/bukkit/potion/PotionEffectType.java ++++ b/src/main/java/org/bukkit/potion/PotionEffectType.java +@@ -126,6 +126,11 @@ public abstract class PotionEffectType { + */ + public static final PotionEffectType SATURATION = new PotionEffectTypeWrapper(23); + ++ /** ++ * Slows the fall rate down ++ */ ++ public static final PotionEffectType LEVITATION = new PotionEffectTypeWrapper(25); ++ + private final int id; + + protected PotionEffectType(int id) { +@@ -202,7 +207,7 @@ public abstract class PotionEffectType { + return "PotionEffectType[" + id + ", " + getName() + "]"; + } + +- private static final PotionEffectType[] byId = new PotionEffectType[24]; ++ private static final PotionEffectType[] byId = new PotionEffectType[26]; + private static final Map byName = new HashMap(); + // will break on updates. + private static boolean acceptingNew = true; +diff --git a/src/main/java/org/bukkit/potion/PotionType.java b/src/main/java/org/bukkit/potion/PotionType.java +index 6ad9a91..a3dc228 100644 +--- a/src/main/java/org/bukkit/potion/PotionType.java ++++ b/src/main/java/org/bukkit/potion/PotionType.java +@@ -15,6 +15,7 @@ public enum PotionType { + INSTANT_DAMAGE(12, PotionEffectType.HARM, 2), + WATER_BREATHING(13, PotionEffectType.WATER_BREATHING, 1), + INVISIBILITY(14, PotionEffectType.INVISIBILITY, 1), ++ LEVITATION(15, PotionEffectType.LEVITATION, 1), + ; + + private final int damageValue, maxLevel; +-- +1.9.5.msysgit.0 + diff --git a/Patches/CraftBukkit-Patches/0177-Dual-version-patch-and-some-other-fixes.patch b/Patches/CraftBukkit-Patches/0177-Dual-version-patch-and-some-other-fixes.patch new file mode 100644 index 000000000..31947a9ff --- /dev/null +++ b/Patches/CraftBukkit-Patches/0177-Dual-version-patch-and-some-other-fixes.patch @@ -0,0 +1,7380 @@ +From 4b151cd529c5de0d32cc78357f417c9fa4866198 Mon Sep 17 00:00:00 2001 +From: libraryaddict +Date: Sun, 29 Nov 2015 02:53:00 +1300 +Subject: [PATCH] Dual version patch and some other fixes + + +diff --git a/src/main/java/com/mineplex/chunk/BlockMap.java b/src/main/java/com/mineplex/chunk/BlockMap.java +new file mode 100644 +index 0000000..22b362a +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/BlockMap.java +@@ -0,0 +1,64 @@ ++package com.mineplex.chunk; ++ ++import net.minecraft.server.MathHelper; ++ ++import org.apache.commons.lang3.Validate; ++ ++public class BlockMap ++{ ++ private final long[] a; ++ private final int b; ++ private final long c; ++ private final int d; ++ ++ public BlockMap(int n2, int n3) ++ { ++ Validate.inclusiveBetween(1, 32, n2); ++ this.d = n3; ++ this.b = n2; ++ this.c = (1 << n2) - 1; ++ this.a = new long[MathHelper.c(n3 * n2, 64) / 64]; ++ } ++ ++ public void a(int n2, int n3) ++ { ++ Validate.inclusiveBetween(0, this.d - 1, n2); ++ Validate.inclusiveBetween(0, this.c, n3); ++ int n4 = n2 * this.b; ++ int n5 = n4 / 64; ++ int n6 = ((n2 + 1) * this.b - 1) / 64; ++ int n7 = n4 % 64; ++ this.a[n5] = this.a[n5] & (this.c << n7 ^ -1) | ((long) n3 & this.c) << n7; ++ if (n5 != n6) ++ { ++ int n8 = 64 - n7; ++ int n9 = this.b - n8; ++ this.a[n6] = this.a[n6] >>> n9 << n9 | ((long) n3 & this.c) >> n8; ++ } ++ } ++ ++ public int a(int n2) ++ { ++ Validate.inclusiveBetween(0, this.d - 1, n2); ++ int n3 = n2 * this.b; ++ int n4 = n3 / 64; ++ int n5 = ((n2 + 1) * this.b - 1) / 64; ++ int n6 = n3 % 64; ++ if (n4 == n5) ++ { ++ return (int) (this.a[n4] >>> n6 & this.c); ++ } ++ int n7 = 64 - n6; ++ return (int) ((this.a[n4] >>> n6 | this.a[n5] << n7) & this.c); ++ } ++ ++ public long[] a() ++ { ++ return this.a; ++ } ++ ++ public int b() ++ { ++ return this.d; ++ } ++} +diff --git a/src/main/java/com/mineplex/chunk/BlockPalette.java b/src/main/java/com/mineplex/chunk/BlockPalette.java +new file mode 100644 +index 0000000..527796c +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/BlockPalette.java +@@ -0,0 +1,15 @@ ++package com.mineplex.chunk; ++ ++import net.minecraft.server.IBlockData; ++import net.minecraft.server.PacketDataSerializer; ++ ++public interface BlockPalette ++{ ++ public int addGetIndex(IBlockData data); ++ ++ public IBlockData getBlock(int index); ++ ++ public void writeSerializer(PacketDataSerializer dataSerializer); ++ ++ public int getLength(); ++} +diff --git a/src/main/java/com/mineplex/chunk/LargeBlockPalette.java b/src/main/java/com/mineplex/chunk/LargeBlockPalette.java +new file mode 100644 +index 0000000..b68ab86 +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/LargeBlockPalette.java +@@ -0,0 +1,39 @@ ++package com.mineplex.chunk; ++ ++import net.minecraft.server.Block; ++import net.minecraft.server.Blocks; ++import net.minecraft.server.IBlockData; ++import net.minecraft.server.PacketDataSerializer; ++ ++public class LargeBlockPalette implements BlockPalette ++{ ++ ++ // Get index ++ @Override ++ public int addGetIndex(IBlockData aqt2) ++ { ++ int n2 = Block.d.b(aqt2); ++ return n2 == -1 ? 0 : n2; ++ } ++ ++ // Get from index ++ @Override ++ public IBlockData getBlock(int index) ++ { ++ IBlockData aqt2 = (IBlockData) Block.d.a(index); ++ return aqt2 == null ? Blocks.AIR.getBlockData() : aqt2; ++ } ++ ++ @Override ++ public void writeSerializer(PacketDataSerializer em2) ++ { ++ em2.b(0); ++ } ++ ++ @Override ++ public int getLength() ++ { ++ return PacketDataSerializer.a(0); ++ } ++ ++} +diff --git a/src/main/java/com/mineplex/chunk/MediumBlockPalette.java b/src/main/java/com/mineplex/chunk/MediumBlockPalette.java +new file mode 100644 +index 0000000..4c0dcc5 +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/MediumBlockPalette.java +@@ -0,0 +1,63 @@ ++package com.mineplex.chunk; ++ ++import java.util.ArrayList; ++import java.util.LinkedHashMap; ++ ++import net.minecraft.server.Block; ++import net.minecraft.server.IBlockData; ++import net.minecraft.server.PacketDataSerializer; ++import net.minecraft.server.ChunkSection; ++ ++public class MediumBlockPalette implements BlockPalette ++{ ++ private PaletteMediumList a; ++ private ChunkSection b; ++ private int bitShift; ++ ++ public MediumBlockPalette(int bitShift, ChunkSection section) ++ { ++ this.bitShift = bitShift; ++ b = section; ++ this.a = new PaletteMediumList(1 << bitShift); ++ } ++ ++ @Override ++ public int addGetIndex(IBlockData data) ++ { ++ int n2 = this.a.a(data); ++ if (n2 == -1 && (n2 = this.a.c(data)) >= 1 << this.bitShift) ++ { ++ n2 = this.b.resizePalette(this.bitShift + 1, data); ++ } ++ return n2; ++ } ++ ++ @Override ++ public IBlockData getBlock(int index) ++ { ++ return a.get(index); ++ } ++ ++ @Override ++ public void writeSerializer(PacketDataSerializer dataSerializer) ++ { ++ int n2 = this.a.b(); ++ dataSerializer.b(n2); ++ for (int i2 = 0; i2 < n2; ++i2) ++ { ++ dataSerializer.b(Block.d.b(this.a.get(i2))); ++ } ++ } ++ ++ @Override ++ public int getLength() ++ { ++ int n2 = PacketDataSerializer.a(this.a.b()); ++ for (int i2 = 0; i2 < this.a.b(); ++i2) ++ { ++ n2 += PacketDataSerializer.a(Block.d.b(this.a.get(i2))); ++ } ++ return n2; ++ } ++ ++} +diff --git a/src/main/java/com/mineplex/chunk/PaletteMediumList.java b/src/main/java/com/mineplex/chunk/PaletteMediumList.java +new file mode 100644 +index 0000000..41917be +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/PaletteMediumList.java +@@ -0,0 +1,171 @@ ++package com.mineplex.chunk; ++ ++import java.util.Iterator; ++ ++import com.google.common.base.Predicates; ++import com.google.common.collect.Iterators; ++ ++public class PaletteMediumList implements Iterable ++{ ++ private static final Object a = null; ++ private T[] b; ++ private int[] c; ++ private T[] d; ++ private int e; ++ private int f; ++ ++ public PaletteMediumList(int n2) ++ { ++ n2 = (int) ((float) n2 / 0.8f); ++ this.b = (T[]) new Object[n2]; ++ this.c = new int[n2]; ++ this.d = (T[]) new Object[n2]; ++ } ++ ++ public int a(T k2) ++ { ++ return this.c(this.b(k2, this.d(k2))); ++ } ++ ++ public T get(int n2) ++ { ++ if (n2 < 0 || n2 >= this.d.length) ++ { ++ return null; ++ } ++ return this.d[n2]; ++ } ++ ++ private int c(int n2) ++ { ++ if (n2 == -1) ++ { ++ return -1; ++ } ++ return this.c[n2]; ++ } ++ ++ public int c(T k2) ++ { ++ int n2 = this.c(); ++ this.a(k2, n2); ++ return n2; ++ } ++ ++ private int c() ++ { ++ while (this.e < this.d.length && this.d[this.e] != null) ++ { ++ ++this.e; ++ } ++ return this.e++; ++ } ++ ++ private void d(int n2) ++ { ++ T[] arrK = this.b; ++ int[] arrn = this.c; ++ this.b = (T[]) new Object[n2]; ++ this.c = new int[n2]; ++ this.d = (T[]) new Object[n2]; ++ this.e = 0; ++ this.f = 0; ++ for (int i2 = 0; i2 < arrK.length; ++i2) ++ { ++ if (arrK[i2] == null) ++ continue; ++ this.a(arrK[i2], arrn[i2]); ++ } ++ } ++ ++ public void a(T k2, int n2) ++ { ++ int n3; ++ int n4; ++ if ((float) (n4 = Math.max(n2, ++this.f)) >= (float) this.b.length * 0.8f) ++ { ++ for (n3 = this.b.length << 1; n3 < n2; n3 <<= 1) ++ { ++ } ++ this.d(n3); ++ } ++ n3 = this.e(this.d(k2)); ++ this.b[n3] = k2; ++ this.c[n3] = n2; ++ this.d[n2] = k2; ++ } ++ ++ public static int math(int n2) ++ { ++ n2 ^= n2 >>> 16; ++ n2 *= -2048144789; ++ n2 ^= n2 >>> 13; ++ n2 *= -1028477387; ++ n2 ^= n2 >>> 16; ++ return n2; ++ } ++ ++ private int d(T k2) ++ { ++ return (math(System.identityHashCode(k2)) & Integer.MAX_VALUE) % this.b.length; ++ } ++ ++ private int b(T k2, int n2) ++ { ++ int n3; ++ for (n3 = n2; n3 < this.b.length; ++n3) ++ { ++ if (this.b[n3] == k2) ++ { ++ return n3; ++ } ++ if (this.b[n3] != a) ++ continue; ++ return -1; ++ } ++ for (n3 = 0; n3 < n2; ++n3) ++ { ++ if (this.b[n3] == k2) ++ { ++ return n3; ++ } ++ if (this.b[n3] != a) ++ continue; ++ return -1; ++ } ++ return -1; ++ } ++ ++ private int e(int n2) ++ { ++ int n3; ++ StringBuilder stringBuilder = new StringBuilder(""); ++ for (n3 = n2; n3 < this.b.length; ++n3) ++ { ++ if (this.b[n3] == a) ++ { ++ return n3; ++ } ++ stringBuilder.append(n3).append(' '); ++ } ++ for (n3 = 0; n3 < n2; ++n3) ++ { ++ if (this.b[n3] == a) ++ { ++ return n3; ++ } ++ stringBuilder.append(n3).append(' '); ++ } ++ throw new RuntimeException("Overflowed :("); ++ } ++ ++ public Iterator iterator() ++ { ++ return Iterators.filter(Iterators.forArray(this.d), Predicates.notNull()); ++ } ++ ++ public int b() ++ { ++ return this.f + 1; ++ } ++} +diff --git a/src/main/java/com/mineplex/chunk/SmallBlockPalette.java b/src/main/java/com/mineplex/chunk/SmallBlockPalette.java +new file mode 100644 +index 0000000..66c2e14 +--- /dev/null ++++ b/src/main/java/com/mineplex/chunk/SmallBlockPalette.java +@@ -0,0 +1,78 @@ ++package com.mineplex.chunk; ++ ++import net.minecraft.server.Block; ++import net.minecraft.server.IBlockData; ++import net.minecraft.server.PacketDataSerializer; ++import net.minecraft.server.ChunkSection; ++ ++public class SmallBlockPalette implements BlockPalette ++{ ++ private final IBlockData[] a; ++ private final ChunkSection b; ++ private final int bitShift; ++ private int d; ++ ++ public SmallBlockPalette(int bitShift, ChunkSection section) ++ { ++ this.a = new IBlockData[1 << bitShift]; ++ this.bitShift = bitShift; ++ this.b = section; ++ } ++ ++ @Override ++ public int addGetIndex(IBlockData data) ++ { ++ int n2; ++ for (n2 = 0; n2 < this.d; ++n2) ++ { ++ if (this.a[n2] != data) ++ continue; ++ return n2; ++ } ++ ++ if ((n2 = this.d++) < this.a.length) ++ { ++ this.a[n2] = data; ++ if (n2 == 16) ++ { ++ System.out.println(""); ++ } ++ return n2; ++ } ++ ++ return this.b.resizePalette(this.bitShift + 1, data); ++ } ++ ++ @Override ++ public IBlockData getBlock(int index) ++ { ++ if (index > 0 && index < this.d) ++ { ++ return this.a[index]; ++ } ++ ++ return null; ++ } ++ ++ @Override ++ public void writeSerializer(PacketDataSerializer dataSerializer) ++ { ++ dataSerializer.b(this.d); ++ for (int i2 = 0; i2 < this.d; ++i2) ++ { ++ dataSerializer.b(Block.d.b(this.a[i2])); ++ } ++ } ++ ++ @Override ++ public int getLength() ++ { ++ int n2 = PacketDataSerializer.a(this.d); ++ for (int i2 = 0; i2 < this.d; ++i2) ++ { ++ n2 += PacketDataSerializer.a(Block.d.b(this.a[i2])); ++ } ++ return n2; ++ } ++ ++} +diff --git a/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java b/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java +new file mode 100644 +index 0000000..81954a4 +--- /dev/null ++++ b/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java +@@ -0,0 +1,570 @@ ++package com.mineplex.spigot; ++ ++import java.lang.reflect.Field; ++import java.util.Map; ++ ++import org.bukkit.Material; ++import org.bukkit.craftbukkit.inventory.CraftItemStack; ++ ++import com.google.common.base.Objects; ++ ++import net.minecraft.server.ChatComponentText; ++import net.minecraft.server.ChatMessage; ++import net.minecraft.server.EntityTypes; ++import net.minecraft.server.IChatBaseComponent; ++import net.minecraft.server.Item; ++import net.minecraft.server.ItemStack; ++import net.minecraft.server.NBTTagCompound; ++import net.minecraft.server.NBTTagList; ++import net.minecraft.server.NBTTagString; ++import net.minecraft.server.PacketDataSerializer; ++ ++public class MineplexTranslateItem ++{ ++ private static final String[] potionNames = new String[128]; ++ private static Map entityTypes; ++ ++ public static IChatBaseComponent convertChat(IChatBaseComponent eu2) throws Exception ++ { ++ Object[] arrobject = null; ++ IChatBaseComponent eu3 = null; ++ ++ if (eu2 instanceof ChatComponentText) ++ { ++ eu3 = new ChatComponentText(((ChatComponentText) eu2).g()); ++ } ++ else if (eu2 instanceof ChatMessage) ++ { ++ arrobject = ((ChatMessage) eu2).j(); ++ for (int i2 = 0; i2 < arrobject.length; ++i2) ++ { ++ Object object = arrobject[i2]; ++ if (!(object instanceof IChatBaseComponent)) ++ continue; ++ arrobject[i2] = convertChat((IChatBaseComponent) object); ++ } ++ eu3 = new ChatMessage(((ChatMessage) eu2).i(), arrobject); ++ } ++ else ++ { ++ return eu2; ++ } ++ ++ for (IChatBaseComponent eu4 : eu2.a()) ++ { ++ eu3.addSibling(convertChat(eu4)); ++ } ++ return eu3; ++ } ++ ++ public static ItemStack receiveItemStack(int id, byte amount, short data, NBTTagCompound nbt) ++ { ++ ItemStack itemstack = new ItemStack(Item.getById(id == 438 ? 373 : id), amount, data); ++ itemstack.setTag(nbt); ++ ++ switch (id) ++ { ++ case 383: ++ if (nbt == null) ++ { ++ break; ++ } ++ ++ if (!nbt.hasKey("EntityTag")) ++ { ++ break; ++ } ++ ++ if (!((NBTTagCompound) nbt.get("EntityTag")).hasKey("id")) ++ { ++ break; ++ } ++ ++ Integer entId = entityTypes.get(((NBTTagCompound) nbt.get("EntityTag")).getString("id")); ++ ++ itemstack.setData(entId); ++ break; ++ case 373: ++ itemstack = receivePotion(itemstack, false); ++ break; ++ case 438: ++ itemstack = receivePotion(itemstack, true); ++ break; ++ default: ++ break; ++ } ++ ++ return itemstack; ++ } ++ ++ public static void sendItemStack(PacketDataSerializer serializer, ItemStack itemstack) ++ { ++ if (itemstack == null || itemstack.getItem() == null || serializer.version == 47) ++ { ++ writeItemStack(serializer, itemstack); ++ return; ++ } ++ ++ switch (Item.getId(itemstack.getItem())) ++ { ++ case 383: ++ itemstack = itemstack.cloneItemStack(); ++ ++ CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); ++ ++ NBTTagCompound nbt = itemstack.getTag(); ++ ++ if (nbt == null) ++ { ++ nbt = new NBTTagCompound(); ++ } ++ ++ String entity = EntityTypes.b(itemstack.getData()); ++ ++ if (entity == null) ++ { ++ nbt.remove("EntityTag"); ++ } ++ else ++ { ++ if (!nbt.hasKey("EntityTag")) ++ { ++ nbt.set("EntityTag", new NBTTagCompound()); ++ } ++ ++ ((NBTTagCompound) nbt.get("EntityTag")).setString("id", entity); ++ } ++ ++ serializer.writeShort(Material.MONSTER_EGG.getId()); ++ serializer.writeByte(itemstack.count); ++ serializer.writeShort(0); ++ ++ serializer.a(nbt); ++ ++ return; ++ case 373: ++ sendPotion(serializer, itemstack.cloneItemStack()); ++ return; ++ case 387: ++ //sendBook(serializer, itemstack.cloneItemStack()); ++ //return; ++ default: ++ break; ++ } ++ ++ writeItemStack(serializer, itemstack); ++ } ++ ++ private static void sendBook(PacketDataSerializer serializer, ItemStack itemstack) ++ { ++ CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); ++ ++ NBTTagCompound nbt = itemstack.getTag(); ++ ++ if (nbt == null) ++ { ++ writeItemStack(serializer, itemstack); ++ return; ++ } ++ ++ nbt.remove("generation"); ++ nbt.setInt("resolved", 1); ++ NBTTagList list = nbt.getList("pages", 8); ++ NBTTagList newList = new NBTTagList(); ++ ++ for (int i = 0; i < list.size(); i++) ++ { ++ String string = list.getString(i); ++ ++ if (string.endsWith(",\"text\":\"\"}")) ++ { ++ string = string.replace(",\"text\":\"\"}", "}").replaceFirst("extra", "text"); ++ } ++ else if (string.startsWith("\"")) ++ string = "{\"text\":" + string + "}"; ++ ++ newList.add(new NBTTagString(string)); ++ ++ /*IChatBaseComponent arg; ++ try ++ { ++ arg = IChatBaseComponent.ChatSerializer.a(string); ++ arg = convertChat(arg); ++ } ++ catch (Exception ex) ++ { ++ arg = new ChatComponentText(string); ++ } ++ ++ list.a(i, new NBTTagString(IChatBaseComponent.ChatSerializer.a(arg)));*/ ++ } ++ nbt.set("pages", newList); ++ ++ for (String n : nbt.c()) ++ { ++ System.out.print("Key: " + n); ++ System.out.print("Value: " + nbt.get(n)); ++ ++ if (nbt.get(n) instanceof NBTTagList) ++ { ++ for (int i = 0; i < nbt.getList(n, 8).size(); i++) ++ { ++ System.out.print("List: " + nbt.getList(n, 8).getString(i)); ++ } ++ } ++ } ++ ++ serializer.writeShort(Item.getId(itemstack.getItem())); ++ serializer.writeByte(itemstack.count); ++ serializer.writeShort(itemstack.getData()); ++ ++ serializer.a(nbt); ++ } ++ ++ private static void writeItemStack(PacketDataSerializer serializer, ItemStack itemstack) ++ { ++ if (itemstack == null || itemstack.getItem() == null) ++ { // CraftBukkit - NPE fix itemstack.getItem() ++ serializer.writeShort(-1); ++ } ++ else ++ { ++ serializer.writeShort(Item.getId(itemstack.getItem())); ++ serializer.writeByte(itemstack.count); ++ serializer.writeShort(itemstack.getData()); ++ NBTTagCompound nbttagcompound = null; ++ ++ if (itemstack.getItem().usesDurability() || itemstack.getItem().p()) ++ { ++ // Spigot start - filter ++ itemstack = itemstack.cloneItemStack(); ++ CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); ++ // Spigot end ++ nbttagcompound = itemstack.getTag(); ++ } ++ ++ serializer.a(nbttagcompound); ++ } ++ } ++ ++ public static void sendPotion(PacketDataSerializer serializer, ItemStack item) ++ { ++ CraftItemStack.setItemMeta(item, CraftItemStack.getItemMeta(item)); ++ ++ NBTTagCompound itemNbt = item.getTag(); ++ ++ if (itemNbt == null) ++ { ++ itemNbt = new NBTTagCompound(); ++ } ++ ++ int dura = item.getData(); ++ boolean splash = (dura & 16384) == 16384; ++ ++ String string = potionNames[dura & 127]; ++ itemNbt.setString("Potion", string == null ? "minecraft:water" : string); ++ ++ int id = !splash ? 373 : 438; ++ ++ serializer.writeShort(id); ++ serializer.writeByte(item.count); ++ serializer.writeShort(0); ++ ++ serializer.a(itemNbt); ++ } ++ ++ public static ItemStack receivePotion(ItemStack itemstack, boolean splash) ++ { ++ NBTTagCompound itemNbt = itemstack.getTag(); ++ ++ if (itemNbt == null || !itemNbt.hasKey("Potion")) ++ { ++ return itemstack; ++ } ++ ++ String type = itemNbt.getString("Potion"); ++ ++ int dura = 0; ++ ++ if (type != null && !type.equals("minecraft:water")) ++ { ++ for (int i = 0; i < potionNames.length; i++) ++ { ++ String b = potionNames[i]; ++ ++ if (Objects.equal(b, type)) ++ { ++ dura = i; ++ break; ++ } ++ } ++ } ++ ++ if (splash) ++ { ++ dura += 16384; ++ } ++ else if (dura > 0) ++ { ++ dura += 8192; ++ } ++ ++ itemstack.setData(dura); ++ ++ return itemstack; ++ } ++ ++ static ++ { ++ potionNames[0] = "minecraft:water"; ++ potionNames[1] = "minecraft:regeneration"; ++ potionNames[2] = "minecraft:swiftness"; ++ potionNames[3] = "minecraft:fire_resistance"; ++ potionNames[4] = "minecraft:poison"; ++ potionNames[5] = "minecraft:healing"; ++ potionNames[6] = "minecraft:night_vision"; ++ potionNames[7] = null; ++ potionNames[8] = "minecraft:weakness"; ++ potionNames[9] = "minecraft:strength"; ++ potionNames[10] = "minecraft:slowness"; ++ potionNames[11] = "minecraft:leaping"; ++ potionNames[12] = "minecraft:harming"; ++ potionNames[13] = "minecraft:water_breathing"; ++ potionNames[14] = "minecraft:invisibility"; ++ potionNames[15] = null; ++ potionNames[16] = "minecraft:awkward"; ++ potionNames[17] = "minecraft:regeneration"; ++ potionNames[18] = "minecraft:swiftness"; ++ potionNames[19] = "minecraft:fire_resistance"; ++ potionNames[20] = "minecraft:poison"; ++ potionNames[21] = "minecraft:healing"; ++ potionNames[22] = "minecraft:night_vision"; ++ potionNames[23] = null; ++ potionNames[24] = "minecraft:weakness"; ++ potionNames[25] = "minecraft:strength"; ++ potionNames[26] = "minecraft:slowness"; ++ potionNames[27] = "minecraft:leaping"; ++ potionNames[28] = "minecraft:harming"; ++ potionNames[29] = "minecraft:water_breathing"; ++ potionNames[30] = "minecraft:invisibility"; ++ potionNames[31] = null; ++ potionNames[32] = "minecraft:thick"; ++ potionNames[33] = "minecraft:strong_regeneration"; ++ potionNames[34] = "minecraft:strong_swiftness"; ++ potionNames[35] = "minecraft:fire_resistance"; ++ potionNames[36] = "minecraft:strong_poison"; ++ potionNames[37] = "minecraft:strong_healing"; ++ potionNames[38] = "minecraft:night_vision"; ++ potionNames[39] = null; ++ potionNames[40] = "minecraft:weakness"; ++ potionNames[41] = "minecraft:strong_strength"; ++ potionNames[42] = "minecraft:slowness"; ++ potionNames[43] = "minecraft:strong_leaping"; ++ potionNames[44] = "minecraft:strong_harming"; ++ potionNames[45] = "minecraft:water_breathing"; ++ potionNames[46] = "minecraft:invisibility"; ++ potionNames[47] = null; ++ potionNames[48] = null; ++ potionNames[49] = "minecraft:strong_regeneration"; ++ potionNames[50] = "minecraft:strong_swiftness"; ++ potionNames[51] = "minecraft:fire_resistance"; ++ potionNames[52] = "minecraft:strong_poison"; ++ potionNames[53] = "minecraft:strong_healing"; ++ potionNames[54] = "minecraft:night_vision"; ++ potionNames[55] = null; ++ potionNames[56] = "minecraft:weakness"; ++ potionNames[57] = "minecraft:strong_strength"; ++ potionNames[58] = "minecraft:slowness"; ++ potionNames[59] = "minecraft:strong_leaping"; ++ potionNames[60] = "minecraft:strong_harming"; ++ potionNames[61] = "minecraft:water_breathing"; ++ potionNames[62] = "minecraft:invisibility"; ++ potionNames[63] = null; ++ potionNames[64] = "minecraft:mundane"; ++ potionNames[65] = "minecraft:long_regeneration"; ++ potionNames[66] = "minecraft:long_swiftness"; ++ potionNames[67] = "minecraft:long_fire_resistance"; ++ potionNames[68] = "minecraft:long_poison"; ++ potionNames[69] = "minecraft:healing"; ++ potionNames[70] = "minecraft:long_night_vision"; ++ potionNames[71] = null; ++ potionNames[72] = "minecraft:long_weakness"; ++ potionNames[73] = "minecraft:long_strength"; ++ potionNames[74] = "minecraft:long_slowness"; ++ potionNames[75] = "minecraft:long_leaping"; ++ potionNames[76] = "minecraft:harming"; ++ potionNames[77] = "minecraft:long_water_breathing"; ++ potionNames[78] = "minecraft:long_invisibility"; ++ potionNames[79] = null; ++ potionNames[80] = "minecraft:awkward"; ++ potionNames[81] = "minecraft:long_regeneration"; ++ potionNames[82] = "minecraft:long_swiftness"; ++ potionNames[83] = "minecraft:long_fire_resistance"; ++ potionNames[84] = "minecraft:long_poison"; ++ potionNames[85] = "minecraft:healing"; ++ potionNames[86] = "minecraft:long_night_vision"; ++ potionNames[87] = null; ++ potionNames[88] = "minecraft:long_weakness"; ++ potionNames[89] = "minecraft:long_strength"; ++ potionNames[90] = "minecraft:long_slowness"; ++ potionNames[91] = "minecraft:long_leaping"; ++ potionNames[92] = "minecraft:harming"; ++ potionNames[93] = "minecraft:long_water_breathing"; ++ potionNames[94] = "minecraft:long_invisibility"; ++ potionNames[95] = null; ++ potionNames[96] = "minecraft:thick"; ++ potionNames[97] = "minecraft:regeneration"; ++ potionNames[98] = "minecraft:swiftness"; ++ potionNames[99] = "minecraft:long_fire_resistance"; ++ potionNames[100] = "minecraft:poison"; ++ potionNames[101] = "minecraft:strong_healing"; ++ potionNames[102] = "minecraft:long_night_vision"; ++ potionNames[103] = null; ++ potionNames[104] = "minecraft:long_weakness"; ++ potionNames[105] = "minecraft:strength"; ++ potionNames[106] = "minecraft:long_slowness"; ++ potionNames[107] = "minecraft:leaping"; ++ potionNames[108] = "minecraft:strong_harming"; ++ potionNames[109] = "minecraft:long_water_breathing"; ++ potionNames[110] = "minecraft:long_invisibility"; ++ potionNames[111] = null; ++ potionNames[112] = null; ++ potionNames[113] = "minecraft:regeneration"; ++ potionNames[114] = "minecraft:swiftness"; ++ potionNames[115] = "minecraft:long_fire_resistance"; ++ potionNames[116] = "minecraft:poison"; ++ potionNames[117] = "minecraft:strong_healing"; ++ potionNames[118] = "minecraft:long_night_vision"; ++ potionNames[119] = null; ++ potionNames[120] = "minecraft:long_weakness"; ++ potionNames[121] = "minecraft:strength"; ++ potionNames[122] = "minecraft:long_slowness"; ++ potionNames[123] = "minecraft:leaping"; ++ potionNames[124] = "minecraft:strong_harming"; ++ potionNames[125] = "minecraft:long_water_breathing"; ++ potionNames[126] = "minecraft:long_invisibility"; ++ potionNames[127] = null; ++ ++ // b[0] = 0; ++ // b[1] = 8193; ++ // b[2] = 8194; ++ // b[3] = 8195; ++ // b[4] = 8196; ++ // b[5] = 8197; ++ // b[6] = 8198; ++ // b[8] = 8200; ++ // b[9] = 8265; ++ // b[10] = 8202; ++ // b[11] = 8203; ++ // b[12] = 8204; ++ // b[13] = 8205; ++ // b[14] = 8206; ++ // b[16] = 8207; ++ // b[17] = 8193; ++ // b[18] = 8194; ++ // b[19] = 8195; ++ // b[20] = 8196; ++ // b[21] = 8197; ++ // b[22] = 8198; ++ // b[24] = 8200; ++ // b[25] = 8265; ++ // b[26] = 8202; ++ // b[27] = 8203; ++ // b[28] = 8204; ++ // b[29] = 8205; ++ // b[30] = 8206; ++ // b[32] = "minecraft:thick"; ++ // b[33] = 8225; ++ // b[34] = 8226; ++ // b[35] = 8195; ++ // b[36] = 8228; ++ // b[37] = 8229; ++ // b[38] = 8198; ++ // b[40] = 8200; ++ // b[41] = 8233; ++ // b[42] = 8202; ++ // b[43] = 8235; ++ // b[44] = 8236; ++ // b[45] = 8205; ++ // b[46] = 8206; ++ // b[49] = 8225; ++ // b[50] = 8226; ++ // b[51] = 8195; ++ // b[52] = 8228; ++ // b[53] = 8229; ++ // b[54] = 8198; ++ // b[56] = 8200; ++ // b[57] = 8233; ++ // b[58] = 8202; ++ // b[59] = 8235; ++ // b[60] = 8236; ++ // b[61] = 8205; ++ // b[62] = 8206; ++ // b[64] = "minecraft:mundane"; ++ // b[65] = 8257; ++ // b[66] = 8258; ++ // b[67] = 8259; ++ // b[68] = 8260; ++ // b[69] = 8197; ++ // b[70] = 8198; ++ // b[72] = 8264; ++ // b[73] = 8265; ++ // b[74] = 8266; ++ // b[75] = 8267; ++ // b[76] = 8204; ++ // b[77] = 8269; ++ // b[78] = 8270; ++ // b[80] = "minecraft:awkward"; ++ // b[81] = 8257; ++ // b[82] = 8258; ++ // b[83] = 8259; ++ // b[84] = 8260; ++ // b[85] = 8197; ++ // b[86] = 8198; ++ // b[88] = 8264; ++ // b[89] = 8265; ++ // b[90] = 8266; ++ // b[91] = 8267; ++ // b[92] = 8204; ++ // b[93] = 8269; ++ // b[94] = 8270; ++ // b[96] = "minecraft:thick"; ++ // b[97] = 8193; ++ // b[98] = 8194; ++ // b[99] = 8259; ++ // b[100] = 8196; ++ // b[101] = 8229; ++ // b[102] = 8198; ++ // b[104] = 8264; ++ // b[105] = 8265; ++ // b[106] = 8266; ++ // b[107] = 8203; ++ // b[108] = 8236; ++ // b[109] = 8269; ++ // b[110] = 8270; ++ // b[113] = 8193; ++ // b[114] = 8194; ++ // b[115] = 8259; ++ // b[116] = 8196; ++ // b[117] = 8229; ++ // b[118] = 8198; ++ // b[120] = 8264; ++ // b[121] = 8265; ++ // b[122] = 8266; ++ // b[123] = 8203; ++ // b[124] = 8236; ++ // b[125] = 8269; ++ // b[126] = 8270; ++ ++ try ++ { ++ Field field = EntityTypes.class.getDeclaredField("g"); ++ field.setAccessible(true); ++ entityTypes = (Map) field.get(null); ++ } ++ catch (Exception ex) ++ { ++ ex.printStackTrace(); ++ } ++ } ++} +diff --git a/src/main/java/com/mineplex/spigot/PacketProcessor.java b/src/main/java/com/mineplex/spigot/PacketProcessor.java +index 5695899..0fe6930 100644 +--- a/src/main/java/com/mineplex/spigot/PacketProcessor.java ++++ b/src/main/java/com/mineplex/spigot/PacketProcessor.java +@@ -35,6 +35,10 @@ import net.minecraft.server.PacketPlayInBlockPlace; + import net.minecraft.server.PacketPlayInSpectate; + import net.minecraft.server.PacketPlayInResourcePackStatus; + import net.minecraft.server.PacketPlayInArmAnimation; ++import net.minecraft.server.PacketPlayInLeftClick; ++import net.minecraft.server.PacketPlayInRightClick; ++import net.minecraft.server.PacketPlayInUnknownPosition; ++import net.minecraft.server.PacketPlayInUnknownFloats; + + public class PacketProcessor implements PacketListenerPlayIn, IUpdatePlayerListBox + { +@@ -93,13 +97,14 @@ public class PacketProcessor implements PacketListenerPlayIn, IUpdatePlayerListB + + public void processIncomingPacket(final Packet packet) + { +- if (!_listenedPackets.containsKey(packet.getClass())) ++ Boolean isMainThread = _listenedPackets.get(packet.getClass()); ++ if (isMainThread == null) + { + packet.a(_packetListener); + return; + } + +- if (!_packetListener.player.u().isMainThread() && _listenedPackets.get(packet.getClass())) ++ if (!_packetListener.player.u().isMainThread() && isMainThread) + { + _packetListener.player.u().postToMainThread(new Runnable() + { +@@ -243,8 +248,28 @@ public class PacketProcessor implements PacketListenerPlayIn, IUpdatePlayerListB + processIncomingPacket(packet); + } + ++ public void a(PacketPlayInUnknownFloats packet) ++ { ++ processIncomingPacket(packet); ++ } ++ ++ public void a(PacketPlayInUnknownPosition packet) ++ { ++ processIncomingPacket(packet); ++ } ++ + public void a(IChatBaseComponent packet) + { + _packetListener.a(packet); + } ++ ++ public void a(PacketPlayInLeftClick packet) ++ { ++ processIncomingPacket(packet); ++ } ++ ++ public void a(PacketPlayInRightClick packet) ++ { ++ processIncomingPacket(packet); ++ } + } +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/ChunkSection.java b/src/main/java/net/minecraft/server/ChunkSection.java +index f734ab0..3782abd 100644 +--- a/src/main/java/net/minecraft/server/ChunkSection.java ++++ b/src/main/java/net/minecraft/server/ChunkSection.java +@@ -1,5 +1,10 @@ + package net.minecraft.server; + ++import java.util.ArrayList; ++import org.apache.commons.lang3.Validate; ++import org.bukkit.craftbukkit.util.CraftMagicNumbers; ++import com.mineplex.chunk.*; ++ + public class ChunkSection { + + private int yPos; +@@ -8,6 +13,10 @@ public class ChunkSection { + private char[] blockIds; + private NibbleArray emittedLight; + private NibbleArray skyLight; ++ private static LargeBlockPalette largePalette = new LargeBlockPalette(); ++ private BlockMap blockMap; ++ private int bitshift; ++ private BlockPalette blockPalette; + + public ChunkSection(int i, boolean flag) { + this.yPos = i; +@@ -17,6 +26,7 @@ public class ChunkSection { + this.skyLight = new NibbleArray(); + } + ++ setSize(4); + } + + // CraftBukkit start +@@ -27,10 +37,72 @@ public class ChunkSection { + if (flag) { + this.skyLight = new NibbleArray(); + } ++ setSize(4); + recalcBlockCounts(); + } + // CraftBukkit end + ++ public void setSize(int newBitShift) ++ { ++ if (newBitShift == this.bitshift) ++ { ++ return; ++ } ++ this.bitshift = newBitShift; ++ if (this.bitshift <= 4) ++ { ++ this.bitshift = 4; ++ this.blockPalette = new SmallBlockPalette(this.bitshift, this); ++ } ++ else if (this.bitshift <= 8) ++ { ++ this.blockPalette = new MediumBlockPalette(this.bitshift, this); ++ } ++ else ++ { ++ this.blockPalette = largePalette; ++ this.bitshift = MathHelper.e(Block.d.a()); ++ } ++ this.blockPalette.addGetIndex(Blocks.AIR.getBlockData()); ++ this.blockMap = new BlockMap(this.bitshift, 4096); ++ } ++ ++ public int resizePalette(int newBitShift, IBlockData aqt2) ++ { ++ BlockMap blockMap = this.blockMap; ++ BlockPalette blockPalette = this.blockPalette; ++ this.setSize(newBitShift); ++ for (int i2 = 0; i2 < blockMap.b(); ++i2) ++ { ++ IBlockData aqt3 = blockPalette.getBlock(blockMap.a(i2)); ++ if (aqt3 == null) ++ continue; ++ ++ // TODO Set data ++ this.setData(i2, aqt3); ++ } ++ // Return index ++ return this.blockPalette.addGetIndex(aqt2); ++ } ++ ++ public void writeSerializer(PacketDataSerializer em2) ++ { ++ em2.writeByte(this.bitshift); ++ this.blockPalette.writeSerializer(em2); ++ em2.b(blockMap.a().length); ++ for (long l : blockMap.a()) ++ { ++ em2.writeLong(l); ++ } ++ } ++ ++ // Get dataserializer size ++ public int getLength() ++ { ++ int n2 = this.blockMap.b(); ++ return 1 + this.blockPalette.getLength() + PacketDataSerializer.a(n2) + n2 * 8; ++ } ++ + public IBlockData getType(int i, int j, int k) { + IBlockData iblockdata = (IBlockData) Block.d.a(this.blockIds[j << 8 | k << 4 | i]); + +@@ -57,8 +129,22 @@ public class ChunkSection { + } + + this.blockIds[j << 8 | k << 4 | i] = (char) Block.d.b(iblockdata); ++ setData(i, j, k, iblockdata); ++ } ++ ++ public void setData(int x, int y, int z, IBlockData blockData) ++ { ++ int bitshift = y << 8 | z << 4 | x; ++ setData(bitshift, blockData); + } + ++ // Set block bitshift, iblockdata ++ protected void setData(int n2, IBlockData aqt2) ++ { ++ int n3 = this.blockPalette.addGetIndex(aqt2); ++ this.blockMap.a(n2, n3); ++ } ++ + public Block b(int i, int j, int k) { + return this.getType(i, j, k).getBlock(); + } +@@ -100,6 +186,7 @@ public class ChunkSection { + public void recalcBlockCounts() { + this.nonEmptyBlockCount = 0; + this.tickingBlockCount = 0; ++ setData(); + + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { +@@ -122,8 +209,20 @@ public class ChunkSection { + return this.blockIds; + } + ++ private void setData() ++ { ++ for (int i = 0; i < 16; ++i) { ++ for (int j = 0; j < 16; ++j) { ++ for (int k = 0; k < 16; ++k) { ++ setData(i, j, k, getType(i, j, k)); ++ } ++ } ++ } ++ } ++ + public void a(char[] achar) { + this.blockIds = achar; ++ setData(); + } + + public NibbleArray getEmittedLightArray() { +diff --git a/src/main/java/net/minecraft/server/DataIndex.java b/src/main/java/net/minecraft/server/DataIndex.java +new file mode 100644 +index 0000000..1e9db13 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/DataIndex.java +@@ -0,0 +1,42 @@ ++package net.minecraft.server; ++ ++public class DataIndex ++{ ++ private final int a; ++ private final DataTypeInferface b; ++ ++ public DataIndex(int n2, DataTypeInferface kf2) ++ { ++ this.a = n2; ++ this.b = kf2; ++ } ++ ++ public int a() ++ { ++ return this.a; ++ } ++ ++ public DataTypeInferface b() ++ { ++ return this.b; ++ } ++ ++ public boolean equals(Object object) ++ { ++ if (this == object) ++ { ++ return true; ++ } ++ if (object == null || this.getClass() != object.getClass()) ++ { ++ return false; ++ } ++ DataIndex ke2 = (DataIndex) object; ++ return this.a == ke2.a; ++ } ++ ++ public int hashCode() ++ { ++ return this.a; ++ } ++} +diff --git a/src/main/java/net/minecraft/server/DataType.java b/src/main/java/net/minecraft/server/DataType.java +new file mode 100644 +index 0000000..a8c317d +--- /dev/null ++++ b/src/main/java/net/minecraft/server/DataType.java +@@ -0,0 +1,265 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++import java.util.UUID; ++ ++import com.google.common.base.Optional; ++import com.mineplex.chunk.PaletteMediumList; ++ ++public class DataType ++{ ++ private static final PaletteMediumList> dataTypes = new PaletteMediumList>(16); ++ ++ public static final DataTypeInferface BYTE = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Byte by) ++ { ++ em2.writeByte(by.byteValue()); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface INTEGER = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Integer n2) ++ { ++ em2.b(n2); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface FLOAT = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Float f2) ++ { ++ em2.writeFloat(f2.floatValue()); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface STRING = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, String string) ++ { ++ em2.a(string); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface ICHATBASECOMPONENT = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, IChatBaseComponent eu2) ++ { ++ try ++ { ++ em2.a(eu2); ++ } ++ catch (IOException e) ++ { ++ e.printStackTrace(); ++ } ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface> OPT_ITEMSTACK = new DataTypeInferface>() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Optional optional) ++ { ++ em2.a(optional.orNull()); ++ } ++ ++ @Override ++ public DataIndex> fromIndex(int n2) ++ { ++ return new DataIndex>(n2, this); ++ } ++ }; ++ public static final DataTypeInferface> OPT_IBLOCKDATA = new DataTypeInferface>() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Optional optional) ++ { ++ if (optional.isPresent()) ++ { ++ em2.b(Block.getCombinedId(optional.get())); ++ } ++ else ++ { ++ em2.b(0); ++ } ++ } ++ ++ @Override ++ public DataIndex> fromIndex(int n2) ++ { ++ return new DataIndex>(n2, this); ++ } ++ }; ++ public static final DataTypeInferface BOOLEAN = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Boolean bl2) ++ { ++ em2.writeBoolean(bl2); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface VECTOR3F = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Vector3f dc2) ++ { ++ em2.writeFloat(dc2.getX()); ++ em2.writeFloat(dc2.getY()); ++ em2.writeFloat(dc2.getZ()); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface BLOCKPOSITION = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, BlockPosition cj2) ++ { ++ em2.a(cj2); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface> OPT_BLOCKPOSITION = new DataTypeInferface>() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Optional optional) ++ { ++ em2.writeBoolean(optional.isPresent()); ++ if (optional.isPresent()) ++ { ++ em2.a(optional.get()); ++ } ++ } ++ ++ @Override ++ public DataIndex> fromIndex(int n2) ++ { ++ return new DataIndex>(n2, this); ++ } ++ }; ++ public static final DataTypeInferface ENUM_DIRECTION = new DataTypeInferface() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, EnumDirection cq2) ++ { ++ em2.a(cq2); ++ } ++ ++ @Override ++ public DataIndex fromIndex(int n2) ++ { ++ return new DataIndex(n2, this); ++ } ++ }; ++ public static final DataTypeInferface> OPT_UUID = new DataTypeInferface>() ++ { ++ ++ @Override ++ public void write(PacketDataSerializer em2, Optional optional) ++ { ++ em2.writeBoolean(optional.isPresent()); ++ if (optional.isPresent()) ++ { ++ em2.a(optional.get()); ++ } ++ } ++ ++ @Override ++ public DataIndex> fromIndex(int n2) ++ { ++ return new DataIndex>(n2, this); ++ } ++ }; ++ ++ public static void a(DataTypeInferface kf2) ++ { ++ dataTypes.c(kf2); ++ } ++ ++ public static DataTypeInferface a(int n2) ++ { ++ return dataTypes.get(n2); ++ } ++ ++ public static int b(DataTypeInferface kf2) ++ { ++ return dataTypes.a(kf2); ++ } ++ ++ static ++ { ++ DataType.a(BYTE); ++ DataType.a(INTEGER); ++ DataType.a(FLOAT); ++ DataType.a(STRING); ++ DataType.a(ICHATBASECOMPONENT); ++ DataType.a(OPT_ITEMSTACK); ++ DataType.a(BOOLEAN); ++ DataType.a(VECTOR3F); ++ DataType.a(BLOCKPOSITION); ++ DataType.a(OPT_BLOCKPOSITION); ++ DataType.a(ENUM_DIRECTION); ++ DataType.a(OPT_UUID); ++ DataType.a(OPT_IBLOCKDATA); ++ } ++ ++} +diff --git a/src/main/java/net/minecraft/server/DataTypeInferface.java b/src/main/java/net/minecraft/server/DataTypeInferface.java +new file mode 100644 +index 0000000..36c2eb7 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/DataTypeInferface.java +@@ -0,0 +1,8 @@ ++package net.minecraft.server; ++ ++public interface DataTypeInferface ++{ ++ public void write(PacketDataSerializer var1, T var2); ++ ++ public DataIndex fromIndex(int var1); ++} +diff --git a/src/main/java/net/minecraft/server/DataWatcher.java b/src/main/java/net/minecraft/server/DataWatcher.java +index dec091e..9e351b1 100644 +--- a/src/main/java/net/minecraft/server/DataWatcher.java ++++ b/src/main/java/net/minecraft/server/DataWatcher.java +@@ -10,6 +10,7 @@ import java.util.Map; + import java.util.concurrent.locks.ReadWriteLock; + import java.util.concurrent.locks.ReentrantReadWriteLock; + import org.apache.commons.lang3.ObjectUtils; ++import com.google.common.base.Optional; + + public class DataWatcher { + +@@ -24,12 +25,41 @@ public class DataWatcher { + // Spigot End + private boolean e; + private ReadWriteLock f = new ReentrantReadWriteLock(); ++ private static final Map, Integer> dataTypes = Maps.newHashMap(); + + public DataWatcher(Entity entity) { + this.a = entity; + } + +- public void a(int i, T t0) { ++ public static DataIndex getIndex(Class class_, DataTypeInferface kf2) ++ { ++ int n2; ++ if (dataTypes.containsKey(class_)) ++ { ++ n2 = dataTypes.get(class_) + 1; ++ } ++ else ++ { ++ int n3 = 0; ++ Class class_2 = class_; ++ while (class_2 != Entity.class) ++ { ++ if (!dataTypes.containsKey(class_2 = (Class) class_2.getSuperclass())) ++ continue; ++ n3 = dataTypes.get(class_2) + 1; ++ break; ++ } ++ n2 = n3; ++ } ++ if (n2 > 254) ++ { ++ throw new IllegalArgumentException("Data value id is too big with " + n2 + "! (Max is " + 254 + ")"); ++ } ++ dataTypes.put(class_, n2); ++ return kf2.fromIndex(n2); ++ } ++ ++ public void a(int i, T t0, DataIndex index, Y newValue) { + int integer = classToId.get(t0.getClass()); // Spigot + + if (integer == -1) { // Spigot +@@ -39,7 +69,7 @@ public class DataWatcher { + } else if (this.dataValues.containsKey(i)) { // Spigot + throw new IllegalArgumentException("Duplicate id value for " + i + "!"); + } else { +- DataWatcher.WatchableObject datawatcher_watchableobject = new DataWatcher.WatchableObject(integer, i, t0); // Spigot ++ DataWatcher.WatchableObject datawatcher_watchableobject = new DataWatcher.WatchableObject(integer, i, t0, index, newValue); // Spigot + + this.f.writeLock().lock(); + this.dataValues.put(i, datawatcher_watchableobject); // Spigot +@@ -48,8 +78,8 @@ public class DataWatcher { + } + } + +- public void add(int i, int j) { +- DataWatcher.WatchableObject datawatcher_watchableobject = new DataWatcher.WatchableObject(j, i, (Object) null); ++ public void add(int i, int j, DataIndex index, Y newValue) { ++ DataWatcher.WatchableObject datawatcher_watchableobject = new DataWatcher.WatchableObject(j, i, (Object) null, index, newValue); + + this.f.writeLock().lock(); + this.dataValues.put(i, datawatcher_watchableobject); // Spigot +@@ -104,11 +134,12 @@ public class DataWatcher { + return (Vector3f) this.j(i).b(); + } + +- public void watch(int i, T t0) { ++ public void watch(int i, T t0, DataIndex index, Y newValue) { + DataWatcher.WatchableObject datawatcher_watchableobject = this.j(i); + +- if (ObjectUtils.notEqual(t0, datawatcher_watchableobject.b())) { +- datawatcher_watchableobject.a(t0); ++ if (ObjectUtils.notEqual(t0, datawatcher_watchableobject.b()) || ObjectUtils.notEqual(newValue, datawatcher_watchableobject.getValue())) ++ { ++ datawatcher_watchableobject.a(t0, newValue); + this.a.i(i); + datawatcher_watchableobject.a(true); + this.e = true; +@@ -136,7 +167,10 @@ public class DataWatcher { + } + } + +- packetdataserializer.writeByte(127); ++ if (packetdataserializer.version == 47) ++ packetdataserializer.writeByte(127); ++ else ++ packetdataserializer.writeByte(255); + } + + public List b() { +@@ -162,6 +196,7 @@ public class DataWatcher { + datawatcher_watchableobject.c(), + datawatcher_watchableobject.a(), + ( (ItemStack) datawatcher_watchableobject.b() ).cloneItemStack() ++ , datawatcher_watchableobject.getIndex(), datawatcher_watchableobject.getValue() + ); + } + // Spigot end +@@ -188,7 +223,10 @@ public class DataWatcher { + } + + this.f.readLock().unlock(); +- packetdataserializer.writeByte(127); ++ if (packetdataserializer.version == 47) ++ packetdataserializer.writeByte(127); ++ else ++ packetdataserializer.writeByte(255); + } + + public List c() { +@@ -203,10 +241,20 @@ public class DataWatcher { + WatchableObject watchableobject = (WatchableObject) arraylist.get( i ); + if ( watchableobject.b() instanceof ItemStack ) + { ++ ItemStack itemStack = ( (ItemStack) watchableobject.b() ).cloneItemStack(); ++ Object obj2 = watchableobject.getValue(); ++ ++ if (watchableobject.getValue() instanceof ItemStack) ++ { ++ obj2 = ( (ItemStack) watchableobject.getValue() ).cloneItemStack(); ++ } ++ else if (watchableobject.getValue() instanceof Optional && ((Optional) watchableobject.getValue()).get() instanceof ItemStack) ++ { ++ obj2 = Optional.of(((Optional) watchableobject.getValue()).get().cloneItemStack()); ++ } + watchableobject = new WatchableObject( + watchableobject.c(), +- watchableobject.a(), +- ( (ItemStack) watchableobject.b() ).cloneItemStack() ++ watchableobject.a(), itemStack, watchableobject.getIndex(), obj2 + ); + arraylist.set( i, watchableobject ); + } +@@ -218,6 +266,23 @@ public class DataWatcher { + } + + private static void a(PacketDataSerializer packetdataserializer, DataWatcher.WatchableObject datawatcher_watchableobject) throws IOException { ++ if (packetdataserializer.version != 47) ++ { ++ DataIndex ke2 = datawatcher_watchableobject.getIndex(); ++ int n2 = DataType.b(ke2.b()); ++ if (n2 < 0) ++ { ++ throw new IllegalArgumentException("Unknown serializer type " + ke2.b()); ++ } ++ packetdataserializer.writeByte(ke2.a()); ++ packetdataserializer.b(n2); ++ ke2.b().write(packetdataserializer, datawatcher_watchableobject.getValue()); ++ return; ++ } ++ ++ if (datawatcher_watchableobject.a() < 0) ++ return; ++ + int i = (datawatcher_watchableobject.c() << 5 | datawatcher_watchableobject.a() & 31) & 255; + + packetdataserializer.writeByte(i); +@@ -269,7 +334,7 @@ public class DataWatcher { + public static List b(PacketDataSerializer packetdataserializer) throws IOException { + ArrayList arraylist = null; + +- for (byte b0 = packetdataserializer.readByte(); b0 != 127; b0 = packetdataserializer.readByte()) { ++ /*for (byte b0 = packetdataserializer.readByte(); b0 != 127; b0 = packetdataserializer.readByte()) { + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } +@@ -320,7 +385,7 @@ public class DataWatcher { + } + + arraylist.add(datawatcher_watchableobject); +- } ++ }*/ + + return arraylist; + } +@@ -346,26 +411,41 @@ public class DataWatcher { + // Spigot End + } + +- public static class WatchableObject { ++ public static class WatchableObject { + + private final int a; + private final int b; + private Object c; + private boolean d; ++ private DataIndex index; ++ private Y value; + +- public WatchableObject(int i, int j, Object object) { +- this.b = j; ++ public WatchableObject(int type, int oldIndex, Object object, DataIndex index, Y newValue) { ++ this.b = oldIndex; + this.c = object; +- this.a = i; ++ this.a = type; + this.d = true; ++ this.index = index; ++ this.value = newValue; + } + + public int a() { + return this.b; + } + +- public void a(Object object) { ++ public DataIndex getIndex() ++ { ++ return this.index; ++ } ++ ++ public void a(Object object, Y newValue) { + this.c = object; ++ this.value = newValue; ++ } ++ ++ public Y getValue() ++ { ++ return value; + } + + public Object b() { +diff --git a/src/main/java/net/minecraft/server/Entity.java b/src/main/java/net/minecraft/server/Entity.java +index 7165579..96d9312 100644 +--- a/src/main/java/net/minecraft/server/Entity.java ++++ b/src/main/java/net/minecraft/server/Entity.java +@@ -128,6 +128,12 @@ public abstract class Entity implements ICommandListener { + public boolean fromMobSpawner; + public void inactiveTick() { } + // Spigot end ++ ++ public static DataIndex META_ENTITYDATA = DataWatcher.getIndex(Entity.class, DataType.BYTE); ++ public static DataIndex META_AIR = DataWatcher.getIndex(Entity.class, DataType.INTEGER); ++ public static DataIndex META_CUSTOMNAME = DataWatcher.getIndex(Entity.class, DataType.STRING); ++ public static DataIndex META_CUSTOMNAME_VISIBLE = DataWatcher.getIndex(Entity.class, DataType.BOOLEAN); ++ public static DataIndex META_SILENT = DataWatcher.getIndex(Entity.class, DataType.BOOLEAN); + + public int getId() { + return this.id; +@@ -201,11 +207,11 @@ public abstract class Entity implements ICommandListener { + // Spigot end + + this.datawatcher = new DataWatcher(this); +- this.datawatcher.a(0, Byte.valueOf((byte) 0)); +- this.datawatcher.a(1, Short.valueOf((short) 300)); +- this.datawatcher.a(3, Byte.valueOf((byte) 0)); +- this.datawatcher.a(2, ""); +- this.datawatcher.a(4, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(0, Byte.valueOf((byte) 0), META_ENTITYDATA, (byte) 0); ++ this.datawatcher.a(1, Short.valueOf((short) 300), META_AIR, 300); ++ this.datawatcher.a(3, Byte.valueOf((byte) 0), META_CUSTOMNAME_VISIBLE, false); ++ this.datawatcher.a(2, "", META_CUSTOMNAME, ""); ++ this.datawatcher.a(4, Byte.valueOf((byte) 0), META_SILENT, false); + this.h(); + } + +@@ -839,7 +845,7 @@ public abstract class Entity implements ICommandListener { + } + + public void b(boolean flag) { +- this.datawatcher.watch(4, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(4, Byte.valueOf((byte) (flag ? 1 : 0)), META_SILENT, flag); + } + + protected boolean s_() { +@@ -1612,11 +1618,13 @@ public abstract class Entity implements ICommandListener { + EntityDismountEvent exitEvent1 = null; + if (this.vehicle != null) { + if ((this.bukkitEntity instanceof LivingEntity) && (entity.getBukkitEntity() instanceof Vehicle)) ++ { + exitEvent = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity); +- pluginManager.callEvent(exitEvent); ++ pluginManager.callEvent(exitEvent); + +- if (exitEvent.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) { +- return; ++ if (exitEvent.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) { ++ return; ++ } + } + + exitEvent1 = new EntityDismountEvent(this.vehicle.getBukkitEntity(), this.bukkitEntity); +@@ -1748,9 +1756,9 @@ public abstract class Entity implements ICommandListener { + byte b0 = this.datawatcher.getByte(0); + + if (flag) { +- this.datawatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << i))); ++ this.datawatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << i)), META_ENTITYDATA, (byte) (b0 | 1 << i)); + } else { +- this.datawatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << i)))); ++ this.datawatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << i))), META_ENTITYDATA, (byte) (b0 & ~(1 << i))); + } + + } +@@ -1760,7 +1768,7 @@ public abstract class Entity implements ICommandListener { + } + + public void setAirTicks(int i) { +- this.datawatcher.watch(1, Short.valueOf((short) i)); ++ this.datawatcher.watch(1, Short.valueOf((short) i), META_AIR, i); + } + + public void onLightningStrike(EntityLightning entitylightning) { +@@ -2123,7 +2131,7 @@ public abstract class Entity implements ICommandListener { + s = s.substring(0, 256); + } + // CraftBukkit end +- this.datawatcher.watch(2, s); ++ this.datawatcher.watch(2, s, META_CUSTOMNAME, s); + } + + public String getCustomName() { +@@ -2135,7 +2143,7 @@ public abstract class Entity implements ICommandListener { + } + + public void setCustomNameVisible(boolean flag) { +- this.datawatcher.watch(3, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(3, Byte.valueOf((byte) (flag ? 1 : 0)), META_CUSTOMNAME_VISIBLE, flag); + } + + public boolean getCustomNameVisible() { +diff --git a/src/main/java/net/minecraft/server/EntityAgeable.java b/src/main/java/net/minecraft/server/EntityAgeable.java +index 09d4335..5359cc1 100644 +--- a/src/main/java/net/minecraft/server/EntityAgeable.java ++++ b/src/main/java/net/minecraft/server/EntityAgeable.java +@@ -1,5 +1,8 @@ + package net.minecraft.server; + ++import com.google.common.base.Optional; ++import java.util.UUID; ++ + public abstract class EntityAgeable extends EntityCreature { + + protected int a; +@@ -8,7 +11,8 @@ public abstract class EntityAgeable extends EntityCreature { + private float bm = -1.0F; + private float bn; + public boolean ageLocked = false; // CraftBukkit +- ++ public static DataIndex META_BABY = DataWatcher.getIndex(EntityAgeable.class, DataType.BOOLEAN); ++ + // Spigot start + @Override + public void inactiveTick() +@@ -76,7 +80,7 @@ public abstract class EntityAgeable extends EntityCreature { + + protected void h() { + super.h(); +- this.datawatcher.a(12, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(12, Byte.valueOf((byte) 0), META_BABY, false); + } + + public int getAge() { +@@ -116,7 +120,7 @@ public abstract class EntityAgeable extends EntityCreature { + } + + public void setAgeRaw(int i) { +- this.datawatcher.watch(12, Byte.valueOf((byte) MathHelper.clamp(i, -1, 1))); ++ this.datawatcher.watch(12, Byte.valueOf((byte) MathHelper.clamp(i, -1, 1)), META_BABY, i < 0); + this.a = i; + this.a(this.isBaby()); + } +diff --git a/src/main/java/net/minecraft/server/EntityArmorStand.java b/src/main/java/net/minecraft/server/EntityArmorStand.java +index cd57d69..3957d4d 100644 +--- a/src/main/java/net/minecraft/server/EntityArmorStand.java ++++ b/src/main/java/net/minecraft/server/EntityArmorStand.java +@@ -30,6 +30,13 @@ public class EntityArmorStand extends EntityLiving { + public Vector3f rightArmPose; + public Vector3f leftLegPose; + public Vector3f rightLegPose; ++ public static DataIndex META_ARMOR_OPTION = DataWatcher.getIndex(EntityArmorStand.class, DataType.BYTE); ++ public static DataIndex META_HEAD_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); ++ public static DataIndex META_BODY_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); ++ public static DataIndex META_LEFT_ARM_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); ++ public static DataIndex META_RIGHT_ARM_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); ++ public static DataIndex META_LEFT_LEG_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); ++ public static DataIndex META_RIGHT_LEG_POSE = DataWatcher.getIndex(EntityArmorStand.class, DataType.VECTOR3F); + + public EntityArmorStand(World world) { + super(world); +@@ -56,13 +63,13 @@ public class EntityArmorStand extends EntityLiving { + + protected void h() { + super.h(); +- this.datawatcher.a(10, Byte.valueOf((byte) 0)); +- this.datawatcher.a(11, EntityArmorStand.a); +- this.datawatcher.a(12, EntityArmorStand.b); +- this.datawatcher.a(13, EntityArmorStand.c); +- this.datawatcher.a(14, EntityArmorStand.d); +- this.datawatcher.a(15, EntityArmorStand.e); +- this.datawatcher.a(16, EntityArmorStand.f); ++ this.datawatcher.a(10, Byte.valueOf((byte) 0), META_ARMOR_OPTION, (byte) 0); ++ this.datawatcher.a(11, EntityArmorStand.a, META_HEAD_POSE, EntityArmorStand.a); ++ this.datawatcher.a(12, EntityArmorStand.b, META_BODY_POSE, EntityArmorStand.a); ++ this.datawatcher.a(13, EntityArmorStand.c, META_LEFT_ARM_POSE, EntityArmorStand.a); ++ this.datawatcher.a(14, EntityArmorStand.d, META_RIGHT_ARM_POSE, EntityArmorStand.a); ++ this.datawatcher.a(15, EntityArmorStand.e, META_LEFT_LEG_POSE, EntityArmorStand.a); ++ this.datawatcher.a(16, EntityArmorStand.f, META_RIGHT_LEG_POSE, EntityArmorStand.a); + } + + public ItemStack bA() { +@@ -591,7 +598,7 @@ public class EntityArmorStand extends EntityLiving { + b0 &= -2; + } + +- this.datawatcher.watch(10, Byte.valueOf(b0)); ++ this.datawatcher.watch(10, Byte.valueOf(b0), META_ARMOR_OPTION, b0); + } + + public boolean isSmall() { +@@ -607,7 +614,7 @@ public class EntityArmorStand extends EntityLiving { + b0 &= -3; + } + +- this.datawatcher.watch(10, Byte.valueOf(b0)); ++ this.datawatcher.watch(10, Byte.valueOf(b0), META_ARMOR_OPTION, b0); + } + + public boolean hasGravity() { +@@ -623,7 +630,7 @@ public class EntityArmorStand extends EntityLiving { + b0 &= -5; + } + +- this.datawatcher.watch(10, Byte.valueOf(b0)); ++ this.datawatcher.watch(10, Byte.valueOf(b0), META_ARMOR_OPTION, b0); + } + + public boolean hasArms() { +@@ -639,7 +646,7 @@ public class EntityArmorStand extends EntityLiving { + b0 &= -9; + } + +- this.datawatcher.watch(10, Byte.valueOf(b0)); ++ this.datawatcher.watch(10, Byte.valueOf(b0), META_ARMOR_OPTION, b0); + } + + public boolean hasBasePlate() { +@@ -656,7 +663,7 @@ public class EntityArmorStand extends EntityLiving { + b0 &= -17; + } + +- this.datawatcher.watch(10, Byte.valueOf(b0)); ++ this.datawatcher.watch(10, Byte.valueOf(b0), META_ARMOR_OPTION, b0); + } + + // PAIL +@@ -666,32 +673,32 @@ public class EntityArmorStand extends EntityLiving { + + public void setHeadPose(Vector3f vector3f) { + this.headPose = vector3f; +- this.datawatcher.watch(11, vector3f); ++ this.datawatcher.watch(11, vector3f, META_HEAD_POSE, vector3f); + } + + public void setBodyPose(Vector3f vector3f) { + this.bodyPose = vector3f; +- this.datawatcher.watch(12, vector3f); ++ this.datawatcher.watch(12, vector3f, META_BODY_POSE, vector3f); + } + + public void setLeftArmPose(Vector3f vector3f) { + this.leftArmPose = vector3f; +- this.datawatcher.watch(13, vector3f); ++ this.datawatcher.watch(13, vector3f, META_LEFT_ARM_POSE, vector3f); + } + + public void setRightArmPose(Vector3f vector3f) { + this.rightArmPose = vector3f; +- this.datawatcher.watch(14, vector3f); ++ this.datawatcher.watch(14, vector3f, META_RIGHT_ARM_POSE, vector3f); + } + + public void setLeftLegPose(Vector3f vector3f) { + this.leftLegPose = vector3f; +- this.datawatcher.watch(15, vector3f); ++ this.datawatcher.watch(15, vector3f, META_LEFT_LEG_POSE, vector3f); + } + + public void setRightLegPose(Vector3f vector3f) { + this.rightLegPose = vector3f; +- this.datawatcher.watch(16, vector3f); ++ this.datawatcher.watch(16, vector3f, META_RIGHT_LEG_POSE, vector3f); + } + + public Vector3f t() { +diff --git a/src/main/java/net/minecraft/server/EntityArrow.java b/src/main/java/net/minecraft/server/EntityArrow.java +index 3a80776..11bcdbc 100644 +--- a/src/main/java/net/minecraft/server/EntityArrow.java ++++ b/src/main/java/net/minecraft/server/EntityArrow.java +@@ -23,6 +23,7 @@ public class EntityArrow extends Entity implements IProjectile { + private int as; + private double damage = 2.0D; + public int knockbackStrength; ++ public static DataIndex META_CRITICAL = DataWatcher.getIndex(EntityArrow.class, DataType.BYTE); + + // Spigot Start + @Override +@@ -99,7 +100,7 @@ public class EntityArrow extends Entity implements IProjectile { + } + + protected void h() { +- this.datawatcher.a(16, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(16, Byte.valueOf((byte) 0), META_CRITICAL, (byte) 0); + } + + public void shoot(double d0, double d1, double d2, float f, float f1) { +@@ -468,9 +469,9 @@ public class EntityArrow extends Entity implements IProjectile { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1)), META_CRITICAL, (byte) (b0 | 1)); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2)), META_CRITICAL, (byte) (b0 | 1)); + } + + } +diff --git a/src/main/java/net/minecraft/server/EntityBat.java b/src/main/java/net/minecraft/server/EntityBat.java +index c078fa6..addf413 100644 +--- a/src/main/java/net/minecraft/server/EntityBat.java ++++ b/src/main/java/net/minecraft/server/EntityBat.java +@@ -6,6 +6,7 @@ public class EntityBat extends EntityAmbient { + + private BlockPosition a; + private boolean _vegetated; ++ public static DataIndex META_UPSIDEDOWN = DataWatcher.getIndex(EntityBat.class, DataType.BYTE); + + public EntityBat(World world) { + super(world); +@@ -25,7 +26,7 @@ public class EntityBat extends EntityAmbient { + + protected void h() { + super.h(); +- this.datawatcher.a(16, new Byte((byte) 0)); ++ this.datawatcher.a(16, new Byte((byte) 0), META_UPSIDEDOWN, (byte) 0); + } + + protected float bB() { +@@ -70,9 +71,9 @@ public class EntityBat extends EntityAmbient { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1)), META_UPSIDEDOWN, Byte.valueOf((byte) (b0 | 1))); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2)), META_UPSIDEDOWN, Byte.valueOf((byte) (b0 & -2))); + } + + } +@@ -169,7 +170,7 @@ public class EntityBat extends EntityAmbient { + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); +- this.datawatcher.watch(16, Byte.valueOf(nbttagcompound.getByte("BatFlags"))); ++ this.datawatcher.watch(16, Byte.valueOf(nbttagcompound.getByte("BatFlags")), META_UPSIDEDOWN, Byte.valueOf(nbttagcompound.getByte("BatFlags"))); + } + + public void b(NBTTagCompound nbttagcompound) { +diff --git a/src/main/java/net/minecraft/server/EntityBlaze.java b/src/main/java/net/minecraft/server/EntityBlaze.java +index a759e00..b596e3c 100644 +--- a/src/main/java/net/minecraft/server/EntityBlaze.java ++++ b/src/main/java/net/minecraft/server/EntityBlaze.java +@@ -4,6 +4,7 @@ public class EntityBlaze extends EntityMonster { + + private float a = 0.5F; + private int b; ++ public static DataIndex META_FIRE = DataWatcher.getIndex(EntityBlaze.class, DataType.BYTE); + + public EntityBlaze(World world) { + super(world); +@@ -27,7 +28,7 @@ public class EntityBlaze extends EntityMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, new Byte((byte) 0)); ++ this.datawatcher.a(16, new Byte((byte) 0), META_FIRE, (byte) 0); + } + + protected String z() { +@@ -119,7 +120,7 @@ public class EntityBlaze extends EntityMonster { + b0 &= -2; + } + +- this.datawatcher.watch(16, Byte.valueOf(b0)); ++ this.datawatcher.watch(16, Byte.valueOf(b0), META_FIRE, b0); + } + + protected boolean n_() { +diff --git a/src/main/java/net/minecraft/server/EntityBoat.java b/src/main/java/net/minecraft/server/EntityBoat.java +index f6a43c0..a9ddd00 100644 +--- a/src/main/java/net/minecraft/server/EntityBoat.java ++++ b/src/main/java/net/minecraft/server/EntityBoat.java +@@ -29,6 +29,11 @@ public class EntityBoat extends Entity { + public double unoccupiedDeceleration = -1; + public boolean landBoats = false; + ++ public static DataIndex META_TIME_SINCE_HIT = DataWatcher.getIndex(EntityBoat.class, DataType.INTEGER); ++ public static DataIndex META_FORWARD_DIRECTION = DataWatcher.getIndex(EntityBoat.class, DataType.INTEGER); ++ public static DataIndex META_DAMAGE_TAKEN = DataWatcher.getIndex(EntityBoat.class, DataType.FLOAT); ++ public static DataIndex META_UNKNOWN_INTEGER = DataWatcher.getIndex(EntityBoat.class, DataType.INTEGER); ++ public static DataIndex[] META_UNKNOWN_FLOATS = new DataIndex[] { DataWatcher.getIndex(EntityBoat.class, DataType.FLOAT), DataWatcher.getIndex(EntityBoat.class, DataType.FLOAT), DataWatcher.getIndex(EntityBoat.class, DataType.FLOAT)}; + @Override + public void collide(Entity entity) { + org.bukkit.entity.Entity hitEntity = (entity == null) ? null : entity.getBukkitEntity(); +@@ -57,9 +62,14 @@ public class EntityBoat extends Entity { + } + + protected void h() { +- this.datawatcher.a(17, new Integer(0)); +- this.datawatcher.a(18, new Integer(1)); +- this.datawatcher.a(19, new Float(0.0F)); ++ this.datawatcher.a(17, new Integer(0), META_TIME_SINCE_HIT, 0); ++ this.datawatcher.a(18, new Integer(1), META_FORWARD_DIRECTION, 1); ++ this.datawatcher.a(19, new Float(0.0F), META_DAMAGE_TAKEN, 0F); ++ this.datawatcher.a(-10, 0, META_UNKNOWN_INTEGER, 0); ++ for (int i=0; i<3; i++) ++ { ++ this.datawatcher.a(-15 + i, 0F, META_UNKNOWN_FLOATS[i], 0F); ++ } + } + + public AxisAlignedBB j(Entity entity) { +@@ -473,7 +483,7 @@ public class EntityBoat extends Entity { + } + + public void setDamage(float f) { +- this.datawatcher.watch(19, Float.valueOf(f)); ++ this.datawatcher.watch(19, Float.valueOf(f), META_DAMAGE_TAKEN, f); + } + + public float j() { +@@ -481,7 +491,7 @@ public class EntityBoat extends Entity { + } + + public void a(int i) { +- this.datawatcher.watch(17, Integer.valueOf(i)); ++ this.datawatcher.watch(17, Integer.valueOf(i), META_TIME_SINCE_HIT, i); + } + + public int l() { +@@ -489,7 +499,7 @@ public class EntityBoat extends Entity { + } + + public void b(int i) { +- this.datawatcher.watch(18, Integer.valueOf(i)); ++ this.datawatcher.watch(18, Integer.valueOf(i), META_FORWARD_DIRECTION, i); + } + + public int m() { +diff --git a/src/main/java/net/minecraft/server/EntityCreeper.java b/src/main/java/net/minecraft/server/EntityCreeper.java +index fecf94d..6ac9be8 100644 +--- a/src/main/java/net/minecraft/server/EntityCreeper.java ++++ b/src/main/java/net/minecraft/server/EntityCreeper.java +@@ -13,6 +13,9 @@ public class EntityCreeper extends EntityMonster { + private int explosionRadius = 3; + private int bn = 0; + private int record = -1; // CraftBukkit ++ public static DataIndex META_FUSE_STATE = DataWatcher.getIndex(EntityCreeper.class, DataType.INTEGER); ++ public static DataIndex META_POWERED = DataWatcher.getIndex(EntityCreeper.class, DataType.BOOLEAN); ++ public static DataIndex META_IGNITED = DataWatcher.getIndex(EntityCreeper.class, DataType.BOOLEAN); + + public EntityCreeper(World world) { + super(world); +@@ -47,9 +50,9 @@ public class EntityCreeper extends EntityMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) -1)); +- this.datawatcher.a(17, Byte.valueOf((byte) 0)); +- this.datawatcher.a(18, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(16, Byte.valueOf((byte) -1), META_FUSE_STATE, -1); ++ this.datawatcher.a(17, Byte.valueOf((byte) 0), META_POWERED, false); ++ this.datawatcher.a(18, Byte.valueOf((byte) 0), META_IGNITED, false); + } + + public void b(NBTTagCompound nbttagcompound) { +@@ -65,7 +68,7 @@ public class EntityCreeper extends EntityMonster { + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); +- this.datawatcher.watch(17, Byte.valueOf((byte) (nbttagcompound.getBoolean("powered") ? 1 : 0))); ++ this.datawatcher.watch(17, Byte.valueOf((byte) (nbttagcompound.getBoolean("powered") ? 1 : 0)), META_POWERED, nbttagcompound.getBoolean("powered")); + if (nbttagcompound.hasKeyOfType("Fuse", 99)) { + this.maxFuseTicks = nbttagcompound.getShort("Fuse"); + } +@@ -167,7 +170,7 @@ public class EntityCreeper extends EntityMonster { + } + + public void a(int i) { +- this.datawatcher.watch(16, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(16, Byte.valueOf((byte) i), META_FUSE_STATE, i); + } + + public void onLightningStrike(EntityLightning entitylightning) { +@@ -182,9 +185,9 @@ public class EntityCreeper extends EntityMonster { + + public void setPowered(boolean powered) { + if (!powered) { +- this.datawatcher.watch(17, Byte.valueOf((byte) 0)); ++ this.datawatcher.watch(17, Byte.valueOf((byte) 0), META_POWERED, powered); + } else { +- this.datawatcher.watch(17, Byte.valueOf((byte) 1)); ++ this.datawatcher.watch(17, Byte.valueOf((byte) 1), META_POWERED, powered); + } + // CraftBukkit end + } +@@ -228,7 +231,7 @@ public class EntityCreeper extends EntityMonster { + } + + public void co() { +- this.datawatcher.watch(18, Byte.valueOf((byte) 1)); ++ this.datawatcher.watch(18, Byte.valueOf((byte) 1), META_IGNITED, true); + } + + public boolean cp() { +diff --git a/src/main/java/net/minecraft/server/EntityEnderCrystal.java b/src/main/java/net/minecraft/server/EntityEnderCrystal.java +index 07533e4..ddd1a0e 100644 +--- a/src/main/java/net/minecraft/server/EntityEnderCrystal.java ++++ b/src/main/java/net/minecraft/server/EntityEnderCrystal.java +@@ -4,11 +4,14 @@ package net.minecraft.server; + import org.bukkit.craftbukkit.event.CraftEventFactory; + import org.bukkit.event.entity.ExplosionPrimeEvent; + // CraftBukkit end ++import com.google.common.base.Optional; + + public class EntityEnderCrystal extends Entity { + + public int a; + public int b; ++ public static DataIndex> META_BLOCK_POSITION = DataWatcher.getIndex(EntityEnderCrystal.class, DataType.OPT_BLOCKPOSITION); ++ public static DataIndex META_STAND = DataWatcher.getIndex(EntityEnderCrystal.class, DataType.BOOLEAN); + + public EntityEnderCrystal(World world) { + super(world); +@@ -23,7 +26,8 @@ public class EntityEnderCrystal extends Entity { + } + + protected void h() { +- this.datawatcher.a(8, Integer.valueOf(this.b)); ++ this.datawatcher.a(8, Integer.valueOf(this.b), META_BLOCK_POSITION, Optional. absent()); ++ this.datawatcher.a(-2, (byte) 1, META_STAND, true); + } + + public void t_() { +@@ -31,10 +35,10 @@ public class EntityEnderCrystal extends Entity { + this.lastY = this.locY; + this.lastZ = this.locZ; + ++this.a; +- this.datawatcher.watch(8, Integer.valueOf(this.b)); + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY); + int k = MathHelper.floor(this.locZ); ++ this.datawatcher.watch(8, Integer.valueOf(this.b), META_BLOCK_POSITION, Optional.of(new BlockPosition(i, j, k))); + + if (this.world.worldProvider instanceof WorldProviderTheEnd && this.world.getType(new BlockPosition(i, j, k)).getBlock() != Blocks.FIRE) { + // CraftBukkit start +diff --git a/src/main/java/net/minecraft/server/EntityEnderDragon.java b/src/main/java/net/minecraft/server/EntityEnderDragon.java +index ed7f549..2198042 100644 +--- a/src/main/java/net/minecraft/server/EntityEnderDragon.java ++++ b/src/main/java/net/minecraft/server/EntityEnderDragon.java +@@ -39,6 +39,7 @@ public class EntityEnderDragon extends EntityInsentient implements IComplex, IMo + public int by; + public EntityEnderCrystal bz; + private Explosion explosionSource = new Explosion(null, this, Double.NaN, Double.NaN, Double.NaN, Float.NaN, true, true); // CraftBukkit - reusable source for CraftTNTPrimed.getSource() ++ public static DataIndex META_UNKNOWN_INTEGER = DataWatcher.getIndex(EntityEnderDragon.class, DataType.INTEGER); + + public EntityEnderDragon(World world) { + super(world); +diff --git a/src/main/java/net/minecraft/server/EntityEnderman.java b/src/main/java/net/minecraft/server/EntityEnderman.java +index a250062..5c09068 100644 +--- a/src/main/java/net/minecraft/server/EntityEnderman.java ++++ b/src/main/java/net/minecraft/server/EntityEnderman.java +@@ -7,6 +7,7 @@ import java.util.List; + import java.util.Random; + import java.util.Set; + import java.util.UUID; ++import com.google.common.base.Optional; + + // CraftBukkit start + import org.bukkit.Location; +@@ -20,6 +21,8 @@ public class EntityEnderman extends EntityMonster { + private static final AttributeModifier b = (new AttributeModifier(EntityEnderman.a, "Attacking speed boost", 0.15000000596046448D, 0)).a(false); + private static final Set c = Sets.newIdentityHashSet(); + private boolean bm; ++ public static DataIndex> META_BLOCK = DataWatcher.getIndex(EntityEnderman.class, DataType.OPT_IBLOCKDATA); ++ public static DataIndex META_ANGRY = DataWatcher.getIndex(EntityEnderman.class, DataType.BOOLEAN); + + public EntityEnderman(World world) { + super(world); +@@ -55,9 +58,9 @@ public class EntityEnderman extends EntityMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, new Short((short) 0)); +- this.datawatcher.a(17, new Byte((byte) 0)); +- this.datawatcher.a(18, new Byte((byte) 0)); ++ this.datawatcher.a(16, new Short((short) 0), META_BLOCK, Optional. absent()); ++ this.datawatcher.a(17, new Byte((byte) 0), META_BLOCK, Optional. absent()); ++ this.datawatcher.a(18, new Byte((byte) 0), META_ANGRY, false); + } + + public void b(NBTTagCompound nbttagcompound) { +@@ -254,7 +257,7 @@ public class EntityEnderman extends EntityMonster { + } + + public void setCarried(IBlockData iblockdata) { +- this.datawatcher.watch(16, Short.valueOf((short) (Block.getCombinedId(iblockdata) & '\uffff'))); ++ this.datawatcher.watch(16, Short.valueOf((short) (Block.getCombinedId(iblockdata) & '\uffff')), META_BLOCK, Optional. fromNullable(iblockdata)); + } + + public IBlockData getCarried() { +@@ -306,7 +309,7 @@ public class EntityEnderman extends EntityMonster { + } + + public void a(boolean flag) { +- this.datawatcher.watch(18, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(18, Byte.valueOf((byte) (flag ? 1 : 0)), META_ANGRY, flag); + } + + static { +diff --git a/src/main/java/net/minecraft/server/EntityFireworks.java b/src/main/java/net/minecraft/server/EntityFireworks.java +index d7be6c2..c918c5f 100644 +--- a/src/main/java/net/minecraft/server/EntityFireworks.java ++++ b/src/main/java/net/minecraft/server/EntityFireworks.java +@@ -1,9 +1,12 @@ + package net.minecraft.server; + ++import com.google.common.base.Optional; ++ + public class EntityFireworks extends Entity { + + private int ticksFlown; + public int expectedLifespan; ++ private final DataIndex> META_ITEM = DataWatcher.getIndex(EntityFireworks.class, DataType.OPT_ITEMSTACK); + + // Spigot Start + @Override +@@ -20,7 +23,7 @@ public class EntityFireworks extends Entity { + } + + protected void h() { +- this.datawatcher.add(8, 5); ++ this.datawatcher.add(8, 5, META_ITEM, Optional. absent()); + } + + public EntityFireworks(World world, double d0, double d1, double d2, ItemStack itemstack) { +@@ -31,7 +34,7 @@ public class EntityFireworks extends Entity { + int i = 1; + + if (itemstack != null && itemstack.hasTag()) { +- this.datawatcher.watch(8, itemstack); ++ this.datawatcher.watch(8, itemstack, META_ITEM, Optional.of(itemstack)); + NBTTagCompound nbttagcompound = itemstack.getTag(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Fireworks"); + +@@ -116,12 +119,17 @@ public class EntityFireworks extends Entity { + ItemStack itemstack = ItemStack.createStack(nbttagcompound1); + + if (itemstack != null) { +- this.datawatcher.watch(8, itemstack); ++ this.datawatcher.watch(8, itemstack, META_ITEM, Optional.of(itemstack)); + } + } + + } + ++ public void setFireworkItem(ItemStack item) ++ { ++ this.datawatcher.watch(8, item, META_ITEM, Optional.of(item)); ++ } ++ + public float c(float f) { + return super.c(f); + } +diff --git a/src/main/java/net/minecraft/server/EntityGhast.java b/src/main/java/net/minecraft/server/EntityGhast.java +index 51608e9..e098e2b 100644 +--- a/src/main/java/net/minecraft/server/EntityGhast.java ++++ b/src/main/java/net/minecraft/server/EntityGhast.java +@@ -5,6 +5,7 @@ import java.util.Random; + public class EntityGhast extends EntityFlying implements IMonster { + + private int a = 1; ++ public static DataIndex META_ANGRY = DataWatcher.getIndex(EntityGhast.class, DataType.BOOLEAN); + + public EntityGhast(World world) { + super(world); +@@ -19,7 +20,7 @@ public class EntityGhast extends EntityFlying implements IMonster { + } + + public void a(boolean flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (flag ? 1 : 0)), META_ANGRY, flag); + } + + public int cf() { +@@ -48,7 +49,7 @@ public class EntityGhast extends EntityFlying implements IMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(16, Byte.valueOf((byte) 0), META_ANGRY, false); + } + + protected void initAttributes() { +diff --git a/src/main/java/net/minecraft/server/EntityGuardian.java b/src/main/java/net/minecraft/server/EntityGuardian.java +index c14caf2..3b46302 100644 +--- a/src/main/java/net/minecraft/server/EntityGuardian.java ++++ b/src/main/java/net/minecraft/server/EntityGuardian.java +@@ -5,6 +5,17 @@ import java.util.*; + + public class EntityGuardian extends EntityMonster + { ++ private float a; ++ private float b; ++ private float c; ++ private float bm; ++ private float bn; ++ private EntityLiving bo; ++ private int bp; ++ private boolean bq; ++ public PathfinderGoalRandomStroll goalRandomStroll; ++ public static DataIndex META_ELDER = DataWatcher.getIndex(EntityGuardian.class, DataType.BYTE); ++ public static DataIndex META_TARGET = DataWatcher.getIndex(EntityGuardian.class, DataType.INTEGER); + static class ControllerMoveGuardian extends ControllerMove + { + +@@ -203,8 +214,8 @@ public class EntityGuardian extends EntityMonster + protected void h() + { + super.h(); +- datawatcher.a(16, Integer.valueOf(0)); +- datawatcher.a(17, Integer.valueOf(0)); ++ datawatcher.a(16, Integer.valueOf(0), META_ELDER, (byte) 0); ++ datawatcher.a(17, Integer.valueOf(0), META_TARGET, 0); + } + + private boolean a(int j) +@@ -216,9 +227,9 @@ public class EntityGuardian extends EntityMonster + { + int k = datawatcher.getInt(16); + if(flag) +- datawatcher.watch(16, Integer.valueOf(k | j)); ++ datawatcher.watch(16, Integer.valueOf(k | j), META_ELDER, (byte) (k | j)); + else +- datawatcher.watch(16, Integer.valueOf(k & ~j)); ++ datawatcher.watch(16, Integer.valueOf(k & ~j), META_TARGET, Integer.valueOf(k & ~j)); + } + + public boolean n() +@@ -257,7 +268,7 @@ public class EntityGuardian extends EntityMonster + + private void b(int j) + { +- datawatcher.watch(17, Integer.valueOf(j)); ++ datawatcher.watch(17, Integer.valueOf(j), META_TARGET, j); + } + + public boolean cp() +@@ -577,14 +588,4 @@ public class EntityGuardian extends EntityMonster + { + entityguardian.l(flag); + } +- +- private float a; +- private float b; +- private float c; +- private float bm; +- private float bn; +- private EntityLiving bo; +- private int bp; +- private boolean bq; +- public PathfinderGoalRandomStroll goalRandomStroll; + } +diff --git a/src/main/java/net/minecraft/server/EntityHorse.java b/src/main/java/net/minecraft/server/EntityHorse.java +index f293118..00ba9ac 100644 +--- a/src/main/java/net/minecraft/server/EntityHorse.java ++++ b/src/main/java/net/minecraft/server/EntityHorse.java +@@ -3,6 +3,8 @@ package net.minecraft.server; + import com.google.common.base.Predicate; + import java.util.Iterator; + import java.util.List; ++import java.util.UUID; ++import com.google.common.base.Optional; + + import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; // CraftBukkit + +@@ -47,6 +49,11 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + private String[] bP = new String[3]; + private boolean bQ = false; + public int maxDomestication = 100; // CraftBukkit - store max domestication value ++ public static DataIndex META_HORSE_STATE = DataWatcher.getIndex(EntityHorse.class, DataType.BYTE); ++ public static DataIndex META_TYPE = DataWatcher.getIndex(EntityHorse.class, DataType.INTEGER); ++ public static DataIndex META_VARIANT = DataWatcher.getIndex(EntityHorse.class, DataType.INTEGER); ++ public static DataIndex> META_OWNER = DataWatcher.getIndex(EntityHorse.class, DataType.OPT_UUID); ++ public static DataIndex META_ARMOR = DataWatcher.getIndex(EntityHorse.class, DataType.INTEGER); + + public EntityHorse(World world) { + super(world); +@@ -67,15 +74,15 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Integer.valueOf(0)); +- this.datawatcher.a(19, Byte.valueOf((byte) 0)); +- this.datawatcher.a(20, Integer.valueOf(0)); +- this.datawatcher.a(21, String.valueOf("")); +- this.datawatcher.a(22, Integer.valueOf(0)); ++ this.datawatcher.a(16, Integer.valueOf(0), META_HORSE_STATE, (byte) 0); ++ this.datawatcher.a(19, Byte.valueOf((byte) 0), META_TYPE, 0); ++ this.datawatcher.a(20, Integer.valueOf(0), META_VARIANT, 0); ++ this.datawatcher.a(21, String.valueOf(""), META_OWNER, Optional. absent()); ++ this.datawatcher.a(22, Integer.valueOf(0), META_ARMOR, 0); + } + + public void setType(int i) { +- this.datawatcher.watch(19, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(19, Byte.valueOf((byte) i), META_TYPE, i); + this.dc(); + } + +@@ -84,7 +91,7 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + } + + public void setVariant(int i) { +- this.datawatcher.watch(20, Integer.valueOf(i)); ++ this.datawatcher.watch(20, Integer.valueOf(i), META_VARIANT, i); + this.dc(); + } + +@@ -129,9 +136,9 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + return; + + if (flag) { +- this.datawatcher.watch(16, Integer.valueOf(j | i)); ++ this.datawatcher.watch(16, Integer.valueOf(j | i), META_HORSE_STATE, (byte) (j | i)); + } else { +- this.datawatcher.watch(16, Integer.valueOf(j & ~i)); ++ this.datawatcher.watch(16, Integer.valueOf(j & ~i), META_HORSE_STATE, (byte) (j & ~i)); + } + + } +@@ -153,7 +160,7 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + } + + public void setOwnerUUID(String s) { +- this.datawatcher.watch(21, s); ++ this.datawatcher.watch(21, s, META_OWNER, Optional.of(UUID.fromString(s))); + } + + public float cu() { +@@ -227,7 +234,7 @@ public class EntityHorse extends EntityAnimal implements IInventoryListener { + } + + public void e(ItemStack itemstack) { +- this.datawatcher.watch(22, Integer.valueOf(this.f(itemstack))); ++ this.datawatcher.watch(22, Integer.valueOf(this.f(itemstack)), META_ARMOR, Integer.valueOf(this.f(itemstack))); + this.dc(); + } + +diff --git a/src/main/java/net/minecraft/server/EntityHuman.java b/src/main/java/net/minecraft/server/EntityHuman.java +index 66c3d0c..5294c66 100644 +--- a/src/main/java/net/minecraft/server/EntityHuman.java ++++ b/src/main/java/net/minecraft/server/EntityHuman.java +@@ -60,6 +60,10 @@ public abstract class EntityHuman extends EntityLiving { + private final GameProfile bH; + private boolean bI = false; + public EntityFishingHook hookedFish; ++ public static DataIndex META_SCALED_HEALTH = DataWatcher.getIndex(EntityHuman.class, DataType.FLOAT); ++ public static DataIndex META_SCORE = DataWatcher.getIndex(EntityHuman.class, DataType.INTEGER); ++ public static DataIndex META_SKIN = DataWatcher.getIndex(EntityHuman.class, DataType.BYTE); ++ public static DataIndex META_CAPE = DataWatcher.getIndex(EntityHuman.class, DataType.BYTE); + + // CraftBukkit start + public boolean fauxSleeping; +@@ -93,10 +97,10 @@ public abstract class EntityHuman extends EntityLiving { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) 0)); +- this.datawatcher.a(17, Float.valueOf(0.0F)); +- this.datawatcher.a(18, Integer.valueOf(0)); +- this.datawatcher.a(10, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(17, Float.valueOf(0.0F), META_SCALED_HEALTH, 0F); ++ this.datawatcher.a(18, Integer.valueOf(0), META_SCORE, 0); ++ this.datawatcher.a(10, Byte.valueOf((byte) 0), META_SKIN, (byte) 0); ++ this.datawatcher.a(16, Byte.valueOf((byte) 0), META_CAPE, (byte) 1); + } + + public boolean bS() { +@@ -453,13 +457,13 @@ public abstract class EntityHuman extends EntityLiving { + } + + public void setScore(int i) { +- this.datawatcher.watch(18, Integer.valueOf(i)); ++ this.datawatcher.watch(18, Integer.valueOf(i), META_SCORE, i); + } + + public void addScore(int i) { + int j = this.getScore(); + +- this.datawatcher.watch(18, Integer.valueOf(j + i)); ++ this.datawatcher.watch(18, Integer.valueOf(j + i), META_SCORE, j + i); + } + + public void die(DamageSource damagesource) { +@@ -1614,7 +1618,7 @@ public abstract class EntityHuman extends EntityLiving { + + this.f = entityhuman.f; + this.enderChest = entityhuman.enderChest; +- this.getDataWatcher().watch(10, Byte.valueOf(entityhuman.getDataWatcher().getByte(10))); ++ this.getDataWatcher().watch(10, Byte.valueOf(entityhuman.getDataWatcher().getByte(10)), META_SKIN, entityhuman.getDataWatcher().getByte(10)); + } + + protected boolean s_() { +@@ -1692,7 +1696,7 @@ public abstract class EntityHuman extends EntityLiving { + f = 0.0F; + } + +- this.getDataWatcher().watch(17, Float.valueOf(f)); ++ this.getDataWatcher().watch(17, Float.valueOf(f), META_SCALED_HEALTH, f); + } + + public float getAbsorptionHearts() { +diff --git a/src/main/java/net/minecraft/server/EntityInsentient.java b/src/main/java/net/minecraft/server/EntityInsentient.java +index b7647bc..c3d5378 100644 +--- a/src/main/java/net/minecraft/server/EntityInsentient.java ++++ b/src/main/java/net/minecraft/server/EntityInsentient.java +@@ -38,6 +38,8 @@ public abstract class EntityInsentient extends EntityLiving { + private boolean _shouldBreakLeash = true; + private boolean _pullWhileLeashed = true; + ++ public static DataIndex META_NOAI = DataWatcher.getIndex(EntityInsentient.class, DataType.BYTE); ++ + public EntityInsentient(World world) { + super(world); + this.goalSelector = new PathfinderGoalSelector(world != null && world.methodProfiler != null ? world.methodProfiler : null); +@@ -159,7 +161,7 @@ public abstract class EntityInsentient extends EntityLiving { + + protected void h() { + super.h(); +- this.datawatcher.a(15, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(15, Byte.valueOf((byte) 0), META_NOAI, (byte) 0); + } + + public int w() { +@@ -958,7 +960,7 @@ public abstract class EntityInsentient extends EntityLiving { + } + + public void k(boolean flag) { +- this.datawatcher.watch(15, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(15, Byte.valueOf((byte) (flag ? 1 : 0)), META_NOAI, (byte) (flag ? 1 : 0)); + } + + public boolean ce() { +diff --git a/src/main/java/net/minecraft/server/EntityIronGolem.java b/src/main/java/net/minecraft/server/EntityIronGolem.java +index ba09cb2..710d1d0 100644 +--- a/src/main/java/net/minecraft/server/EntityIronGolem.java ++++ b/src/main/java/net/minecraft/server/EntityIronGolem.java +@@ -8,6 +8,7 @@ public class EntityIronGolem extends EntityGolem { + Village a; + private int c; + private int bm; ++ public static DataIndex META_PLAYER_CREATED = DataWatcher.getIndex(EntityIronGolem.class, DataType.BYTE); + + public EntityIronGolem(World world) { + super(world); +@@ -28,7 +29,7 @@ public class EntityIronGolem extends EntityGolem { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(16, Byte.valueOf((byte) 0), META_PLAYER_CREATED, Byte.valueOf((byte) 0)); + } + + protected void E() { +@@ -167,9 +168,9 @@ public class EntityIronGolem extends EntityGolem { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1)), META_PLAYER_CREATED, Byte.valueOf((byte) (b0 | 1))); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2)), META_PLAYER_CREATED, Byte.valueOf((byte) (b0 & -2))); + } + + } +diff --git a/src/main/java/net/minecraft/server/EntityItem.java b/src/main/java/net/minecraft/server/EntityItem.java +index 1f8b1c7..b59ffc5 100644 +--- a/src/main/java/net/minecraft/server/EntityItem.java ++++ b/src/main/java/net/minecraft/server/EntityItem.java +@@ -4,6 +4,7 @@ import java.util.Iterator; + import org.apache.logging.log4j.LogManager; + import org.apache.logging.log4j.Logger; + import org.bukkit.event.player.PlayerPickupItemEvent; // CraftBukkit ++import com.google.common.base.Optional; + + public class EntityItem extends Entity { + +@@ -15,6 +16,7 @@ public class EntityItem extends Entity { + private String g; + public float a; + private int lastTick = MinecraftServer.currentTick; // CraftBukkit ++ public static DataIndex> META_ITEM = DataWatcher.getIndex(EntityItem.class, DataType.OPT_ITEMSTACK); + + public EntityItem(World world, double d0, double d1, double d2) { + super(world); +@@ -51,7 +53,7 @@ public class EntityItem extends Entity { + } + + protected void h() { +- this.getDataWatcher().add(10, 5); ++ this.getDataWatcher().add(10, 5, META_ITEM, Optional. absent()); + } + + public void t_() { +@@ -396,7 +398,7 @@ public class EntityItem extends Entity { + } + + public void setItemStack(ItemStack itemstack) { +- this.getDataWatcher().watch(10, itemstack); ++ this.getDataWatcher().watch(10, itemstack, META_ITEM, Optional.of(itemstack)); + this.getDataWatcher().update(10); + } + +diff --git a/src/main/java/net/minecraft/server/EntityItemFrame.java b/src/main/java/net/minecraft/server/EntityItemFrame.java +index 1008567..a3d7b66 100644 +--- a/src/main/java/net/minecraft/server/EntityItemFrame.java ++++ b/src/main/java/net/minecraft/server/EntityItemFrame.java +@@ -2,10 +2,13 @@ package net.minecraft.server; + + import java.util.UUID; + import org.apache.commons.codec.Charsets; ++import com.google.common.base.Optional; + + public class EntityItemFrame extends EntityHanging { + + private float c = 1.0F; ++ public static DataIndex> META_ITEM = DataWatcher.getIndex(EntityItemFrame.class, DataType.OPT_ITEMSTACK); ++ public static DataIndex META_ROTATION = DataWatcher.getIndex(EntityItemFrame.class, DataType.INTEGER); + + public EntityItemFrame(World world) { + super(world); +@@ -17,8 +20,8 @@ public class EntityItemFrame extends EntityHanging { + } + + protected void h() { +- this.getDataWatcher().add(8, 5); +- this.getDataWatcher().a(9, Byte.valueOf((byte) 0)); ++ this.getDataWatcher().add(8, 5, META_ITEM, Optional. absent()); ++ this.getDataWatcher().a(9, Byte.valueOf((byte) 0), META_ROTATION, 0); + } + + public float ao() { +@@ -110,7 +113,7 @@ public class EntityItemFrame extends EntityHanging { + itemstack.a(this); + } + +- this.getDataWatcher().watch(8, itemstack); ++ this.getDataWatcher().watch(8, itemstack, META_ITEM, Optional.fromNullable(itemstack)); + this.getDataWatcher().update(8); + if (flag && this.blockPosition != null) { + this.world.updateAdjacentComparators(this.blockPosition, Blocks.AIR); +@@ -127,7 +130,7 @@ public class EntityItemFrame extends EntityHanging { + } + + private void setRotation(int i, boolean flag) { +- this.getDataWatcher().watch(9, Byte.valueOf((byte) (i % 8))); ++ this.getDataWatcher().watch(9, Byte.valueOf((byte) (i % 8)), META_ROTATION, i % 8); + if (flag && this.blockPosition != null) { + this.world.updateAdjacentComparators(this.blockPosition, Blocks.AIR); + } +diff --git a/src/main/java/net/minecraft/server/EntityLiving.java b/src/main/java/net/minecraft/server/EntityLiving.java +index 96b3905..d0af93f 100644 +--- a/src/main/java/net/minecraft/server/EntityLiving.java ++++ b/src/main/java/net/minecraft/server/EntityLiving.java +@@ -114,11 +114,17 @@ public abstract class EntityLiving extends Entity { + _ghost = ghost; + } + ++ public static DataIndex META_UNKNOWN_BYTE = DataWatcher.getIndex(EntityLiving.class, DataType.BYTE); ++ public static DataIndex META_HEALTH = DataWatcher.getIndex(EntityLiving.class, DataType.FLOAT); ++ public static DataIndex META_POTION_COLOR = DataWatcher.getIndex(EntityLiving.class, DataType.INTEGER); ++ public static DataIndex META_AMBIENT_POTION = DataWatcher.getIndex(EntityLiving.class, DataType.BOOLEAN); ++ public static DataIndex META_ARROWS = DataWatcher.getIndex(EntityLiving.class, DataType.INTEGER); ++ + public EntityLiving(World world) { + super(world); + this.initAttributes(); + // CraftBukkit - setHealth(getMaxHealth()) inlined and simplified to skip the instanceof check for EntityPlayer, as getBukkitEntity() is not initialized in constructor +- this.datawatcher.watch(6, (float) this.getAttributeInstance(GenericAttributes.maxHealth).getValue()); ++ this.datawatcher.watch(6, (float) this.getAttributeInstance(GenericAttributes.maxHealth).getValue(), META_HEALTH, (float) this.getAttributeInstance(GenericAttributes.maxHealth).getValue()); + this.k = true; + this.aH = (float) ((Math.random() + 1.0D) * 0.009999999776482582D); + this.setPosition(this.locX, this.locY, this.locZ); +@@ -129,10 +135,11 @@ public abstract class EntityLiving extends Entity { + } + + protected void h() { +- this.datawatcher.a(7, Integer.valueOf(0)); +- this.datawatcher.a(8, Byte.valueOf((byte) 0)); +- this.datawatcher.a(9, Byte.valueOf((byte) 0)); +- this.datawatcher.a(6, Float.valueOf(1.0F)); ++ this.datawatcher.a(-1, (byte) 0, META_UNKNOWN_BYTE, (byte) new Random().nextInt(5)); ++ this.datawatcher.a(7, Integer.valueOf(0), META_POTION_COLOR, 0); ++ this.datawatcher.a(8, Byte.valueOf((byte) 0), META_AMBIENT_POTION, false); ++ this.datawatcher.a(9, Byte.valueOf((byte) 0), META_ARROWS, 0); ++ this.datawatcher.a(6, Float.valueOf(1.0F), META_HEALTH, 1F); + } + + protected void initAttributes() { +@@ -547,16 +554,16 @@ public abstract class EntityLiving extends Entity { + } else { + int i = PotionBrewer.a(this.effects.values()); + +- this.datawatcher.watch(8, Byte.valueOf((byte) (PotionBrewer.b(this.effects.values()) ? 1 : 0))); +- this.datawatcher.watch(7, Integer.valueOf(i)); ++ this.datawatcher.watch(8, Byte.valueOf((byte) (PotionBrewer.b(this.effects.values()) ? 1 : 0)), META_AMBIENT_POTION, PotionBrewer.b(this.effects.values())); ++ this.datawatcher.watch(7, Integer.valueOf(i), META_POTION_COLOR, i); + this.setInvisible(this.hasEffect(MobEffectList.INVISIBILITY.id)); + } + + } + + protected void bj() { +- this.datawatcher.watch(8, Byte.valueOf((byte) 0)); +- this.datawatcher.watch(7, Integer.valueOf(0)); ++ this.datawatcher.watch(8, Byte.valueOf((byte) 0), META_AMBIENT_POTION, false); ++ this.datawatcher.watch(7, Integer.valueOf(0), META_POTION_COLOR, 0); + } + + public void removeAllEffects() { +@@ -709,11 +716,11 @@ public abstract class EntityLiving extends Entity { + player.setRealHealth(f); + } + +- this.datawatcher.watch(6, Float.valueOf(player.getScaledHealth())); ++ this.datawatcher.watch(6, Float.valueOf(player.getScaledHealth()), META_HEALTH, player.getScaledHealth()); + return; + } + // CraftBukkit end +- this.datawatcher.watch(6, Float.valueOf(MathHelper.a(f, 0.0F, this.getMaxHealth()))); ++ this.datawatcher.watch(6, Float.valueOf(MathHelper.a(f, 0.0F, this.getMaxHealth())), META_HEALTH, MathHelper.a(f, 0.0F, this.getMaxHealth())); + } + + public boolean damageEntity(DamageSource damagesource, float f) { +@@ -1174,7 +1181,7 @@ public abstract class EntityLiving extends Entity { + } + + public final void o(int i) { +- this.datawatcher.watch(9, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(9, Byte.valueOf((byte) i), META_ARROWS, i); + } + + private int n() { +diff --git a/src/main/java/net/minecraft/server/EntityMinecartAbstract.java b/src/main/java/net/minecraft/server/EntityMinecartAbstract.java +index 4bf790c..5372460 100644 +--- a/src/main/java/net/minecraft/server/EntityMinecartAbstract.java ++++ b/src/main/java/net/minecraft/server/EntityMinecartAbstract.java +@@ -35,6 +35,13 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + private double flyingZ = 0.95; + public double maxSpeed = 0.4D; + // CraftBukkit end ++ ++ public static DataIndex META_SHAKING_POWER = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.INTEGER); ++ public static DataIndex META_SHAKING_DIRECTION = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.INTEGER); ++ public static DataIndex META_SHAKING_MULT = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.FLOAT); ++ public static DataIndex META_BLOCK = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.INTEGER); ++ public static DataIndex META_Y_OFFSET = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.INTEGER); ++ public static DataIndex META_SHOW_BLOCK = DataWatcher.getIndex(EntityMinecartAbstract.class, DataType.BOOLEAN); + + public EntityMinecartAbstract(World world) { + super(world); +@@ -72,12 +79,12 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + protected void h() { +- this.datawatcher.a(17, new Integer(0)); +- this.datawatcher.a(18, new Integer(1)); +- this.datawatcher.a(19, new Float(0.0F)); +- this.datawatcher.a(20, new Integer(0)); +- this.datawatcher.a(21, new Integer(6)); +- this.datawatcher.a(22, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(17, new Integer(0), META_SHAKING_POWER, 0); ++ this.datawatcher.a(18, new Integer(1), META_SHAKING_DIRECTION, 0); ++ this.datawatcher.a(19, new Float(0.0F), META_SHAKING_MULT, 0F); ++ this.datawatcher.a(20, new Integer(0), META_BLOCK, 0); ++ this.datawatcher.a(21, new Integer(6), META_Y_OFFSET, 6); ++ this.datawatcher.a(22, Byte.valueOf((byte) 0), META_SHOW_BLOCK, false); + } + + public AxisAlignedBB j(Entity entity) { +@@ -772,7 +779,7 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + public void setDamage(float f) { +- this.datawatcher.watch(19, Float.valueOf(f)); ++ this.datawatcher.watch(19, Float.valueOf(f), META_SHAKING_MULT, f); + } + + public float getDamage() { +@@ -780,7 +787,7 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + public void j(int i) { +- this.datawatcher.watch(17, Integer.valueOf(i)); ++ this.datawatcher.watch(17, Integer.valueOf(i), META_SHAKING_POWER, i); + } + + public int getType() { +@@ -788,7 +795,7 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + public void k(int i) { +- this.datawatcher.watch(18, Integer.valueOf(i)); ++ this.datawatcher.watch(18, Integer.valueOf(i), META_SHAKING_DIRECTION, i); + } + + public int r() { +@@ -814,12 +821,12 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + public void setDisplayBlock(IBlockData iblockdata) { +- this.getDataWatcher().watch(20, Integer.valueOf(Block.getCombinedId(iblockdata))); ++ this.getDataWatcher().watch(20, Integer.valueOf(Block.getCombinedId(iblockdata)), META_BLOCK, Block.getCombinedId(iblockdata)); + this.a(true); + } + + public void SetDisplayBlockOffset(int i) { +- this.getDataWatcher().watch(21, Integer.valueOf(i)); ++ this.getDataWatcher().watch(21, Integer.valueOf(i), META_Y_OFFSET, i); + this.a(true); + } + +@@ -828,7 +835,7 @@ public abstract class EntityMinecartAbstract extends Entity implements INamableT + } + + public void a(boolean flag) { +- this.getDataWatcher().watch(22, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.getDataWatcher().watch(22, Byte.valueOf((byte) (flag ? 1 : 0)), META_SHOW_BLOCK, flag); + } + + public void setCustomName(String s) { +diff --git a/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java b/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java +index 44ae155..5ae66df 100644 +--- a/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java ++++ b/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java +@@ -7,8 +7,8 @@ public class EntityMinecartCommandBlock extends EntityMinecartAbstract { + this.sender = (org.bukkit.craftbukkit.entity.CraftMinecartCommand) EntityMinecartCommandBlock.this.getBukkitEntity(); // CraftBukkit - Set the sender + } + public void h() { +- EntityMinecartCommandBlock.this.getDataWatcher().watch(23, this.getCommand()); +- EntityMinecartCommandBlock.this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.k())); ++ EntityMinecartCommandBlock.this.getDataWatcher().watch(23, this.getCommand(), META_COMMAND, this.getCommand()); ++ EntityMinecartCommandBlock.this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.k()), META_COMMAND_OUTPUT, this.k()); + } + + public BlockPosition getChunkCoordinates() { +@@ -28,6 +28,8 @@ public class EntityMinecartCommandBlock extends EntityMinecartAbstract { + } + }; + private int b = 0; ++ public static DataIndex META_COMMAND = DataWatcher.getIndex(EntityMinecartCommandBlock.class, DataType.STRING); ++ public static DataIndex META_COMMAND_OUTPUT = DataWatcher.getIndex(EntityMinecartCommandBlock.class, DataType.ICHATBASECOMPONENT); + + public EntityMinecartCommandBlock(World world) { + super(world); +@@ -39,15 +41,15 @@ public class EntityMinecartCommandBlock extends EntityMinecartAbstract { + + protected void h() { + super.h(); +- this.getDataWatcher().a(23, ""); +- this.getDataWatcher().a(24, ""); ++ this.getDataWatcher().a(23, "", META_COMMAND, ""); ++ this.getDataWatcher().a(24, "", META_COMMAND_OUTPUT, new ChatComponentText("")); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a.b(nbttagcompound); +- this.getDataWatcher().watch(23, this.getCommandBlock().getCommand()); +- this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.getCommandBlock().k())); ++ this.getDataWatcher().watch(23, this.getCommandBlock().getCommand(), META_COMMAND, this.getCommandBlock().getCommand()); ++ this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.getCommandBlock().k()), META_COMMAND_OUTPUT, this.getCommandBlock().k()); + } + + protected void b(NBTTagCompound nbttagcompound) { +diff --git a/src/main/java/net/minecraft/server/EntityMinecartFurnace.java b/src/main/java/net/minecraft/server/EntityMinecartFurnace.java +new file mode 100644 +index 0000000..1ffb6bf +--- /dev/null ++++ b/src/main/java/net/minecraft/server/EntityMinecartFurnace.java +@@ -0,0 +1,151 @@ ++package net.minecraft.server; ++ ++import java.util.Random; ++ ++public class EntityMinecartFurnace extends EntityMinecartAbstract ++{ ++ private int c; ++ public double a; ++ public double b; ++ public static DataIndex META_BURNING = DataWatcher.getIndex(EntityMinecartFurnace.class, DataType.BOOLEAN); ++ ++ public EntityMinecartFurnace(World paramWorld) ++ { ++ super(paramWorld); ++ } ++ ++ public EntityMinecartFurnace(World paramWorld, double paramDouble1, double paramDouble2, double paramDouble3) { ++ super(paramWorld, paramDouble1, paramDouble2, paramDouble3); ++ } ++ ++ public EntityMinecartAbstract.EnumMinecartType s() ++ { ++ return EntityMinecartAbstract.EnumMinecartType.FURNACE; ++ } ++ ++ protected void h() ++ { ++ super.h(); ++ this.datawatcher.a(16, new Byte((byte)0), META_BURNING, false); ++ } ++ ++ public void t_() ++ { ++ super.t_(); ++ ++ if (this.c > 0) { ++ this.c -= 1; ++ } ++ if (this.c <= 0) { ++ this.a = (this.b = 0.0D); ++ } ++ i(this.c > 0); ++ ++ if ((j()) && (this.random.nextInt(4) == 0)) ++ this.world.addParticle(EnumParticle.SMOKE_LARGE, this.locX, this.locY + 0.8D, this.locZ, 0.0D, 0.0D, 0.0D, new int[0]); ++ } ++ ++ protected double m() ++ { ++ return 0.2D; ++ } ++ ++ public void a(DamageSource paramDamageSource) ++ { ++ super.a(paramDamageSource); ++ ++ if ((!paramDamageSource.isExplosion()) && (this.world.getGameRules().getBoolean("doEntityDrops"))) ++ a(new ItemStack(Blocks.FURNACE, 1), 0.0F); ++ } ++ ++ protected void a(BlockPosition paramBlockPosition, IBlockData paramIBlockData) ++ { ++ super.a(paramBlockPosition, paramIBlockData); ++ ++ double d1 = this.a * this.a + this.b * this.b; ++ if ((d1 > 0.0001D) && (this.motX * this.motX + this.motZ * this.motZ > 0.001D)) { ++ d1 = MathHelper.sqrt(d1); ++ this.a /= d1; ++ this.b /= d1; ++ ++ if (this.a * this.motX + this.b * this.motZ < 0.0D) { ++ this.a = 0.0D; ++ this.b = 0.0D; ++ } else { ++ double d2 = d1 / m(); ++ this.a *= d2; ++ this.b *= d2; ++ } ++ } ++ } ++ ++ protected void o() ++ { ++ double d1 = this.a * this.a + this.b * this.b; ++ ++ if (d1 > 0.0001D) { ++ d1 = MathHelper.sqrt(d1); ++ this.a /= d1; ++ this.b /= d1; ++ double d2 = 1.0D; ++ this.motX *= 0.800000011920929D; ++ this.motY *= 0.0D; ++ this.motZ *= 0.800000011920929D; ++ this.motX += this.a * d2; ++ this.motZ += this.b * d2; ++ } else { ++ this.motX *= 0.9800000190734863D; ++ this.motY *= 0.0D; ++ this.motZ *= 0.9800000190734863D; ++ } ++ ++ super.o(); ++ } ++ ++ public boolean e(EntityHuman paramEntityHuman) ++ { ++ ItemStack localItemStack = paramEntityHuman.inventory.getItemInHand(); ++ if ((localItemStack != null) && (localItemStack.getItem() == Items.COAL)) { ++ if (!paramEntityHuman.abilities.canInstantlyBuild) if (--localItemStack.count == 0) { ++ paramEntityHuman.inventory.setItem(paramEntityHuman.inventory.itemInHandIndex, null); ++ } ++ this.c += 3600; ++ } ++ this.a = (this.locX - paramEntityHuman.locX); ++ this.b = (this.locZ - paramEntityHuman.locZ); ++ ++ return true; ++ } ++ ++ protected void b(NBTTagCompound paramNBTTagCompound) ++ { ++ super.b(paramNBTTagCompound); ++ paramNBTTagCompound.setDouble("PushX", this.a); ++ paramNBTTagCompound.setDouble("PushZ", this.b); ++ paramNBTTagCompound.setShort("Fuel", (short)this.c); ++ } ++ ++ protected void a(NBTTagCompound paramNBTTagCompound) ++ { ++ super.a(paramNBTTagCompound); ++ this.a = paramNBTTagCompound.getDouble("PushX"); ++ this.b = paramNBTTagCompound.getDouble("PushZ"); ++ this.c = paramNBTTagCompound.getShort("Fuel"); ++ } ++ ++ protected boolean j() { ++ return (this.datawatcher.getByte(16) & 0x1) != 0; ++ } ++ ++ protected void i(boolean paramBoolean) { ++ if (paramBoolean) ++ this.datawatcher.watch(16, Byte.valueOf((byte)(this.datawatcher.getByte(16) | 0x1)), META_BURNING, paramBoolean); ++ else ++ this.datawatcher.watch(16, Byte.valueOf((byte)(this.datawatcher.getByte(16) & 0xFFFFFFFE)), META_BURNING, paramBoolean); ++ } ++ ++ public IBlockData u() ++ { ++ return (j() ? Blocks.LIT_FURNACE : Blocks.FURNACE).getBlockData().set(BlockFurnace.FACING, EnumDirection.NORTH); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/EntityOcelot.java b/src/main/java/net/minecraft/server/EntityOcelot.java +index edcb307..15abdfe 100644 +--- a/src/main/java/net/minecraft/server/EntityOcelot.java ++++ b/src/main/java/net/minecraft/server/EntityOcelot.java +@@ -7,6 +7,7 @@ public class EntityOcelot extends EntityTameableAnimal { + private PathfinderGoalAvoidTarget bo; + private PathfinderGoalTempt bp; + public boolean spawnBonus = true; // Spigot ++ public static DataIndex META_TYPE = DataWatcher.getIndex(EntityOcelot.class, DataType.INTEGER); + + public EntityOcelot(World world) { + super(world); +@@ -27,7 +28,7 @@ public class EntityOcelot extends EntityTameableAnimal { + + protected void h() { + super.h(); +- this.datawatcher.a(18, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(18, Byte.valueOf((byte) 0), META_TYPE, 0); + } + + public void E() { +@@ -184,7 +185,7 @@ public class EntityOcelot extends EntityTameableAnimal { + } + + public void setCatType(int i) { +- this.datawatcher.watch(18, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(18, Byte.valueOf((byte) i), META_TYPE, i); + } + + public boolean bR() { +diff --git a/src/main/java/net/minecraft/server/EntityPig.java b/src/main/java/net/minecraft/server/EntityPig.java +index 3f2ce15..0e5550d 100644 +--- a/src/main/java/net/minecraft/server/EntityPig.java ++++ b/src/main/java/net/minecraft/server/EntityPig.java +@@ -5,6 +5,7 @@ import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit + public class EntityPig extends EntityAnimal { + + private final PathfinderGoalPassengerCarrotStick bm; ++ public static DataIndex META_SADDLED = DataWatcher.getIndex(EntityPig.class, DataType.BOOLEAN); + + public EntityPig(World world) { + super(world); +@@ -36,7 +37,7 @@ public class EntityPig extends EntityAnimal { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(16, Byte.valueOf((byte) 0), META_SADDLED, false); + } + + public void b(NBTTagCompound nbttagcompound) { +@@ -103,9 +104,9 @@ public class EntityPig extends EntityAnimal { + + public void setSaddle(boolean flag) { + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) 1)); ++ this.datawatcher.watch(16, Byte.valueOf((byte) 1), META_SADDLED, true); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) 0)); ++ this.datawatcher.watch(16, Byte.valueOf((byte) 0), META_SADDLED, false); + } + + } +diff --git a/src/main/java/net/minecraft/server/EntityPlayer.java b/src/main/java/net/minecraft/server/EntityPlayer.java +index 44ac587..9c46797 100644 +--- a/src/main/java/net/minecraft/server/EntityPlayer.java ++++ b/src/main/java/net/minecraft/server/EntityPlayer.java +@@ -246,7 +246,13 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + if (arraylist.size() == 1) { + this.playerConnection.sendPacket(new PacketPlayOutMapChunk((Chunk) arraylist.get(0), true, '\uffff')); + } else { ++ if (playerConnection.networkManager.getVersion() == 47) + this.playerConnection.sendPacket(new PacketPlayOutMapChunkBulk(arraylist)); ++ else ++ for (Chunk chunk1 : (ArrayList) arraylist) ++ { ++ this.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk1, true, '\uffff')); ++ } + } + + Iterator iterator2 = arraylist1.iterator(); +@@ -596,7 +602,15 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + + super.mount(entity); + if (this.vehicle != entity1) { // CraftBukkit +- this.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this, this.vehicle)); ++ if (playerConnection.networkManager.getVersion() > 47) ++ { ++ if (entity1 != null) ++ this.playerConnection.sendPacket(new PacketPlayOutNewAttachEntity(entity1, entity1.passenger)); ++ if (this.vehicle != null) ++ this.playerConnection.sendPacket(new PacketPlayOutNewAttachEntity(this.vehicle, this)); ++ } ++ else ++ this.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this, this.vehicle)); + this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + } + +@@ -747,7 +761,11 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + Item item = itemstack.getItem(); + + if (item == Items.WRITTEN_BOOK) { +- this.playerConnection.sendPacket(new PacketPlayOutCustomPayload("MC|BOpen", new PacketDataSerializer(Unpooled.buffer()))); ++ PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer()); ++ ++ if (this.playerConnection.networkManager.getVersion() > 47) ++ serializer.b(0); ++ this.playerConnection.sendPacket(new PacketPlayOutCustomPayload("MC|BOpen", serializer)); + } + + } +@@ -1000,7 +1018,8 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + this.locale = packetplayinsettings.a(); + this.bR = packetplayinsettings.c(); + this.bS = packetplayinsettings.d(); +- this.getDataWatcher().watch(10, Byte.valueOf((byte) packetplayinsettings.e())); ++ this.getDataWatcher().watch(10, (byte) packetplayinsettings.e(), META_SKIN, (byte) packetplayinsettings.e()); ++ this.getDataWatcher().watch(16, (byte) 0, META_CAPE, (byte) 1); + } + + public EntityHuman.EnumChatVisibility getChatFlags() { +diff --git a/src/main/java/net/minecraft/server/EntityPotion.java b/src/main/java/net/minecraft/server/EntityPotion.java +index fd174c3..e2be9db 100644 +--- a/src/main/java/net/minecraft/server/EntityPotion.java ++++ b/src/main/java/net/minecraft/server/EntityPotion.java +@@ -8,11 +8,13 @@ import java.util.HashMap; + + import org.bukkit.craftbukkit.entity.CraftLivingEntity; + import org.bukkit.entity.LivingEntity; ++import com.google.common.base.Optional; + // CraftBukkit end + + public class EntityPotion extends EntityProjectile { + +- public ItemStack item; ++ private ItemStack item; ++ public static DataIndex> META_ITEMSTACK = DataWatcher.getIndex(EntityItem.class, DataType.OPT_ITEMSTACK); + + public EntityPotion(World world) { + super(world); +@@ -25,11 +27,13 @@ public class EntityPotion extends EntityProjectile { + public EntityPotion(World world, EntityLiving entityliving, ItemStack itemstack) { + super(world, entityliving); + this.item = itemstack; ++ this.datawatcher.a(-12, 0, META_ITEMSTACK, Optional.fromNullable(item)); + } + + public EntityPotion(World world, double d0, double d1, double d2, ItemStack itemstack) { + super(world, d0, d1, d2); + this.item = itemstack; ++ this.datawatcher.a(-12, 0, META_ITEMSTACK, Optional.fromNullable(item)); + } + + protected float m() { +@@ -50,6 +54,18 @@ public class EntityPotion extends EntityProjectile { + } + + this.item.setData(i); ++ this.datawatcher.watch(-12, 0, META_ITEMSTACK, Optional.fromNullable(item)); ++ } ++ ++ public void setItem(ItemStack item) ++ { ++ this.item = item; ++ this.datawatcher.watch(-12, 0, META_ITEMSTACK, Optional.fromNullable(item)); ++ } ++ ++ public ItemStack getItem() ++ { ++ return this.item; + } + + public int getPotionValue() { +@@ -139,6 +155,7 @@ public class EntityPotion extends EntityProjectile { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("Potion", 10)) { + this.item = ItemStack.createStack(nbttagcompound.getCompound("Potion")); ++ this.datawatcher.watch(-12, 0, META_ITEMSTACK, Optional.fromNullable(item)); + } else { + this.setPotionValue(nbttagcompound.getInt("potionValue")); + } +diff --git a/src/main/java/net/minecraft/server/EntityRabbit.java b/src/main/java/net/minecraft/server/EntityRabbit.java +index bb47e09..20b5d17 100644 +--- a/src/main/java/net/minecraft/server/EntityRabbit.java ++++ b/src/main/java/net/minecraft/server/EntityRabbit.java +@@ -11,6 +11,7 @@ public class EntityRabbit extends EntityAnimal { + private EntityRabbit.EnumRabbitState bt; + private int bu; + private EntityHuman bv; ++ public static DataIndex META_TYPE = DataWatcher.getIndex(EntityRabbit.class, DataType.INTEGER); + + public EntityRabbit(World world) { + super(world); +@@ -81,7 +82,7 @@ public class EntityRabbit extends EntityAnimal { + + protected void h() { + super.h(); +- this.datawatcher.a(18, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(18, Byte.valueOf((byte) 0), META_TYPE, 0); + } + + public void E() { +@@ -289,7 +290,7 @@ public class EntityRabbit extends EntityAnimal { + } + } + +- this.datawatcher.watch(18, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(18, Byte.valueOf((byte) i), META_TYPE, i); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { +diff --git a/src/main/java/net/minecraft/server/EntitySheep.java b/src/main/java/net/minecraft/server/EntitySheep.java +index 29611a1..ef22dba 100644 +--- a/src/main/java/net/minecraft/server/EntitySheep.java ++++ b/src/main/java/net/minecraft/server/EntitySheep.java +@@ -27,6 +27,7 @@ public class EntitySheep extends EntityAnimal { + private static final Map bo = Maps.newEnumMap(EnumColor.class); + private int bp; + private PathfinderGoalEatTile bq = new PathfinderGoalEatTile(this); ++ public static DataIndex META_WOOL_STATE = DataWatcher.getIndex(EntitySheep.class, DataType.BYTE); + + public static float[] a(EnumColor enumcolor) { + return (float[]) EntitySheep.bo.get(enumcolor); +@@ -71,7 +72,7 @@ public class EntitySheep extends EntityAnimal { + + protected void h() { + super.h(); +- this.datawatcher.a(16, new Byte((byte) 0)); ++ this.datawatcher.a(16, new Byte((byte) 0), META_WOOL_STATE, (byte) 0); + } + + protected void dropDeathLoot(boolean flag, int i) { +@@ -162,8 +163,9 @@ public class EntitySheep extends EntityAnimal { + + public void setColor(EnumColor enumcolor) { + byte b0 = this.datawatcher.getByte(16); ++ b0 = (byte) (b0 & 240 | enumcolor.getColorIndex() & 15); + +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & 240 | enumcolor.getColorIndex() & 15))); ++ this.datawatcher.watch(16, Byte.valueOf(b0), META_WOOL_STATE, b0); + } + + public boolean isSheared() { +@@ -174,9 +176,9 @@ public class EntitySheep extends EntityAnimal { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 16))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 16)), META_WOOL_STATE, (byte) (b0 | 16)); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -17))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -17)), META_WOOL_STATE, (byte) (b0 & -17)); + } + + } +diff --git a/src/main/java/net/minecraft/server/EntitySkeleton.java b/src/main/java/net/minecraft/server/EntitySkeleton.java +index 46bff95..19af049 100644 +--- a/src/main/java/net/minecraft/server/EntitySkeleton.java ++++ b/src/main/java/net/minecraft/server/EntitySkeleton.java +@@ -3,11 +3,14 @@ package net.minecraft.server; + import java.util.Calendar; + + import org.bukkit.event.entity.EntityCombustEvent; // CraftBukkit ++import org.bukkit.event.entity.EntityTargetEvent; + + public class EntitySkeleton extends EntityMonster implements IRangedEntity { + + private PathfinderGoalArrowAttack a = new PathfinderGoalArrowAttack(this, 1.0D, 20, 60, 15.0F); + private PathfinderGoalMeleeAttack b = new PathfinderGoalMeleeAttack(this, EntityHuman.class, 1.2D, false); ++ public static DataIndex META_TYPE = DataWatcher.getIndex(EntitySkeleton.class, DataType.INTEGER); ++ public static DataIndex META_AIMING = DataWatcher.getIndex(EntitySkeleton.class, DataType.BOOLEAN); + + public EntitySkeleton(World world) { + super(world); +@@ -34,7 +37,8 @@ public class EntitySkeleton extends EntityMonster implements IRangedEntity { + + protected void h() { + super.h(); +- this.datawatcher.a(13, new Byte((byte) 0)); ++ this.datawatcher.a(13, new Byte((byte) 0), META_TYPE, 0); ++ this.datawatcher.a(-20, (byte) 0, META_AIMING, false); + } + + protected String z() { +@@ -273,7 +277,7 @@ public class EntitySkeleton extends EntityMonster implements IRangedEntity { + } + + public void setSkeletonType(int i) { +- this.datawatcher.watch(13, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(13, Byte.valueOf((byte) i), META_TYPE, i); + this.fireProof = i == 1; + if (i == 1) { + this.setSize(0.72F, 2.535F); +@@ -305,7 +309,14 @@ public class EntitySkeleton extends EntityMonster implements IRangedEntity { + this.n(); + } + +- } ++ } ++ ++ public void setGoalTarget(EntityLiving entityliving, EntityTargetEvent.TargetReason reason, boolean fireEvent) ++ { ++ super.setGoalTarget(entityliving, reason, fireEvent); ++ ++ this.datawatcher.watch(-20, (byte) 0, META_AIMING, getGoalTarget() != null); ++ } + + public float getHeadHeight() { + return this.getSkeletonType() == 1 ? super.getHeadHeight() : 1.74F; +diff --git a/src/main/java/net/minecraft/server/EntitySlime.java b/src/main/java/net/minecraft/server/EntitySlime.java +index d39df07..8acc3fb 100644 +--- a/src/main/java/net/minecraft/server/EntitySlime.java ++++ b/src/main/java/net/minecraft/server/EntitySlime.java +@@ -10,6 +10,7 @@ public class EntitySlime extends EntityInsentient implements IMonster { + public float b; + public float c; + private boolean bk; ++ public static DataIndex META_SIZE = DataWatcher.getIndex(EntitySlime.class, DataType.INTEGER); + + public EntitySlime(World world) { + super(world); +@@ -24,11 +25,11 @@ public class EntitySlime extends EntityInsentient implements IMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Byte.valueOf((byte) 1)); ++ this.datawatcher.a(16, Byte.valueOf((byte) 1), META_SIZE, 1); + } + + public void setSize(int i) { +- this.datawatcher.watch(16, Byte.valueOf((byte) i)); ++ this.datawatcher.watch(16, Byte.valueOf((byte) i), META_SIZE, i); + this.setSize(0.51000005F * (float) i, 0.51000005F * (float) i); + this.setPosition(this.locX, this.locY, this.locZ); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue((double) (i * i)); +diff --git a/src/main/java/net/minecraft/server/EntitySpider.java b/src/main/java/net/minecraft/server/EntitySpider.java +index 68a253c..e37cf66 100644 +--- a/src/main/java/net/minecraft/server/EntitySpider.java ++++ b/src/main/java/net/minecraft/server/EntitySpider.java +@@ -4,6 +4,8 @@ import java.util.Random; + + public class EntitySpider extends EntityMonster { + ++ public static DataIndex META_CLIMBING = DataWatcher.getIndex(EntitySpider.class, DataType.BYTE); ++ + public EntitySpider(World world) { + super(world); + this.setSize(1.4F, 0.9F); +@@ -29,7 +31,7 @@ public class EntitySpider extends EntityMonster { + + protected void h() { + super.h(); +- this.datawatcher.a(16, new Byte((byte) 0)); ++ this.datawatcher.a(16, new Byte((byte) 0), META_CLIMBING, (byte) 0); + } + + public void t_() { +@@ -101,7 +103,7 @@ public class EntitySpider extends EntityMonster { + b0 &= -2; + } + +- this.datawatcher.watch(16, Byte.valueOf(b0)); ++ this.datawatcher.watch(16, Byte.valueOf(b0), META_CLIMBING, b0); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { +diff --git a/src/main/java/net/minecraft/server/EntityTNTPrimed.java b/src/main/java/net/minecraft/server/EntityTNTPrimed.java +index 83e71c1..9b13620 100644 +--- a/src/main/java/net/minecraft/server/EntityTNTPrimed.java ++++ b/src/main/java/net/minecraft/server/EntityTNTPrimed.java +@@ -10,6 +10,7 @@ public class EntityTNTPrimed extends Entity { + public boolean isIncendiary = false; // CraftBukkit - add field + + public boolean spectating; ++ public static DataIndex META_FUSE = DataWatcher.getIndex(EntityTNTPrimed.class, DataType.INTEGER); + + public EntityTNTPrimed(World world) { + super(world); +@@ -32,7 +33,9 @@ public class EntityTNTPrimed extends Entity { + this.source = entityliving; + } + +- protected void h() {} ++ protected void h() { ++ datawatcher.a(24, 0, META_FUSE, 80); ++ } + + protected boolean s_() { + return false; +@@ -94,6 +97,13 @@ public class EntityTNTPrimed extends Entity { + + protected void a(NBTTagCompound nbttagcompound) { + this.fuseTicks = nbttagcompound.getByte("Fuse"); ++ datawatcher.a(24, 0, META_FUSE, fuseTicks); ++ } ++ ++ public void setFuseTicks(int newTicks) ++ { ++ fuseTicks = newTicks; ++ datawatcher.a(24, 0, META_FUSE, fuseTicks); + } + + public EntityLiving getSource() { +diff --git a/src/main/java/net/minecraft/server/EntityTameableAnimal.java b/src/main/java/net/minecraft/server/EntityTameableAnimal.java +new file mode 100644 +index 0000000..89b5dd7 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/EntityTameableAnimal.java +@@ -0,0 +1,167 @@ ++package net.minecraft.server; ++ ++import java.util.Random; ++import java.util.UUID; ++import com.google.common.base.Optional; ++ ++public abstract class EntityTameableAnimal extends EntityAnimal ++ implements EntityOwnable ++{ ++ protected PathfinderGoalSit bm = new PathfinderGoalSit(this); ++ public static DataIndex META_SITTING_TAMED = DataWatcher.getIndex(EntityTameableAnimal.class, DataType.BYTE); ++ public static DataIndex> META_OWNER = DataWatcher.getIndex(EntityTameableAnimal.class, DataType.OPT_UUID); ++ ++ public EntityTameableAnimal(World paramWorld) { ++ super(paramWorld); ++ cm(); ++ } ++ ++ protected void h() ++ { ++ super.h(); ++ this.datawatcher.a(16, Byte.valueOf((byte)0), META_SITTING_TAMED, (byte) 0); ++ this.datawatcher.a(17, "", META_OWNER, Optional. absent()); ++ } ++ ++ public void b(NBTTagCompound paramNBTTagCompound) ++ { ++ super.b(paramNBTTagCompound); ++ if (getOwnerUUID() == null) ++ paramNBTTagCompound.setString("OwnerUUID", ""); ++ else { ++ paramNBTTagCompound.setString("OwnerUUID", getOwnerUUID()); ++ } ++ paramNBTTagCompound.setBoolean("Sitting", isSitting()); ++ } ++ ++ public void a(NBTTagCompound paramNBTTagCompound) ++ { ++ super.a(paramNBTTagCompound); ++ String str1 = ""; ++ if (paramNBTTagCompound.hasKeyOfType("OwnerUUID", 8)) { ++ str1 = paramNBTTagCompound.getString("OwnerUUID"); ++ } else { ++ String str2 = paramNBTTagCompound.getString("Owner"); ++ str1 = NameReferencingFileConverter.a(str2); ++ } ++ if (str1.length() > 0) { ++ setOwnerUUID(str1); ++ setTamed(true); ++ } ++ this.bm.setSitting(paramNBTTagCompound.getBoolean("Sitting")); ++ setSitting(paramNBTTagCompound.getBoolean("Sitting")); ++ } ++ ++ protected void l(boolean paramBoolean) { ++ EnumParticle localEnumParticle = EnumParticle.HEART; ++ if (!paramBoolean) { ++ localEnumParticle = EnumParticle.SMOKE_NORMAL; ++ } ++ for (int i = 0; i < 7; i++) { ++ double d1 = this.random.nextGaussian() * 0.02D; ++ double d2 = this.random.nextGaussian() * 0.02D; ++ double d3 = this.random.nextGaussian() * 0.02D; ++ this.world.addParticle(localEnumParticle, this.locX + this.random.nextFloat() * this.width * 2.0F - this.width, this.locY + 0.5D + this.random.nextFloat() * this.length, this.locZ + this.random.nextFloat() * this.width * 2.0F - this.width, d1, d2, d3, new int[0]); ++ } ++ } ++ ++ public boolean isTamed() ++ { ++ return (this.datawatcher.getByte(16) & 0x4) != 0; ++ } ++ ++ public void setTamed(boolean paramBoolean) { ++ int i = this.datawatcher.getByte(16); ++ if (paramBoolean) ++ this.datawatcher.watch(16, Byte.valueOf((byte)(i | 0x4)), META_SITTING_TAMED, (byte)(i | 0x4)); ++ else { ++ this.datawatcher.watch(16, Byte.valueOf((byte)(i & 0xFFFFFFFB)), META_SITTING_TAMED, (byte)(i & 0xFFFFFFFB)); ++ } ++ ++ cm(); ++ } ++ ++ protected void cm() { ++ } ++ ++ public boolean isSitting() { ++ return (this.datawatcher.getByte(16) & 0x1) != 0; ++ } ++ ++ public void setSitting(boolean paramBoolean) { ++ int i = this.datawatcher.getByte(16); ++ if (paramBoolean) ++ this.datawatcher.watch(16, Byte.valueOf((byte)(i | 0x1)), META_SITTING_TAMED, (byte)(i | 0x1)); ++ else ++ this.datawatcher.watch(16, Byte.valueOf((byte)(i & 0xFFFFFFFE)), META_SITTING_TAMED, (byte)(i & 0xFFFFFFFE)); ++ } ++ ++ public String getOwnerUUID() ++ { ++ return this.datawatcher.getString(17); ++ } ++ ++ public void setOwnerUUID(String paramString) { ++ this.datawatcher.watch(17, paramString, META_OWNER, Optional.of(UUID.fromString(getOwnerUUID()))); ++ } ++ ++ public EntityLiving getOwner() ++ { ++ try { ++ UUID localUUID = UUID.fromString(getOwnerUUID()); ++ if (localUUID == null) { ++ return null; ++ } ++ return this.world.b(localUUID); } catch (IllegalArgumentException localIllegalArgumentException) { ++ } ++ return null; ++ } ++ ++ public boolean e(EntityLiving paramEntityLiving) ++ { ++ return paramEntityLiving == getOwner(); ++ } ++ ++ public PathfinderGoalSit getGoalSit() { ++ return this.bm; ++ } ++ ++ public boolean a(EntityLiving paramEntityLiving1, EntityLiving paramEntityLiving2) { ++ return true; ++ } ++ ++ public ScoreboardTeamBase getScoreboardTeam() ++ { ++ if (isTamed()) { ++ EntityLiving localEntityLiving = getOwner(); ++ if (localEntityLiving != null) { ++ return localEntityLiving.getScoreboardTeam(); ++ } ++ } ++ return super.getScoreboardTeam(); ++ } ++ ++ public boolean c(EntityLiving paramEntityLiving) ++ { ++ if (isTamed()) { ++ EntityLiving localEntityLiving = getOwner(); ++ if (paramEntityLiving == localEntityLiving) { ++ return true; ++ } ++ if (localEntityLiving != null) { ++ return localEntityLiving.c(paramEntityLiving); ++ } ++ } ++ return super.c(paramEntityLiving); ++ } ++ ++ public void die(DamageSource paramDamageSource) ++ { ++ if ((!this.world.isClientSide) && (this.world.getGameRules().getBoolean("showDeathMessages")) && (hasCustomName()) && ++ ((getOwner() instanceof EntityPlayer))) { ++ ((EntityPlayer)getOwner()).sendMessage(bs().b()); ++ } ++ ++ super.die(paramDamageSource); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/EntityTrackerEntry.java b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +index 3fb3205..39f0b73 100644 +--- a/src/main/java/net/minecraft/server/EntityTrackerEntry.java ++++ b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +@@ -75,8 +75,35 @@ public class EntityTrackerEntry { + } + + if (this.w != this.tracker.vehicle || this.tracker.vehicle != null && this.m % 60 == 0) { ++ ++ Iterator iterator = this.trackedPlayers.iterator(); ++ ++ Packet[] packets = new Packet[(this.w != null ? 1 : 0) + (this.tracker.vehicle != null ? 1 : 0)]; ++ int index = 0; ++ ++ if (this.w != null) ++ { ++ packets[index++] = new PacketPlayOutNewAttachEntity(this.w, this.w.passenger); ++ } ++ ++ if (this.tracker.vehicle != null) ++ { ++ packets[index++] = new PacketPlayOutNewAttachEntity(this.tracker.vehicle, this.tracker); ++ } ++ + this.w = this.tracker.vehicle; +- this.broadcast(new PacketPlayOutAttachEntity(0, this.tracker, this.tracker.vehicle)); ++ ++ while (iterator.hasNext()) { ++ EntityPlayer entityplayer = (EntityPlayer) iterator.next(); ++ ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47) ++ { ++ for (Packet packet : packets) ++ entityplayer.playerConnection.sendPacket(packet); ++ } ++ else ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this.tracker, this.tracker.vehicle)); ++ } + } + + if (this.tracker instanceof EntityItemFrame /*&& this.m % 10 == 0*/) { // CraftBukkit - Moved below, should always enter this block +@@ -334,7 +361,7 @@ public class EntityTrackerEntry { + + NBTTagCompound nbttagcompound = this.tracker.getNBTTag(); + +- if (nbttagcompound != null) { ++ if (nbttagcompound != null && entityplayer.playerConnection.networkManager.getVersion() == 47) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutUpdateEntityNBT(this.tracker.getId(), nbttagcompound)); + } + +@@ -361,7 +388,10 @@ public class EntityTrackerEntry { + } + + if (this.tracker.vehicle != null) { +- entityplayer.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this.tracker, this.tracker.vehicle)); ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47) ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutNewAttachEntity(this.tracker.vehicle, this.tracker)); ++ else ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this.tracker, this.tracker.vehicle)); + } + + if (this.tracker instanceof EntityInsentient && ((EntityInsentient) this.tracker).getLeashHolder() != null) { +diff --git a/src/main/java/net/minecraft/server/EntityVillager.java b/src/main/java/net/minecraft/server/EntityVillager.java +index f1c905a..784cbec 100644 +--- a/src/main/java/net/minecraft/server/EntityVillager.java ++++ b/src/main/java/net/minecraft/server/EntityVillager.java +@@ -22,6 +22,7 @@ public class EntityVillager extends EntityAgeable implements IMerchant, NPC { + private boolean bz; + private boolean bA; + public InventorySubcontainer inventory; ++ public static DataIndex META_TYPE = DataWatcher.getIndex(EntityVillager.class, DataType.INTEGER); + private static final EntityVillager.IMerchantRecipeOption[][][][] bC = new EntityVillager.IMerchantRecipeOption[][][][] { { { { new EntityVillager.MerchantRecipeOptionBuy(Items.WHEAT, new EntityVillager.MerchantOptionRandomRange(18, 22)), new EntityVillager.MerchantRecipeOptionBuy(Items.POTATO, new EntityVillager.MerchantOptionRandomRange(15, 19)), new EntityVillager.MerchantRecipeOptionBuy(Items.CARROT, new EntityVillager.MerchantOptionRandomRange(15, 19)), new EntityVillager.MerchantRecipeOptionSell(Items.BREAD, new EntityVillager.MerchantOptionRandomRange(-4, -2))}, { new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.PUMPKIN), new EntityVillager.MerchantOptionRandomRange(8, 13)), new EntityVillager.MerchantRecipeOptionSell(Items.PUMPKIN_PIE, new EntityVillager.MerchantOptionRandomRange(-3, -2))}, { new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.MELON_BLOCK), new EntityVillager.MerchantOptionRandomRange(7, 12)), new EntityVillager.MerchantRecipeOptionSell(Items.APPLE, new EntityVillager.MerchantOptionRandomRange(-5, -7))}, { new EntityVillager.MerchantRecipeOptionSell(Items.COOKIE, new EntityVillager.MerchantOptionRandomRange(-6, -10)), new EntityVillager.MerchantRecipeOptionSell(Items.CAKE, new EntityVillager.MerchantOptionRandomRange(1, 1))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Items.STRING, new EntityVillager.MerchantOptionRandomRange(15, 20)), new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionProcess(Items.FISH, new EntityVillager.MerchantOptionRandomRange(6, 6), Items.COOKED_FISH, new EntityVillager.MerchantOptionRandomRange(6, 6))}, { new EntityVillager.MerchantRecipeOptionEnchant(Items.FISHING_ROD, new EntityVillager.MerchantOptionRandomRange(7, 8))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.WOOL), new EntityVillager.MerchantOptionRandomRange(16, 22)), new EntityVillager.MerchantRecipeOptionSell(Items.SHEARS, new EntityVillager.MerchantOptionRandomRange(3, 4))}, { new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 0), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 1), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 2), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 3), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 4), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 5), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 6), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 7), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 8), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 9), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 10), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 11), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 12), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 13), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 14), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 15), new EntityVillager.MerchantOptionRandomRange(1, 2))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Items.STRING, new EntityVillager.MerchantOptionRandomRange(15, 20)), new EntityVillager.MerchantRecipeOptionSell(Items.ARROW, new EntityVillager.MerchantOptionRandomRange(-12, -8))}, { new EntityVillager.MerchantRecipeOptionSell(Items.BOW, new EntityVillager.MerchantOptionRandomRange(2, 3)), new EntityVillager.MerchantRecipeOptionProcess(Item.getItemOf(Blocks.GRAVEL), new EntityVillager.MerchantOptionRandomRange(10, 10), Items.FLINT, new EntityVillager.MerchantOptionRandomRange(6, 10))}}}, { { { new EntityVillager.MerchantRecipeOptionBuy(Items.PAPER, new EntityVillager.MerchantOptionRandomRange(24, 36)), new EntityVillager.MerchantRecipeOptionBook()}, { new EntityVillager.MerchantRecipeOptionBuy(Items.BOOK, new EntityVillager.MerchantOptionRandomRange(8, 10)), new EntityVillager.MerchantRecipeOptionSell(Items.COMPASS, new EntityVillager.MerchantOptionRandomRange(10, 12)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.BOOKSHELF), new EntityVillager.MerchantOptionRandomRange(3, 4))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.WRITTEN_BOOK, new EntityVillager.MerchantOptionRandomRange(2, 2)), new EntityVillager.MerchantRecipeOptionSell(Items.CLOCK, new EntityVillager.MerchantOptionRandomRange(10, 12)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.GLASS), new EntityVillager.MerchantOptionRandomRange(-5, -3))}, { new EntityVillager.MerchantRecipeOptionBook()}, { new EntityVillager.MerchantRecipeOptionBook()}, { new EntityVillager.MerchantRecipeOptionSell(Items.NAME_TAG, new EntityVillager.MerchantOptionRandomRange(20, 22))}}}, { { { new EntityVillager.MerchantRecipeOptionBuy(Items.ROTTEN_FLESH, new EntityVillager.MerchantOptionRandomRange(36, 40)), new EntityVillager.MerchantRecipeOptionBuy(Items.GOLD_INGOT, new EntityVillager.MerchantOptionRandomRange(8, 10))}, { new EntityVillager.MerchantRecipeOptionSell(Items.REDSTONE, new EntityVillager.MerchantOptionRandomRange(-4, -1)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new EntityVillager.MerchantOptionRandomRange(-2, -1))}, { new EntityVillager.MerchantRecipeOptionSell(Items.ENDER_EYE, new EntityVillager.MerchantOptionRandomRange(7, 11)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.GLOWSTONE), new EntityVillager.MerchantOptionRandomRange(-3, -1))}, { new EntityVillager.MerchantRecipeOptionSell(Items.EXPERIENCE_BOTTLE, new EntityVillager.MerchantOptionRandomRange(3, 11))}}}, { { { new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_HELMET, new EntityVillager.MerchantOptionRandomRange(4, 6))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(10, 14))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(16, 19))}, { new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_BOOTS, new EntityVillager.MerchantOptionRandomRange(5, 7)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_LEGGINGS, new EntityVillager.MerchantOptionRandomRange(9, 11)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_HELMET, new EntityVillager.MerchantOptionRandomRange(5, 7)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(11, 15))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_AXE, new EntityVillager.MerchantOptionRandomRange(6, 8))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_SWORD, new EntityVillager.MerchantOptionRandomRange(9, 10))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_SWORD, new EntityVillager.MerchantOptionRandomRange(12, 15)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_AXE, new EntityVillager.MerchantOptionRandomRange(9, 12))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_SHOVEL, new EntityVillager.MerchantOptionRandomRange(5, 7))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_PICKAXE, new EntityVillager.MerchantOptionRandomRange(9, 11))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_PICKAXE, new EntityVillager.MerchantOptionRandomRange(12, 15))}}}, { { { new EntityVillager.MerchantRecipeOptionBuy(Items.PORKCHOP, new EntityVillager.MerchantOptionRandomRange(14, 18)), new EntityVillager.MerchantRecipeOptionBuy(Items.CHICKEN, new EntityVillager.MerchantOptionRandomRange(14, 18))}, { new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.COOKED_PORKCHOP, new EntityVillager.MerchantOptionRandomRange(-7, -5)), new EntityVillager.MerchantRecipeOptionSell(Items.COOKED_CHICKEN, new EntityVillager.MerchantOptionRandomRange(-8, -6))}}, { { new EntityVillager.MerchantRecipeOptionBuy(Items.LEATHER, new EntityVillager.MerchantOptionRandomRange(9, 12)), new EntityVillager.MerchantRecipeOptionSell(Items.LEATHER_LEGGINGS, new EntityVillager.MerchantOptionRandomRange(2, 4))}, { new EntityVillager.MerchantRecipeOptionEnchant(Items.LEATHER_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(7, 12))}, { new EntityVillager.MerchantRecipeOptionSell(Items.SADDLE, new EntityVillager.MerchantOptionRandomRange(8, 10))}}}}; + + public EntityVillager(World world) { +@@ -145,7 +146,7 @@ public class EntityVillager extends EntityAgeable implements IMerchant, NPC { + + protected void h() { + super.h(); +- this.datawatcher.a(16, Integer.valueOf(0)); ++ this.datawatcher.a(16, Integer.valueOf(0), META_TYPE, 0); + } + + public void b(NBTTagCompound nbttagcompound) { +@@ -216,7 +217,7 @@ public class EntityVillager extends EntityAgeable implements IMerchant, NPC { + } + + public void setProfession(int i) { +- this.datawatcher.watch(16, Integer.valueOf(i)); ++ this.datawatcher.watch(16, Integer.valueOf(i), META_TYPE, i); + } + + public int getProfession() { +diff --git a/src/main/java/net/minecraft/server/EntityWitch.java b/src/main/java/net/minecraft/server/EntityWitch.java +new file mode 100644 +index 0000000..ce9b56a +--- /dev/null ++++ b/src/main/java/net/minecraft/server/EntityWitch.java +@@ -0,0 +1,185 @@ ++package net.minecraft.server; ++ ++import java.util.List; ++import java.util.Random; ++import java.util.UUID; ++ ++public class EntityWitch extends EntityMonster ++ implements IRangedEntity ++{ ++ private static final UUID a = UUID.fromString("5CD17E52-A79A-43D3-A529-90FDE04B181E"); ++ private static final AttributeModifier b = new AttributeModifier(a, "Drinking speed penalty", -0.25D, 0).a(false); ++ ++ private static final Item[] c = { Items.GLOWSTONE_DUST, Items.SUGAR, Items.REDSTONE, Items.SPIDER_EYE, Items.GLASS_BOTTLE, Items.GUNPOWDER, Items.STICK, Items.STICK }; ++ public static DataIndex META_AGGRESSIVE = DataWatcher.getIndex(EntityWitch.class, DataType.BOOLEAN); ++ private int bm; ++ ++ public EntityWitch(World paramWorld) ++ { ++ super(paramWorld); ++ setSize(0.6F, 1.95F); ++ ++ this.goalSelector.a(1, new PathfinderGoalFloat(this)); ++ this.goalSelector.a(2, new PathfinderGoalArrowAttack(this, 1.0D, 60, 10.0F)); ++ this.goalSelector.a(2, new PathfinderGoalRandomStroll(this, 1.0D)); ++ this.goalSelector.a(3, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); ++ this.goalSelector.a(3, new PathfinderGoalRandomLookaround(this)); ++ ++ this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false, new Class[0])); ++ this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget(this, EntityHuman.class, true)); ++ } ++ ++ protected void h() ++ { ++ super.h(); ++ ++ getDataWatcher().a(21, Byte.valueOf((byte)0), META_AGGRESSIVE, false); ++ } ++ ++ protected String z() ++ { ++ return null; ++ } ++ ++ protected String bo() ++ { ++ return null; ++ } ++ ++ protected String bp() ++ { ++ return null; ++ } ++ ++ public void a(boolean paramBoolean) { ++ getDataWatcher().watch(21, Byte.valueOf((byte)(paramBoolean ? 1 : 0)), META_AGGRESSIVE, paramBoolean); ++ } ++ ++ public boolean n() { ++ return getDataWatcher().getByte(21) == 1; ++ } ++ ++ protected void initAttributes() ++ { ++ super.initAttributes(); ++ ++ getAttributeInstance(GenericAttributes.maxHealth).setValue(26.0D); ++ getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); ++ } ++ ++ public void m() ++ { ++ if (!this.world.isClientSide) ++ { ++ Object localObject; ++ if (n()) { ++ if (this.bm-- <= 0) { ++ a(false); ++ ItemStack localItemStack = bA(); ++ setEquipment(0, null); ++ ++ if ((localItemStack != null) && (localItemStack.getItem() == Items.POTION)) { ++ localObject = Items.POTION.h(localItemStack); ++ if (localObject != null) { ++ for (MobEffect localMobEffect : (List)localObject) { ++ addEffect(new MobEffect(localMobEffect)); ++ } ++ } ++ } ++ ++ getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).c(b); ++ } ++ } else { ++ int i = -1; ++ ++ if ((this.random.nextFloat() < 0.15F) && (a(Material.WATER)) && (!hasEffect(MobEffectList.WATER_BREATHING))) ++ i = 8237; ++ else if ((this.random.nextFloat() < 0.15F) && (isBurning()) && (!hasEffect(MobEffectList.FIRE_RESISTANCE))) ++ i = 16307; ++ else if ((this.random.nextFloat() < 0.05F) && (getHealth() < getMaxHealth())) ++ i = 16341; ++ else if ((this.random.nextFloat() < 0.25F) && (getGoalTarget() != null) && (!hasEffect(MobEffectList.FASTER_MOVEMENT)) && (getGoalTarget().h(this) > 121.0D)) ++ i = 16274; ++ else if ((this.random.nextFloat() < 0.25F) && (getGoalTarget() != null) && (!hasEffect(MobEffectList.FASTER_MOVEMENT)) && (getGoalTarget().h(this) > 121.0D)) { ++ i = 16274; ++ } ++ ++ if (i > -1) { ++ setEquipment(0, new ItemStack(Items.POTION, 1, i)); ++ this.bm = bA().l(); ++ a(true); ++ localObject = getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); ++ ((AttributeInstance)localObject).c(b); ++ ((AttributeInstance)localObject).b(b); ++ } ++ } ++ ++ if (this.random.nextFloat() < 0.00075F) { ++ this.world.broadcastEntityEffect(this, (byte)15); ++ } ++ } ++ ++ super.m(); ++ } ++ ++ protected float applyMagicModifier(DamageSource paramDamageSource, float paramFloat) ++ { ++ paramFloat = super.applyMagicModifier(paramDamageSource, paramFloat); ++ ++ if (paramDamageSource.getEntity() == this) { ++ paramFloat = 0.0F; ++ } ++ if (paramDamageSource.isMagic()) { ++ paramFloat = (float)(paramFloat * 0.15D); ++ } ++ ++ return paramFloat; ++ } ++ ++ protected void dropDeathLoot(boolean paramBoolean, int paramInt) ++ { ++ int i = this.random.nextInt(3) + 1; ++ for (int j = 0; j < i; j++) { ++ int k = this.random.nextInt(3); ++ Item localItem = c[this.random.nextInt(c.length)]; ++ if (paramInt > 0) { ++ k += this.random.nextInt(paramInt + 1); ++ } ++ ++ for (int m = 0; m < k; m++) ++ a(localItem, 1); ++ } ++ } ++ ++ public void a(EntityLiving paramEntityLiving, float paramFloat) ++ { ++ if (n()) { ++ return; ++ } ++ ++ EntityPotion localEntityPotion = new EntityPotion(this.world, this, 32732); ++ double d1 = paramEntityLiving.locY + paramEntityLiving.getHeadHeight() - 1.100000023841858D; ++ localEntityPotion.pitch -= -20.0F; ++ double d2 = paramEntityLiving.locX + paramEntityLiving.motX - this.locX; ++ double d3 = d1 - this.locY; ++ double d4 = paramEntityLiving.locZ + paramEntityLiving.motZ - this.locZ; ++ float f = MathHelper.sqrt(d2 * d2 + d4 * d4); ++ ++ if ((f >= 8.0F) && (!paramEntityLiving.hasEffect(MobEffectList.SLOWER_MOVEMENT))) ++ localEntityPotion.setPotionValue(32698); ++ else if ((paramEntityLiving.getHealth() >= 8.0F) && (!paramEntityLiving.hasEffect(MobEffectList.POISON))) ++ localEntityPotion.setPotionValue(32660); ++ else if ((f <= 3.0F) && (!paramEntityLiving.hasEffect(MobEffectList.WEAKNESS)) && (this.random.nextFloat() < 0.25F)) { ++ localEntityPotion.setPotionValue(32696); ++ } ++ ++ localEntityPotion.shoot(d2, d3 + f * 0.2F, d4, 0.75F, 8.0F); ++ ++ this.world.addEntity(localEntityPotion); ++ } ++ ++ public float getHeadHeight() ++ { ++ return 1.62F; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/EntityWither.java b/src/main/java/net/minecraft/server/EntityWither.java +index fb19bad..4efe5bc 100644 +--- a/src/main/java/net/minecraft/server/EntityWither.java ++++ b/src/main/java/net/minecraft/server/EntityWither.java +@@ -30,6 +30,12 @@ public class EntityWither extends EntityMonster implements IRangedEntity { + } + }; + ++ public static DataIndex META_TARGET_1 = DataWatcher.getIndex(EntityWither.class, DataType.INTEGER); ++ public static DataIndex META_TARGET_2 = DataWatcher.getIndex(EntityWither.class, DataType.INTEGER); ++ public static DataIndex META_TARGET_3 = DataWatcher.getIndex(EntityWither.class, DataType.INTEGER); ++ public static DataIndex META_INVUL_TIME = DataWatcher.getIndex(EntityWither.class, DataType.INTEGER); ++ public static DataIndex[] META_HEAD_TARGETS = new DataIndex[] {META_TARGET_1, META_TARGET_2, META_TARGET_3}; ++ + public EntityWither(World world) { + super(world); + this.setHealth(this.getMaxHealth()); +@@ -48,10 +54,10 @@ public class EntityWither extends EntityMonster implements IRangedEntity { + + protected void h() { + super.h(); +- this.datawatcher.a(17, new Integer(0)); +- this.datawatcher.a(18, new Integer(0)); +- this.datawatcher.a(19, new Integer(0)); +- this.datawatcher.a(20, new Integer(0)); ++ this.datawatcher.a(17, new Integer(0), META_TARGET_1, new Integer(0)); ++ this.datawatcher.a(18, new Integer(0), META_TARGET_2, new Integer(0)); ++ this.datawatcher.a(19, new Integer(0), META_TARGET_3, new Integer(0)); ++ this.datawatcher.a(20, new Integer(0), META_INVUL_TIME, new Integer(0)); + } + + public void b(NBTTagCompound nbttagcompound) { +@@ -478,7 +484,7 @@ public class EntityWither extends EntityMonster implements IRangedEntity { + } + + public void r(int i) { +- this.datawatcher.watch(20, Integer.valueOf(i)); ++ this.datawatcher.watch(20, Integer.valueOf(i), META_INVUL_TIME, new Integer(i)); + } + + public int s(int i) { +@@ -486,7 +492,7 @@ public class EntityWither extends EntityMonster implements IRangedEntity { + } + + public void b(int i, int j) { +- this.datawatcher.watch(17 + i, Integer.valueOf(j)); ++ this.datawatcher.watch(17 + i, Integer.valueOf(j), META_HEAD_TARGETS[i], j); + } + + public boolean cm() { +diff --git a/src/main/java/net/minecraft/server/EntityWitherSkull.java b/src/main/java/net/minecraft/server/EntityWitherSkull.java +index f0e627b..a66d66a 100644 +--- a/src/main/java/net/minecraft/server/EntityWitherSkull.java ++++ b/src/main/java/net/minecraft/server/EntityWitherSkull.java +@@ -3,6 +3,7 @@ package net.minecraft.server; + import org.bukkit.event.entity.ExplosionPrimeEvent; // CraftBukkit + + public class EntityWitherSkull extends EntityFireball { ++ public static DataIndex META_BLUE = DataWatcher.getIndex(EntityWitherSkull.class, DataType.BOOLEAN); + + public EntityWitherSkull(World world) { + super(world); +@@ -90,7 +91,7 @@ public class EntityWitherSkull extends EntityFireball { + } + + protected void h() { +- this.datawatcher.a(10, Byte.valueOf((byte) 0)); ++ this.datawatcher.a(10, Byte.valueOf((byte) 0), META_BLUE, false); + } + + public boolean isCharged() { +@@ -98,6 +99,6 @@ public class EntityWitherSkull extends EntityFireball { + } + + public void setCharged(boolean flag) { +- this.datawatcher.watch(10, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.datawatcher.watch(10, Byte.valueOf((byte) (flag ? 1 : 0)), META_BLUE, flag); + } + } +diff --git a/src/main/java/net/minecraft/server/EntityWolf.java b/src/main/java/net/minecraft/server/EntityWolf.java +index 469c87a..b7c6cc7 100644 +--- a/src/main/java/net/minecraft/server/EntityWolf.java ++++ b/src/main/java/net/minecraft/server/EntityWolf.java +@@ -15,6 +15,9 @@ public class EntityWolf extends EntityTameableAnimal { + private boolean br; + private float bs; + private float bt; ++ public static DataIndex META_WOLF_HEALTH = DataWatcher.getIndex(EntityWolf.class, DataType.FLOAT); ++ public static DataIndex META_BEGGING = DataWatcher.getIndex(EntityWolf.class, DataType.BOOLEAN); ++ public static DataIndex META_COLLAR = DataWatcher.getIndex(EntityWolf.class, DataType.INTEGER); + + public EntityWolf(World world) { + super(world); +@@ -82,14 +85,14 @@ public class EntityWolf extends EntityTameableAnimal { + // CraftBukkit end + + protected void E() { +- this.datawatcher.watch(18, Float.valueOf(this.getHealth())); ++ this.datawatcher.watch(18, Float.valueOf(this.getHealth()), META_WOLF_HEALTH, getHealth()); + } + + protected void h() { + super.h(); +- this.datawatcher.a(18, new Float(this.getHealth())); +- this.datawatcher.a(19, new Byte((byte) 0)); +- this.datawatcher.a(20, new Byte((byte) EnumColor.RED.getColorIndex())); ++ this.datawatcher.a(18, new Float(this.getHealth()), META_WOLF_HEALTH, getHealth()); ++ this.datawatcher.a(19, new Byte((byte) 0), META_BEGGING, false); ++ this.datawatcher.a(20, new Byte((byte) EnumColor.RED.getColorIndex()), META_COLLAR, EnumColor.RED.getColorIndex()); + } + + protected void a(BlockPosition blockposition, Block block) { +@@ -323,9 +326,9 @@ public class EntityWolf extends EntityTameableAnimal { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 2))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 2)), META_SITTING_TAMED, (byte) (b0 | 2)); + } else { +- this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -3))); ++ this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -3)), META_SITTING_TAMED, (byte) (b0 & -3)); + } + + } +@@ -335,7 +338,7 @@ public class EntityWolf extends EntityTameableAnimal { + } + + public void setCollarColor(EnumColor enumcolor) { +- this.datawatcher.watch(20, Byte.valueOf((byte) (enumcolor.getInvColorIndex() & 15))); ++ this.datawatcher.watch(20, Byte.valueOf((byte) (enumcolor.getInvColorIndex() & 15)), META_COLLAR, enumcolor.getInvColorIndex() & 15); + } + + public EntityWolf b(EntityAgeable entityageable) { +@@ -352,9 +355,9 @@ public class EntityWolf extends EntityTameableAnimal { + + public void p(boolean flag) { + if (flag) { +- this.datawatcher.watch(19, Byte.valueOf((byte) 1)); ++ this.datawatcher.watch(19, Byte.valueOf((byte) 1), META_BEGGING, flag); + } else { +- this.datawatcher.watch(19, Byte.valueOf((byte) 0)); ++ this.datawatcher.watch(19, Byte.valueOf((byte) 0), META_BEGGING, flag); + } + + } +diff --git a/src/main/java/net/minecraft/server/EntityZombie.java b/src/main/java/net/minecraft/server/EntityZombie.java +index 1a8d3d8..253ff5e 100644 +--- a/src/main/java/net/minecraft/server/EntityZombie.java ++++ b/src/main/java/net/minecraft/server/EntityZombie.java +@@ -23,6 +23,10 @@ public class EntityZombie extends EntityMonster { + private float bp = -1.0F; + private float bq; + private int lastTick = MinecraftServer.currentTick; // CraftBukkit - add field ++ public static DataIndex META_CHILD = DataWatcher.getIndex(EntityZombie.class, DataType.BOOLEAN); ++ public static DataIndex META_UNKNOWN_INTEGER = DataWatcher.getIndex(EntityZombie.class, DataType.INTEGER); ++ public static DataIndex META_VILLAGER = DataWatcher.getIndex(EntityZombie.class, DataType.BOOLEAN); ++ public static DataIndex META_CONVERTING = DataWatcher.getIndex(EntityZombie.class, DataType.BOOLEAN); + + public EntityZombie(World world) { + super(world); +@@ -57,9 +61,9 @@ public class EntityZombie extends EntityMonster { + + protected void h() { + super.h(); +- this.getDataWatcher().a(12, Byte.valueOf((byte) 0)); +- this.getDataWatcher().a(13, Byte.valueOf((byte) 0)); +- this.getDataWatcher().a(14, Byte.valueOf((byte) 0)); ++ this.getDataWatcher().a(12, Byte.valueOf((byte) 0), META_CHILD, false); ++ this.getDataWatcher().a(13, Byte.valueOf((byte) 0), META_VILLAGER, false); ++ this.getDataWatcher().a(14, Byte.valueOf((byte) 0), META_CONVERTING, false); + } + + public int br() { +@@ -101,7 +105,7 @@ public class EntityZombie extends EntityMonster { + } + + public void setBaby(boolean flag) { +- this.getDataWatcher().watch(12, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.getDataWatcher().watch(12, Byte.valueOf((byte) (flag ? 1 : 0)), META_CHILD, flag); + if (this.world != null && !this.world.isClientSide) { + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + +@@ -119,7 +123,7 @@ public class EntityZombie extends EntityMonster { + } + + public void setVillager(boolean flag) { +- this.getDataWatcher().watch(13, Byte.valueOf((byte) (flag ? 1 : 0))); ++ this.getDataWatcher().watch(13, Byte.valueOf((byte) (flag ? 1 : 0)), META_VILLAGER, flag); + } + + public void m() { +@@ -462,7 +466,7 @@ public class EntityZombie extends EntityMonster { + + protected void a(int i) { + this.bn = i; +- this.getDataWatcher().watch(14, Byte.valueOf((byte) 1)); ++ this.getDataWatcher().watch(14, Byte.valueOf((byte) 1), META_CONVERTING, true); + this.removeEffect(MobEffectList.WEAKNESS.id); + this.addEffect(new MobEffect(MobEffectList.INCREASE_DAMAGE.id, i, Math.min(this.world.getDifficulty().a() - 1, 0))); + this.world.broadcastEntityEffect(this, (byte) 16); +diff --git a/src/main/java/net/minecraft/server/EnumProtocol.java b/src/main/java/net/minecraft/server/EnumProtocol.java +new file mode 100644 +index 0000000..eb425dc +--- /dev/null ++++ b/src/main/java/net/minecraft/server/EnumProtocol.java +@@ -0,0 +1,304 @@ ++// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. ++// Jad home page: http://www.kpdus.com/jad.html ++// Decompiler options: packimports(3) ++// Source File Name: SourceFile ++ ++package net.minecraft.server; ++ ++import com.google.common.collect.*; ++import java.util.*; ++import org.apache.logging.log4j.LogManager; ++import org.apache.logging.log4j.Logger; ++import java.util.Map.Entry; ++ ++public enum EnumProtocol ++{ ++ HANDSHAKING(-1) { ++ ++ ++ { ++ a(EnumProtocolDirection.SERVERBOUND, PacketHandshakingInSetProtocol.class, 0); ++ } ++ }, ++ ++ ++ PLAY(0) { ++ ++ ++ { ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetCompression.class, 70, -1); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMapChunkBulk.class, 38, -1); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateEntityNBT.class, 73, -1); ++ ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntity.class, 14, 0); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityExperienceOrb.class, 17, 1); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityWeather.class, 44, 2); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityLiving.class, 15, 3); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityPainting.class, 16, 4); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNamedEntitySpawn.class, 12, 5); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAnimation.class, 11, 6); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutStatistic.class, 55, 7); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockBreakAnimation.class, 37, 8); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTileEntityData.class, 53, 9); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockAction.class, 36, 10); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockChange.class, 35, 11); ++ // Boss bar ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutServerDifficulty.class, 65, 13); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTabComplete.class, 58, 14); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutChat.class, 2, 15); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMultiBlockChange.class, 34, 16); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTransaction.class, 50, 17); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCloseWindow.class, 46, 18); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutOpenWindow.class, 45, 19); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowItems.class, 48, 20); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowData.class, 49, 21); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetSlot.class, 47, 22); ++ // Set cooldown ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCustomPayload.class, 63, 24); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNamedSoundEffect.class, 41, 25); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutKickDisconnect.class, 64, 26); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityStatus.class, 26, 27); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutExplosion.class, 39, 28); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUnloadChunk.class, -1, 29); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutGameStateChange.class, 43, 30); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutKeepAlive.class, 0, 31); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMapChunk.class, 33, 32); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldEvent.class, 40, 33); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldParticles.class, 42, 34); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutLogin.class, 1, 35); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMap.class, 52, 36); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutRelEntityMove.class, 21, 37); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook.class, 23, 38); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutEntityLook.class, 22, 39); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.class, 20, 40); ++ // ??? double, double, double, float float ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutOpenSignEditor.class, 54, 42); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAbilities.class, 57, 43); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCombatEvent.class, 66, 44); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPlayerInfo.class, 56, 45); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPosition.class, 8, 46); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBed.class, 10, 47); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityDestroy.class, 19, 48); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutRemoveEntityEffect.class, 30, 49); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutResourcePackSend.class, 72, 50); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutRespawn.class, 7, 51); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityHeadRotation.class, 25, 52); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldBorder.class, 68, 53); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCamera.class, 67, 54); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutHeldItemSlot.class, 9, 55); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardDisplayObjective.class, 61, 56); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityMetadata.class, 28, 57); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAttachEntity.class, 27, 58); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityVelocity.class, 18, 59); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityEquipment.class, 4, 60); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutExperience.class, 31, 61); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateHealth.class, 6, 62); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardObjective.class, 59, 63); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNewAttachEntity.class, -1, 64); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardTeam.class, 62, 65); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardScore.class, 60, 66); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnPosition.class, 5, 67); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateTime.class, 3, 68); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTitle.class, 69, 69); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateSign.class, 51, 70); ++ // Subtitle packet ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPlayerListHeaderFooter.class, 71, 72); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCollect.class, 13, 73); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityTeleport.class, 24, 74); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateAttributes.class, 32, 75); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityEffect.class, 29, 76); ++ ++ ++ ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInArmAnimation.class, 10, 26); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInTabComplete.class, 20, 1); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInChat.class, 1, 2); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInClientCommand.class, 22, 3); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSettings.class, 21, 4); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInTransaction.class, 15, 5); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInEnchantItem.class, 17, 6); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInWindowClick.class, 14, 7); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInCloseWindow.class, 13, 8); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInCustomPayload.class, 23, 9); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUseEntity.class, 2, 10); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInKeepAlive.class, 0, 11); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInPosition.class, 4, 12); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInPositionLook.class, 6, 13); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInLook.class, 5, 14); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.class, 3, 15); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUnknownPosition.class, -1, 16); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUnknownFloats.class, -1, 17); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInAbilities.class, 19, 18); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInBlockDig.class, 7, 19); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInEntityAction.class, 11, 20); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSteerVehicle.class, 12, 21); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInResourcePackStatus.class, 25, 22); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInHeldItemSlot.class, 9, 23); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSetCreativeSlot.class, 16, 24); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUpdateSign.class, 18, 25); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInLeftClick.class, -1, 0); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSpectate.class, 24, 27); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInBlockPlace.class, 8, 28); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInRightClick.class, -1, 29); ++ ++ } ++ }, ++ ++ ++ STATUS(1) { ++ ++ ++ { ++ a(EnumProtocolDirection.SERVERBOUND, PacketStatusInStart.class, 0); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketStatusOutServerInfo.class, 0); ++ a(EnumProtocolDirection.SERVERBOUND, PacketStatusInPing.class, 1); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketStatusOutPong.class, 1); ++ } ++ }, ++ ++ ++ LOGIN(2) { ++ ++ ++ { ++ a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutDisconnect.class, 0); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutEncryptionBegin.class, 1); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutSuccess.class, 2); ++ a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutSetCompression.class, 3); ++ a(EnumProtocolDirection.SERVERBOUND, PacketLoginInStart.class, 0); ++ a(EnumProtocolDirection.SERVERBOUND, PacketLoginInEncryptionBegin.class, 1); ++ } ++ }; ++ ++ private EnumProtocol(int i1) ++ { ++ j = Maps.newEnumMap(EnumProtocolDirection.class); ++ i = i1; ++ } ++ ++ protected EnumProtocol a(EnumProtocolDirection enumprotocoldirection, Class class1, int id19) ++ { ++ Object obj = (BiMap)j.get(enumprotocoldirection); ++ if(obj == null) ++ { ++ obj = HashBiMap.create(); ++ j.put(enumprotocoldirection, obj); ++ } ++ if(((BiMap) (obj)).containsValue(class1)) ++ { ++ String s = (new StringBuilder()).append(enumprotocoldirection).append(" packet ").append(class1).append(" is already known to ID ").append(((BiMap) (obj)).inverse().get(class1)).toString(); ++ LogManager.getLogger().fatal(s); ++ throw new IllegalArgumentException(s); ++ } else ++ { ++ ((BiMap) (obj)).put(new HashMap.SimpleEntry(((BiMap) (obj)).size(), id19), class1); ++ return this; ++ } ++ } ++ ++ protected EnumProtocol a(EnumProtocolDirection enumprotocoldirection, Class class1, int id18, int id19) ++ { ++ Object obj = (BiMap)j.get(enumprotocoldirection); ++ if(obj == null) ++ { ++ obj = HashBiMap.create(); ++ j.put(enumprotocoldirection, obj); ++ } ++ if(((BiMap) (obj)).containsValue(class1)) ++ { ++ String s = (new StringBuilder()).append(enumprotocoldirection).append(" packet ").append(class1).append(" is already known to ID ").append(((BiMap) (obj)).inverse().get(class1)).toString(); ++ LogManager.getLogger().fatal(s); ++ throw new IllegalArgumentException(s); ++ } else ++ { ++ ((BiMap) (obj)).put(new HashMap.SimpleEntry(id18, id19), class1); ++ return this; ++ } ++ } ++ ++ public Integer a(EnumProtocolDirection enumprotocoldirection, Packet packet, boolean is1_8) ++ { ++ Entry entry = (Entry) ((BiMap)j.get(enumprotocoldirection)).inverse().get(packet.getClass()); ++ if ((Integer) (is1_8 ? entry.getKey() : entry.getValue()) < 0){System.out.print("Trying to send unsupported " + packet.getClass().getSimpleName());Thread.dumpStack();} ++ return (Integer) (is1_8 ? entry.getKey() : entry.getValue()); ++ } ++ ++ public Packet a(EnumProtocolDirection enumprotocoldirection, int l, boolean is1_8) ++ throws IllegalAccessException, InstantiationException ++ { ++ for (Entry entry : (Set) ((BiMap) j.get(enumprotocoldirection)).entrySet()) ++ { ++ Entry entry1 = (Entry) entry.getKey(); ++ if (l == (is1_8 ? (Integer) entry1.getKey() : (Integer) entry1.getValue())) ++ { ++ return (Packet) ((Class) entry.getValue()).newInstance(); ++ } ++ } ++ return null; ++ } ++ ++ public int a() ++ { ++ return i; ++ } ++ ++ public static EnumProtocol a(int l) ++ { ++ if(l < e || l > f) ++ return null; ++ else ++ return g[l - e]; ++ } ++ ++ public static EnumProtocol a(Packet packet) ++ { ++ return (EnumProtocol)h.get(packet.getClass()); ++ } ++ ++ private static int e; ++ private static int f; ++ private static final EnumProtocol g[]; ++ private static final Map h; ++ private final int i; ++ private final Map j; ++ ++ static ++ { ++ e = -1; ++ f = 2; ++ g = new EnumProtocol[(f - e) + 1]; ++ h = Maps.newHashMap(); ++ EnumProtocol aenumprotocol[] = values(); ++ int l = aenumprotocol.length; ++ for(int i1 = 0; i1 < l; i1++) ++ { ++ EnumProtocol enumprotocol = aenumprotocol[i1]; ++ int j1 = enumprotocol.a(); ++ if(j1 < e || j1 > f) ++ throw new Error((new StringBuilder()).append("Invalid protocol ID ").append(Integer.toString(j1)).toString()); ++ g[j1 - e] = enumprotocol; ++ for(Iterator iterator = enumprotocol.j.keySet().iterator(); iterator.hasNext();) ++ { ++ EnumProtocolDirection enumprotocoldirection = (EnumProtocolDirection)iterator.next(); ++ Iterator iterator1 = ((BiMap)enumprotocol.j.get(enumprotocoldirection)).values().iterator(); ++ while(iterator1.hasNext()) ++ { ++ Class class1 = (Class)iterator1.next(); ++ if(h.containsKey(class1) && h.get(class1) != enumprotocol) ++ throw new Error((new StringBuilder()).append("Packet ").append(class1).append(" is already assigned to protocol ").append(h.get(class1)).append(" - can't reassign to ").append(enumprotocol).toString()); ++ try ++ { ++ class1.newInstance(); ++ } ++ catch(Throwable throwable) ++ { ++ throw new Error((new StringBuilder()).append("Packet ").append(class1).append(" fails instantiation checks! ").append(class1).toString()); ++ } ++ h.put(class1, enumprotocol); ++ } ++ } ++ ++ } ++ ++ } ++} +diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java +index 64f6a9b..bec9f80 100644 +--- a/src/main/java/net/minecraft/server/HandshakeListener.java ++++ b/src/main/java/net/minecraft/server/HandshakeListener.java +@@ -22,6 +22,16 @@ public class HandshakeListener implements PacketHandshakingInListener { + } + + public void a(PacketHandshakingInSetProtocol packethandshakinginsetprotocol) { ++ ++ int version = packethandshakinginsetprotocol.b(); ++ //System.out.print(version); ++ boolean supported = version == 47 || version == 89 || version == 86; ++ ++ if (supported) ++ { ++ this.b.channel.attr(NetworkManager.protocolVersion).set(Integer.valueOf(version)); ++ } ++ + switch (HandshakeListener.SyntheticClass_1.a[packethandshakinginsetprotocol.a().ordinal()]) { + case 1: + this.b.a(EnumProtocol.LOGIN); +@@ -61,12 +71,8 @@ public class HandshakeListener implements PacketHandshakingInListener { + org.apache.logging.log4j.LogManager.getLogger().debug("Failed to check connection throttle", t); + } + // CraftBukkit end +- +- if (packethandshakinginsetprotocol.b() > 47) { +- chatcomponenttext = new ChatComponentText( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedServerMessage, "1.8.8" ) ); // Spigot +- this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); +- this.b.close(chatcomponenttext); +- } else if (packethandshakinginsetprotocol.b() < 47) { ++ ++ if (!supported) { + chatcomponenttext = new ChatComponentText( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedClientMessage, "1.8.8" ) ); // Spigot + this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + this.b.close(chatcomponenttext); +diff --git a/src/main/java/net/minecraft/server/MathHelper.java b/src/main/java/net/minecraft/server/MathHelper.java +new file mode 100644 +index 0000000..db19ad4 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/MathHelper.java +@@ -0,0 +1,309 @@ ++package net.minecraft.server; ++ ++import java.util.Random; ++import java.util.UUID; ++ ++public class MathHelper { ++ public static final float a; ++ private static final float[] b; ++ private static final int[] c; ++ private static final double d; ++ private static final double[] e; ++ private static final double[] f; ++ ++ public static float sin(float f) { ++ return b[(int)(f * 10430.378f) & 65535]; ++ } ++ ++ public static float cos(float f) { ++ return b[(int)(f * 10430.378f + 16384.0f) & 65535]; ++ } ++ ++ public static float c(float f) { ++ return (float)Math.sqrt(f); ++ } ++ ++ public static float sqrt(double d) { ++ return (float)Math.sqrt(d); ++ } ++ ++ public static int d(float f) { ++ int n = (int)f; ++ return f < (float)n ? n - 1 : n; ++ } ++ ++ public static int floor(double d) { ++ int n = (int)d; ++ return d < (double)n ? n - 1 : n; ++ } ++ ++ public static long d(double d) { ++ long l = (long)d; ++ return d < (double)l ? l - 1 : l; ++ } ++ ++ public static float e(float f) { ++ return f >= 0.0f ? f : - f; ++ } ++ ++ public static int a(int n) { ++ return n >= 0 ? n : - n; ++ } ++ ++ public static int f(float f) { ++ int n = (int)f; ++ return f > (float)n ? n + 1 : n; ++ } ++ ++ public static int f(double d) { ++ int n = (int)d; ++ return d > (double)n ? n + 1 : n; ++ } ++ ++ public static int clamp(int n, int n2, int n3) { ++ if (n < n2) { ++ return n2; ++ } ++ if (n > n3) { ++ return n3; ++ } ++ return n; ++ } ++ ++ public static float a(float f, float f2, float f3) { ++ if (f < f2) { ++ return f2; ++ } ++ if (f > f3) { ++ return f3; ++ } ++ return f; ++ } ++ ++ public static double a(double d, double d2, double d3) { ++ if (d < d2) { ++ return d2; ++ } ++ if (d > d3) { ++ return d3; ++ } ++ return d; ++ } ++ ++ public static double b(double d, double d2, double d3) { ++ if (d3 < 0.0) { ++ return d; ++ } ++ if (d3 > 1.0) { ++ return d2; ++ } ++ return d + (d2 - d) * d3; ++ } ++ ++ public static double a(double d, double d2) { ++ if (d < 0.0) { ++ d = - d; ++ } ++ if (d2 < 0.0) { ++ d2 = - d2; ++ } ++ return d > d2 ? d : d2; ++ } ++ ++ public static int nextInt(Random random, int n, int n2) { ++ if (n >= n2) { ++ return n; ++ } ++ return random.nextInt(n2 - n + 1) + n; ++ } ++ ++ public static float a(Random random, float f, float f2) { ++ if (f >= f2) { ++ return f; ++ } ++ return random.nextFloat() * (f2 - f) + f; ++ } ++ ++ public static double a(Random random, double d, double d2) { ++ if (d >= d2) { ++ return d; ++ } ++ return random.nextDouble() * (d2 - d) + d; ++ } ++ ++ public static double a(long[] arrl) { ++ long l = 0; ++ for (long l2 : arrl) { ++ l += l2; ++ } ++ return (double)l / (double)arrl.length; ++ } ++ ++ public static float g(float f) { ++ if ((f %= 360.0f) >= 180.0f) { ++ f -= 360.0f; ++ } ++ if (f < -180.0f) { ++ f += 360.0f; ++ } ++ return f; ++ } ++ ++ public static double g(double d) { ++ if ((d %= 360.0) >= 180.0) { ++ d -= 360.0; ++ } ++ if (d < -180.0) { ++ d += 360.0; ++ } ++ return d; ++ } ++ ++ public static int a(String string, int n) { ++ try { ++ return Integer.parseInt(string); ++ } ++ catch (Throwable var2_2) { ++ return n; ++ } ++ } ++ ++ public static int a(String string, int n, int n2) { ++ return Math.max(n2, MathHelper.a(string, n)); ++ } ++ ++ public static double a(String string, double d) { ++ try { ++ return Double.parseDouble(string); ++ } ++ catch (Throwable var3_2) { ++ return d; ++ } ++ } ++ ++ public static double a(String string, double d, double d2) { ++ return Math.max(d2, MathHelper.a(string, d)); ++ } ++ ++ public static int b(int n) { ++ int n2 = n - 1; ++ n2 |= n2 >> 1; ++ n2 |= n2 >> 2; ++ n2 |= n2 >> 4; ++ n2 |= n2 >> 8; ++ n2 |= n2 >> 16; ++ return n2 + 1; ++ } ++ ++ private static boolean d(int n) { ++ return n != 0 && (n & n - 1) == 0; ++ } ++ ++ public static int e(int n) { ++ n = MathHelper.d(n) ? n : MathHelper.b(n); ++ return c[(int)((long)n * 125613361 >> 27) & 31]; ++ } ++ ++ public static int c(int n) { ++ return MathHelper.e(n) - (MathHelper.d(n) ? 0 : 1); ++ } ++ ++ public static int c(int n, int n2) { ++ int n3; ++ if (n2 == 0) { ++ return 0; ++ } ++ if (n == 0) { ++ return n2; ++ } ++ if (n < 0) { ++ n2 *= -1; ++ } ++ if ((n3 = n % n2) == 0) { ++ return n; ++ } ++ return n + n2 - n3; ++ } ++ ++ public static UUID a(Random random) { ++ long l = random.nextLong() & -61441 | 16384; ++ long l2 = random.nextLong() & 0x3FFFFFFFFFFFFFFFL | Long.MIN_VALUE; ++ return new UUID(l, l2); ++ } ++ ++ public static double c(double d, double d2, double d3) { ++ return (d - d2) / (d3 - d2); ++ } ++ ++ public static double b(double d, double d2) { ++ boolean bl; ++ double d3; ++ boolean bl2; ++ boolean bl3; ++ double d4 = d2 * d2 + d * d; ++ if (Double.isNaN(d4)) { ++ return Double.NaN; ++ } ++ boolean bl4 = bl2 = d < 0.0; ++ if (bl2) { ++ d = - d; ++ } ++ boolean bl5 = bl3 = d2 < 0.0; ++ if (bl3) { ++ d2 = - d2; ++ } ++ boolean bl6 = bl = d > d2; ++ if (bl) { ++ d3 = d2; ++ d2 = d; ++ d = d3; ++ } ++ d3 = MathHelper.i(d4); ++ double d5 = MathHelper.d + (d *= d3); ++ int n = (int)Double.doubleToRawLongBits(d5); ++ double d6 = e[n]; ++ double d7 = f[n]; ++ double d8 = d5 - MathHelper.d; ++ double d9 = d * d7 - (d2 *= d3) * d8; ++ double d10 = (6.0 + d9 * d9) * d9 * 0.16666666666666666; ++ double d11 = d6 + d10; ++ if (bl) { ++ d11 = 1.5707963267948966 - d11; ++ } ++ if (bl3) { ++ d11 = 3.141592653589793 - d11; ++ } ++ if (bl2) { ++ d11 = - d11; ++ } ++ return d11; ++ } ++ ++ public static double i(double d) { ++ double d2 = 0.5 * d; ++ long l = Double.doubleToRawLongBits(d); ++ l = 6910469410427058090L - (l >> 1); ++ d = Double.longBitsToDouble(l); ++ d *= 1.5 - d2 * d * d; ++ return d; ++ } ++ ++ static { ++ int n; ++ a = MathHelper.c(2.0f); ++ b = new float[65536]; ++ for (n = 0; n < 65536; ++n) { ++ MathHelper.b[n] = (float)Math.sin((double)n * 3.141592653589793 * 2.0 / 65536.0); ++ } ++ c = new int[]{0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; ++ d = Double.longBitsToDouble(4805340802404319232L); ++ e = new double[257]; ++ f = new double[257]; ++ for (n = 0; n < 257; ++n) { ++ double d = (double)n / 256.0; ++ double d2 = Math.asin(d); ++ MathHelper.f[n] = Math.cos(d2); ++ MathHelper.e[n] = d2; ++ } ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java +index 55e2afd..1e9dc6c 100644 +--- a/src/main/java/net/minecraft/server/MinecraftServer.java ++++ b/src/main/java/net/minecraft/server/MinecraftServer.java +@@ -1023,7 +1023,7 @@ public abstract class MinecraftServer implements Runnable, ICommandListener, IAs + } + + public String getServerModName() { +- return "Spigot"; // Spigot - Spigot > // CraftBukkit - cb > vanilla! ++ return "Mineplex Spigot"; // Spigot - Spigot > // CraftBukkit - cb > vanilla! + } + + public CrashReport b(CrashReport crashreport) { +diff --git a/src/main/java/net/minecraft/server/NetworkManager.java b/src/main/java/net/minecraft/server/NetworkManager.java +index 83a600c..bf324f8 100644 +--- a/src/main/java/net/minecraft/server/NetworkManager.java ++++ b/src/main/java/net/minecraft/server/NetworkManager.java +@@ -76,10 +76,21 @@ public class NetworkManager extends SimpleChannelInboundHandler { + private IChatBaseComponent n; + private boolean o; + private boolean p; ++ public static final AttributeKey protocolVersion = new AttributeKey("protocol_version"); + + public NetworkManager(EnumProtocolDirection enumprotocoldirection) { + this.h = enumprotocoldirection; + } ++ ++ public static int getVersion(Channel attr) ++ { ++ Integer ver = (Integer)attr.attr(protocolVersion).get(); ++ return ver != null ? ver.intValue() : 47; ++ } ++ ++ public int getVersion() { ++ return getVersion(this.channel); ++ } + + public void channelActive(ChannelHandlerContext channelhandlercontext) throws Exception { + super.channelActive(channelhandlercontext); +diff --git a/src/main/java/net/minecraft/server/PacketDataSerializer.java b/src/main/java/net/minecraft/server/PacketDataSerializer.java +index f426c2e..1f98dce 100644 +--- a/src/main/java/net/minecraft/server/PacketDataSerializer.java ++++ b/src/main/java/net/minecraft/server/PacketDataSerializer.java +@@ -20,15 +20,24 @@ import java.nio.channels.GatheringByteChannel; + import java.nio.channels.ScatteringByteChannel; + import java.nio.charset.Charset; + import java.util.UUID; ++import com.mineplex.spigot.MineplexTranslateItem; ++import java.lang.reflect.Method; + + import org.bukkit.craftbukkit.inventory.CraftItemStack; // CraftBukkit + + public class PacketDataSerializer extends ByteBuf { + + private final ByteBuf a; ++ public final int version; + + public PacketDataSerializer(ByteBuf bytebuf) { + this.a = bytebuf; ++ version = 47; ++ } ++ ++ public PacketDataSerializer(ByteBuf bytebuf, int version) { ++ this.a = bytebuf; ++ this.version = version; + } + + public static int a(int i) { +@@ -66,7 +75,14 @@ public class PacketDataSerializer extends ByteBuf { + } + + public void a(IChatBaseComponent ichatbasecomponent) throws IOException { +- this.a(IChatBaseComponent.ChatSerializer.a(ichatbasecomponent)); ++ String s = IChatBaseComponent.ChatSerializer.a(ichatbasecomponent); ++ ++ if (s == null || s.equals("null")) ++ s = "{\"text\":\"\"}"; ++ else if (s.startsWith("\"")) ++ s = "{\"text\":" + s + "}"; ++ ++ this.a(s); + } + + public > T a(Class oclass) { +@@ -164,25 +180,7 @@ public class PacketDataSerializer extends ByteBuf { + } + + public void a(ItemStack itemstack) { +- if (itemstack == null || itemstack.getItem() == null) { // CraftBukkit - NPE fix itemstack.getItem() +- this.writeShort(-1); +- } else { +- this.writeShort(Item.getId(itemstack.getItem())); +- this.writeByte(itemstack.count); +- this.writeShort(itemstack.getData()); +- NBTTagCompound nbttagcompound = null; +- +- if (itemstack.getItem().usesDurability() || itemstack.getItem().p()) { +- // Spigot start - filter +- itemstack = itemstack.cloneItemStack(); +- CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); +- // Spigot end +- nbttagcompound = itemstack.getTag(); +- } +- +- this.a(nbttagcompound); +- } +- ++ MineplexTranslateItem.sendItemStack(this, itemstack); + } + + public ItemStack i() throws IOException { +@@ -193,8 +191,14 @@ public class PacketDataSerializer extends ByteBuf { + byte b0 = this.readByte(); + short short1 = this.readShort(); + +- itemstack = new ItemStack(Item.getById(short0), b0, short1); +- itemstack.setTag(this.h()); ++ if (version == 47) ++ { ++ itemstack = new ItemStack(Item.getById(short0), b0, short1); ++ itemstack.setTag(this.h()); ++ } ++ else ++ itemstack = MineplexTranslateItem.receiveItemStack(short0, b0, short1, this.h()); ++ + // CraftBukkit start + if (itemstack.getTag() != null) { + CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); +diff --git a/src/main/java/net/minecraft/server/PacketDecoder.java b/src/main/java/net/minecraft/server/PacketDecoder.java +new file mode 100644 +index 0000000..7790f68 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketDecoder.java +@@ -0,0 +1,50 @@ ++package net.minecraft.server; ++ ++import io.netty.buffer.ByteBuf; ++import io.netty.channel.Channel; ++import io.netty.channel.ChannelHandlerContext; ++import io.netty.handler.codec.ByteToMessageDecoder; ++import io.netty.util.Attribute; ++import java.io.IOException; ++import java.util.List; ++import org.apache.logging.log4j.LogManager; ++import org.apache.logging.log4j.Logger; ++import org.apache.logging.log4j.Marker; ++import org.apache.logging.log4j.MarkerManager; ++ ++public class PacketDecoder extends ByteToMessageDecoder ++{ ++ private static final Logger a = LogManager.getLogger(); ++ private static final Marker b = MarkerManager.getMarker("PACKET_RECEIVED", NetworkManager.b); ++ private final EnumProtocolDirection c; ++ ++ public PacketDecoder(EnumProtocolDirection paramEnumProtocolDirection) ++ { ++ this.c = paramEnumProtocolDirection; ++ } ++ ++ protected void decode(ChannelHandlerContext paramChannelHandlerContext, ByteBuf paramByteBuf, List paramList) throws Exception ++ { ++ if (paramByteBuf.readableBytes() == 0) { ++ return; ++ } ++ ++ int version = NetworkManager.getVersion(paramChannelHandlerContext.channel()); ++ PacketDataSerializer localPacketDataSerializer = new PacketDataSerializer(paramByteBuf, version); ++ int i = localPacketDataSerializer.e(); ++ Packet localPacket = ((EnumProtocol)paramChannelHandlerContext.channel().attr(NetworkManager.c).get()).a(this.c, i, version == 47); ++ ++ if (localPacket == null) { ++ throw new IOException("Bad packet id " + i); ++ } ++ ++ localPacket.a(localPacketDataSerializer); ++ if (localPacketDataSerializer.readableBytes() > 0) { ++ throw new IOException("Packet " + ((EnumProtocol)paramChannelHandlerContext.channel().attr(NetworkManager.c).get()).a() + "/" + i + " (" + localPacket.getClass().getSimpleName() + ") was larger than I expected, found " + localPacketDataSerializer.readableBytes() + " bytes extra whilst reading packet " + i); ++ } ++ paramList.add(localPacket); ++ ++ if (a.isDebugEnabled()) ++ a.debug(b, " IN: [{}:{}] {}", new Object[] { paramChannelHandlerContext.channel().attr(NetworkManager.c).get(), Integer.valueOf(i), localPacket.getClass().getName() }); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketEncoder.java b/src/main/java/net/minecraft/server/PacketEncoder.java +new file mode 100644 +index 0000000..70a3a7b +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketEncoder.java +@@ -0,0 +1,50 @@ ++package net.minecraft.server; ++ ++import io.netty.buffer.ByteBuf; ++import io.netty.channel.Channel; ++import io.netty.channel.ChannelHandlerContext; ++import io.netty.handler.codec.MessageToByteEncoder; ++import io.netty.util.Attribute; ++import java.io.IOException; ++import org.apache.logging.log4j.LogManager; ++import org.apache.logging.log4j.Logger; ++import org.apache.logging.log4j.Marker; ++import org.apache.logging.log4j.MarkerManager; ++ ++public class PacketEncoder extends MessageToByteEncoder ++{ ++ private static final Logger a = LogManager.getLogger(); ++ private static final Marker b = MarkerManager.getMarker("PACKET_SENT", NetworkManager.b); ++ private final EnumProtocolDirection c; ++ ++ public PacketEncoder(EnumProtocolDirection paramEnumProtocolDirection) ++ { ++ this.c = paramEnumProtocolDirection; ++ } ++ ++ protected void encode(ChannelHandlerContext paramChannelHandlerContext, Packet paramPacket, ByteBuf paramByteBuf) throws Exception ++ { ++ int version = NetworkManager.getVersion(paramChannelHandlerContext.channel()); ++ Integer localInteger = ((EnumProtocol)paramChannelHandlerContext.channel().attr(NetworkManager.c).get()).a(this.c, paramPacket, version == 47); ++ ++ if (a.isDebugEnabled()) { ++ a.debug(b, "OUT: [{}:{}] {}", new Object[] { paramChannelHandlerContext.channel().attr(NetworkManager.c).get(), localInteger, paramPacket.getClass().getName() }); ++ } ++ ++ if (localInteger == null) { ++ throw new IOException("Can't serialize unregistered packet"); ++ } ++ ++ PacketDataSerializer localPacketDataSerializer = new PacketDataSerializer(paramByteBuf, version); ++ localPacketDataSerializer.b(localInteger.intValue()); ++ try ++ { ++ if ((paramPacket instanceof PacketPlayOutNamedEntitySpawn)) { ++ paramPacket = paramPacket; ++ } ++ paramPacket.b(localPacketDataSerializer); ++ } catch (Throwable localThrowable) { ++ a.error(localThrowable); ++ } ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketListenerPlayIn.java b/src/main/java/net/minecraft/server/PacketListenerPlayIn.java +new file mode 100644 +index 0000000..80c2645 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketListenerPlayIn.java +@@ -0,0 +1,58 @@ ++package net.minecraft.server; ++ ++public abstract interface PacketListenerPlayIn extends PacketListener ++{ ++ public abstract void a(PacketPlayInArmAnimation paramPacketPlayInArmAnimation); ++ ++ public abstract void a(PacketPlayInChat paramPacketPlayInChat); ++ ++ public abstract void a(PacketPlayInTabComplete paramPacketPlayInTabComplete); ++ ++ public abstract void a(PacketPlayInClientCommand paramPacketPlayInClientCommand); ++ ++ public abstract void a(PacketPlayInSettings paramPacketPlayInSettings); ++ ++ public abstract void a(PacketPlayInTransaction paramPacketPlayInTransaction); ++ ++ public abstract void a(PacketPlayInEnchantItem paramPacketPlayInEnchantItem); ++ ++ public abstract void a(PacketPlayInWindowClick paramPacketPlayInWindowClick); ++ ++ public abstract void a(PacketPlayInCloseWindow paramPacketPlayInCloseWindow); ++ ++ public abstract void a(PacketPlayInCustomPayload paramPacketPlayInCustomPayload); ++ ++ public abstract void a(PacketPlayInUseEntity paramPacketPlayInUseEntity); ++ ++ public abstract void a(PacketPlayInKeepAlive paramPacketPlayInKeepAlive); ++ ++ public abstract void a(PacketPlayInFlying paramPacketPlayInFlying); ++ ++ public abstract void a(PacketPlayInAbilities paramPacketPlayInAbilities); ++ ++ public abstract void a(PacketPlayInBlockDig paramPacketPlayInBlockDig); ++ ++ public abstract void a(PacketPlayInEntityAction paramPacketPlayInEntityAction); ++ ++ public abstract void a(PacketPlayInSteerVehicle paramPacketPlayInSteerVehicle); ++ ++ public abstract void a(PacketPlayInHeldItemSlot paramPacketPlayInHeldItemSlot); ++ ++ public abstract void a(PacketPlayInSetCreativeSlot paramPacketPlayInSetCreativeSlot); ++ ++ public abstract void a(PacketPlayInUpdateSign paramPacketPlayInUpdateSign); ++ ++ public abstract void a(PacketPlayInBlockPlace paramPacketPlayInBlockPlace); ++ ++ public abstract void a(PacketPlayInSpectate paramPacketPlayInSpectate); ++ ++ public abstract void a(PacketPlayInResourcePackStatus paramPacketPlayInResourcePackStatus); ++ ++ public abstract void a(PacketPlayInUnknownFloats paramPacketPlayInUnknownFloats); ++ ++ public abstract void a(PacketPlayInUnknownPosition paramPacketInPlayUnknownPosition); ++ ++ public abstract void a(PacketPlayInLeftClick paramPacketPlayInLeftClick); ++ ++ public abstract void a(PacketPlayInRightClick paramPacketPlayInRightClick); ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketListenerPlayOut.java b/src/main/java/net/minecraft/server/PacketListenerPlayOut.java +new file mode 100644 +index 0000000..361eebb +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketListenerPlayOut.java +@@ -0,0 +1,150 @@ ++package net.minecraft.server; ++ ++public abstract interface PacketListenerPlayOut extends PacketListener ++{ ++ public abstract void a(PacketPlayOutSpawnEntity paramPacketPlayOutSpawnEntity); ++ ++ public abstract void a(PacketPlayOutSpawnEntityExperienceOrb paramPacketPlayOutSpawnEntityExperienceOrb); ++ ++ public abstract void a(PacketPlayOutSpawnEntityWeather paramPacketPlayOutSpawnEntityWeather); ++ ++ public abstract void a(PacketPlayOutSpawnEntityLiving paramPacketPlayOutSpawnEntityLiving); ++ ++ public abstract void a(PacketPlayOutScoreboardObjective paramPacketPlayOutScoreboardObjective); ++ ++ public abstract void a(PacketPlayOutSpawnEntityPainting paramPacketPlayOutSpawnEntityPainting); ++ ++ public abstract void a(PacketPlayOutNamedEntitySpawn paramPacketPlayOutNamedEntitySpawn); ++ ++ public abstract void a(PacketPlayOutAnimation paramPacketPlayOutAnimation); ++ ++ public abstract void a(PacketPlayOutStatistic paramPacketPlayOutStatistic); ++ ++ public abstract void a(PacketPlayOutBlockBreakAnimation paramPacketPlayOutBlockBreakAnimation); ++ ++ public abstract void a(PacketPlayOutOpenSignEditor paramPacketPlayOutOpenSignEditor); ++ ++ public abstract void a(PacketPlayOutTileEntityData paramPacketPlayOutTileEntityData); ++ ++ public abstract void a(PacketPlayOutBlockAction paramPacketPlayOutBlockAction); ++ ++ public abstract void a(PacketPlayOutBlockChange paramPacketPlayOutBlockChange); ++ ++ public abstract void a(PacketPlayOutChat paramPacketPlayOutChat); ++ ++ public abstract void a(PacketPlayOutTabComplete paramPacketPlayOutTabComplete); ++ ++ public abstract void a(PacketPlayOutMultiBlockChange paramPacketPlayOutMultiBlockChange); ++ ++ public abstract void a(PacketPlayOutMap paramPacketPlayOutMap); ++ ++ public abstract void a(PacketPlayOutTransaction paramPacketPlayOutTransaction); ++ ++ public abstract void a(PacketPlayOutCloseWindow paramPacketPlayOutCloseWindow); ++ ++ public abstract void a(PacketPlayOutWindowItems paramPacketPlayOutWindowItems); ++ ++ public abstract void a(PacketPlayOutOpenWindow paramPacketPlayOutOpenWindow); ++ ++ public abstract void a(PacketPlayOutWindowData paramPacketPlayOutWindowData); ++ ++ public abstract void a(PacketPlayOutSetSlot paramPacketPlayOutSetSlot); ++ ++ public abstract void a(PacketPlayOutCustomPayload paramPacketPlayOutCustomPayload); ++ ++ public abstract void a(PacketPlayOutKickDisconnect paramPacketPlayOutKickDisconnect); ++ ++ public abstract void a(PacketPlayOutBed paramPacketPlayOutBed); ++ ++ public abstract void a(PacketPlayOutEntityStatus paramPacketPlayOutEntityStatus); ++ ++ public abstract void a(PacketPlayOutAttachEntity paramPacketPlayOutAttachEntity); ++ ++ public abstract void a(PacketPlayOutExplosion paramPacketPlayOutExplosion); ++ ++ public abstract void a(PacketPlayOutGameStateChange paramPacketPlayOutGameStateChange); ++ ++ public abstract void a(PacketPlayOutKeepAlive paramPacketPlayOutKeepAlive); ++ ++ public abstract void a(PacketPlayOutMapChunk paramPacketPlayOutMapChunk); ++ ++ public abstract void a(PacketPlayOutMapChunkBulk paramPacketPlayOutMapChunkBulk); ++ ++ public abstract void a(PacketPlayOutWorldEvent paramPacketPlayOutWorldEvent); ++ ++ public abstract void a(PacketPlayOutLogin paramPacketPlayOutLogin); ++ ++ public abstract void a(PacketPlayOutEntity paramPacketPlayOutEntity); ++ ++ public abstract void a(PacketPlayOutPosition paramPacketPlayOutPosition); ++ ++ public abstract void a(PacketPlayOutWorldParticles paramPacketPlayOutWorldParticles); ++ ++ public abstract void a(PacketPlayOutAbilities paramPacketPlayOutAbilities); ++ ++ public abstract void a(PacketPlayOutPlayerInfo paramPacketPlayOutPlayerInfo); ++ ++ public abstract void a(PacketPlayOutEntityDestroy paramPacketPlayOutEntityDestroy); ++ ++ public abstract void a(PacketPlayOutRemoveEntityEffect paramPacketPlayOutRemoveEntityEffect); ++ ++ public abstract void a(PacketPlayOutRespawn paramPacketPlayOutRespawn); ++ ++ public abstract void a(PacketPlayOutEntityHeadRotation paramPacketPlayOutEntityHeadRotation); ++ ++ public abstract void a(PacketPlayOutHeldItemSlot paramPacketPlayOutHeldItemSlot); ++ ++ public abstract void a(PacketPlayOutScoreboardDisplayObjective paramPacketPlayOutScoreboardDisplayObjective); ++ ++ public abstract void a(PacketPlayOutEntityMetadata paramPacketPlayOutEntityMetadata); ++ ++ public abstract void a(PacketPlayOutEntityVelocity paramPacketPlayOutEntityVelocity); ++ ++ public abstract void a(PacketPlayOutEntityEquipment paramPacketPlayOutEntityEquipment); ++ ++ public abstract void a(PacketPlayOutExperience paramPacketPlayOutExperience); ++ ++ public abstract void a(PacketPlayOutUpdateHealth paramPacketPlayOutUpdateHealth); ++ ++ public abstract void a(PacketPlayOutScoreboardTeam paramPacketPlayOutScoreboardTeam); ++ ++ public abstract void a(PacketPlayOutScoreboardScore paramPacketPlayOutScoreboardScore); ++ ++ public abstract void a(PacketPlayOutSpawnPosition paramPacketPlayOutSpawnPosition); ++ ++ public abstract void a(PacketPlayOutUpdateTime paramPacketPlayOutUpdateTime); ++ ++ public abstract void a(PacketPlayOutUpdateSign paramPacketPlayOutUpdateSign); ++ ++ public abstract void a(PacketPlayOutNamedSoundEffect paramPacketPlayOutNamedSoundEffect); ++ ++ public abstract void a(PacketPlayOutCollect paramPacketPlayOutCollect); ++ ++ public abstract void a(PacketPlayOutEntityTeleport paramPacketPlayOutEntityTeleport); ++ ++ public abstract void a(PacketPlayOutUpdateAttributes paramPacketPlayOutUpdateAttributes); ++ ++ public abstract void a(PacketPlayOutEntityEffect paramPacketPlayOutEntityEffect); ++ ++ public abstract void a(PacketPlayOutCombatEvent paramPacketPlayOutCombatEvent); ++ ++ public abstract void a(PacketPlayOutServerDifficulty paramPacketPlayOutServerDifficulty); ++ ++ public abstract void a(PacketPlayOutCamera paramPacketPlayOutCamera); ++ ++ public abstract void a(PacketPlayOutWorldBorder paramPacketPlayOutWorldBorder); ++ ++ public abstract void a(PacketPlayOutTitle paramPacketPlayOutTitle); ++ ++ public abstract void a(PacketPlayOutSetCompression paramPacketPlayOutSetCompression); ++ ++ public abstract void a(PacketPlayOutPlayerListHeaderFooter paramPacketPlayOutPlayerListHeaderFooter); ++ ++ public abstract void a(PacketPlayOutResourcePackSend paramPacketPlayOutResourcePackSend); ++ ++ public abstract void a(PacketPlayOutUpdateEntityNBT paramPacketPlayOutUpdateEntityNBT); ++ ++ public abstract void a(PacketPlayOutUnloadChunk paramPacketPlayOutUnloadChunk); ++ ++ public abstract void a(PacketPlayOutNewAttachEntity paramPacketPlayOutNewAttachEntity); ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java b/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java +index 28cb5e3..d892097 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java ++++ b/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java +@@ -10,6 +10,10 @@ public class PacketPlayInArmAnimation implements Packet { + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + timestamp = System.currentTimeMillis(); // Spigot ++ if (packetdataserializer.version != 47) ++ { ++ packetdataserializer.e(); ++ } + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException {} +diff --git a/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java b/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java +index ac5928d..3238be6 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java ++++ b/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java +@@ -32,8 +32,15 @@ public class PacketPlayInBlockPlace implements Packet { + public void a(PacketDataSerializer packetdataserializer) throws IOException { + timestamp = System.currentTimeMillis(); // CraftBukkit + this.b = packetdataserializer.c(); +- this.c = packetdataserializer.readUnsignedByte(); +- this.d = packetdataserializer.i(); ++ if (packetdataserializer.version == 47) ++ { ++ this.c = packetdataserializer.readUnsignedByte(); ++ this.d = packetdataserializer.i(); ++ } ++ else { ++ this.c = packetdataserializer.e(); ++ packetdataserializer.e(); ++ } + this.e = (float) packetdataserializer.readUnsignedByte() / 16.0F; + this.f = (float) packetdataserializer.readUnsignedByte() / 16.0F; + this.g = (float) packetdataserializer.readUnsignedByte() / 16.0F; +diff --git a/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java b/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java +new file mode 100644 +index 0000000..366479c +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java +@@ -0,0 +1,28 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInKeepAlive ++ implements Packet ++{ ++ private int a; ++ ++ public void a(PacketListenerPlayIn paramPacketListenerPlayIn) ++ { ++ paramPacketListenerPlayIn.a(this); ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ this.a = paramPacketDataSerializer.e(); ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.b(this.a); ++ } ++ ++ public int a() { ++ return this.a; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInLeftClick.java b/src/main/java/net/minecraft/server/PacketPlayInLeftClick.java +new file mode 100644 +index 0000000..c186d56 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInLeftClick.java +@@ -0,0 +1,18 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInLeftClick implements Packet { ++ ++ public PacketPlayInLeftClick() {} ++ ++ public void a(PacketDataSerializer packetdataserializer) throws IOException { ++ packetdataserializer.e(); ++ } ++ ++ public void b(PacketDataSerializer packetdataserializer) throws IOException {} ++ ++ public void a(PacketListenerPlayIn packetlistenerplayin) { ++ packetlistenerplayin.a(this); ++ } ++} +diff --git a/src/main/java/net/minecraft/server/PacketPlayInRightClick.java b/src/main/java/net/minecraft/server/PacketPlayInRightClick.java +new file mode 100644 +index 0000000..a24efd6 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInRightClick.java +@@ -0,0 +1,18 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInRightClick implements Packet { ++ ++ public PacketPlayInRightClick() {} ++ ++ public void a(PacketDataSerializer packetdataserializer) throws IOException { ++ packetdataserializer.e(); ++ } ++ ++ public void b(PacketDataSerializer packetdataserializer) throws IOException {} ++ ++ public void a(PacketListenerPlayIn packetlistenerplayin) { ++ packetlistenerplayin.a(this); ++ } ++} +diff --git a/src/main/java/net/minecraft/server/PacketPlayInSettings.java b/src/main/java/net/minecraft/server/PacketPlayInSettings.java +new file mode 100644 +index 0000000..67487f6 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInSettings.java +@@ -0,0 +1,63 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInSettings ++ implements Packet ++{ ++ public String a; ++ public int b; ++ public EntityHuman.EnumChatVisibility c; ++ public boolean d; ++ public int e; ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ this.a = paramPacketDataSerializer.c(7); ++ this.b = paramPacketDataSerializer.readByte(); ++ ++ if (paramPacketDataSerializer.version == 47) ++ this.c = EntityHuman.EnumChatVisibility.a(paramPacketDataSerializer.readByte()); ++ else ++ this.c = EntityHuman.EnumChatVisibility.a(paramPacketDataSerializer.e()); ++ ++ this.d = paramPacketDataSerializer.readBoolean(); ++ ++ this.e = paramPacketDataSerializer.readUnsignedByte(); ++ ++ if (paramPacketDataSerializer.version != 47) ++ paramPacketDataSerializer.e(); ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.a(this.a); ++ paramPacketDataSerializer.writeByte(this.b); ++ paramPacketDataSerializer.writeByte(this.c.a()); ++ paramPacketDataSerializer.writeBoolean(this.d); ++ paramPacketDataSerializer.writeByte(this.e); ++ } ++ ++ public void a(PacketListenerPlayIn paramPacketListenerPlayIn) ++ { ++ paramPacketListenerPlayIn.a(this); ++ } ++ ++ public String a() { ++ return this.a; ++ } ++ ++ public EntityHuman.EnumChatVisibility c() ++ { ++ return this.c; ++ } ++ ++ public boolean d() { ++ return this.d; ++ } ++ ++ public int e() { ++ return this.e; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java b/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java +new file mode 100644 +index 0000000..b8947f4 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java +@@ -0,0 +1,58 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++import org.apache.commons.lang3.StringUtils; ++ ++public class PacketPlayInTabComplete ++ implements Packet ++{ ++ private String a; ++ private BlockPosition b; ++ ++ public PacketPlayInTabComplete() ++ { ++ } ++ ++ public PacketPlayInTabComplete(String paramString) ++ { ++ this(paramString, null); ++ } ++ ++ public PacketPlayInTabComplete(String paramString, BlockPosition paramBlockPosition) { ++ this.a = paramString; ++ this.b = paramBlockPosition; ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ this.a = paramPacketDataSerializer.c(32767); ++ if (paramPacketDataSerializer.version > 47) ++ paramPacketDataSerializer.readBoolean(); ++ boolean bool = paramPacketDataSerializer.readBoolean(); ++ if (bool) ++ this.b = paramPacketDataSerializer.c(); ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ paramPacketDataSerializer.a(StringUtils.substring(this.a, 0, 32767)); ++ boolean bool = this.b != null; ++ paramPacketDataSerializer.writeBoolean(bool); ++ if (bool) ++ paramPacketDataSerializer.a(this.b); ++ } ++ ++ public void a(PacketListenerPlayIn paramPacketListenerPlayIn) ++ { ++ paramPacketListenerPlayIn.a(this); ++ } ++ ++ public String a() { ++ return this.a; ++ } ++ ++ public BlockPosition b() { ++ return this.b; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInUnknownFloats.java b/src/main/java/net/minecraft/server/PacketPlayInUnknownFloats.java +new file mode 100644 +index 0000000..ace5a60 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInUnknownFloats.java +@@ -0,0 +1,39 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInUnknownFloats ++ implements Packet ++{ ++ public float a; ++ public float b; ++ ++ public PacketPlayInUnknownFloats() ++ { ++ } ++ ++ public void a(PacketDataSerializer dataSerializer) throws IOException ++ { ++ this.a = dataSerializer.readFloat(); ++ this.b = dataSerializer.readFloat(); ++ } ++ ++ public void b(PacketDataSerializer dataSerializer) throws IOException ++ { ++ dataSerializer.writeFloat(this.a); ++ dataSerializer.writeFloat(this.b); ++ } ++ ++ public void a(PacketListenerPlayIn listenerPlayIn) ++ { ++ listenerPlayIn.a(this); ++ } ++ ++ public float a() { ++ return this.a; ++ } ++ ++ public float b() { ++ return this.b; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInUnknownPosition.java b/src/main/java/net/minecraft/server/PacketPlayInUnknownPosition.java +new file mode 100644 +index 0000000..af5883a +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInUnknownPosition.java +@@ -0,0 +1,60 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInUnknownPosition ++ implements Packet ++{ ++ public double a; ++ public double b; ++ public double c; ++ public float d; ++ public float e; ++ ++ public PacketPlayInUnknownPosition() ++ { ++ } ++ ++ public void a(PacketDataSerializer dataSerializer) throws IOException ++ { ++ this.a = dataSerializer.readDouble(); ++ this.b = dataSerializer.readDouble(); ++ this.c = dataSerializer.readDouble(); ++ this.d = dataSerializer.readFloat(); ++ this.e = dataSerializer.readFloat(); ++ } ++ ++ public void b(PacketDataSerializer dataSerializer) throws IOException ++ { ++ dataSerializer.writeDouble(this.a); ++ dataSerializer.writeDouble(this.b); ++ dataSerializer.writeDouble(this.c); ++ dataSerializer.writeFloat(this.d); ++ dataSerializer.writeFloat(this.e); ++ } ++ ++ public void a(PacketListenerPlayIn listenerPlayIn) ++ { ++ listenerPlayIn.a(this); ++ } ++ ++ public double a() { ++ return this.a; ++ } ++ ++ public double b() { ++ return this.b; ++ } ++ ++ public double c() { ++ return this.c; ++ } ++ ++ public float d() { ++ return this.d; ++ } ++ ++ public float e() { ++ return this.e; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java b/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java +new file mode 100644 +index 0000000..7b8f6dc +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java +@@ -0,0 +1,58 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++import org.bukkit.craftbukkit.util.CraftChatMessage; ++ ++public class PacketPlayInUpdateSign ++ implements Packet ++{ ++ private BlockPosition a; ++ private IChatBaseComponent[] b; ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ this.a = paramPacketDataSerializer.c(); ++ this.b = new IChatBaseComponent[4]; ++ for (int i = 0; i < 4; i++) { ++ if (paramPacketDataSerializer.version == 47) { ++ String str = paramPacketDataSerializer.c(384); ++ IChatBaseComponent localIChatBaseComponent = IChatBaseComponent.ChatSerializer.a(str); ++ this.b[i] = localIChatBaseComponent; ++ } ++ else ++ { ++ b[i] = CraftChatMessage.fromString(paramPacketDataSerializer.c(384))[0]; ++ } ++ } ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.a(this.a); ++ for (int i = 0; i < 4; i++) { ++ IChatBaseComponent localIChatBaseComponent = this.b[i]; ++ if (paramPacketDataSerializer.version == 47) { ++ String str = IChatBaseComponent.ChatSerializer.a(localIChatBaseComponent); ++ paramPacketDataSerializer.a(str); ++ } ++ else ++ { ++ paramPacketDataSerializer.a(CraftChatMessage.fromComponent(localIChatBaseComponent)); ++ } ++ } ++ } ++ ++ public void a(PacketListenerPlayIn paramPacketListenerPlayIn) ++ { ++ paramPacketListenerPlayIn.a(this); ++ } ++ ++ public BlockPosition a() { ++ return this.a; ++ } ++ ++ public IChatBaseComponent[] b() { ++ return this.b; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java b/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java +index 40c4e2d..3969fa9 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java ++++ b/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java +@@ -16,6 +16,10 @@ public class PacketPlayInUseEntity + this.action = ((EnumEntityUseAction)paramPacketDataSerializer.a(EnumEntityUseAction.class)); + if (this.action == EnumEntityUseAction.INTERACT_AT) + this.c = new Vec3D(paramPacketDataSerializer.readFloat(), paramPacketDataSerializer.readFloat(), paramPacketDataSerializer.readFloat()); ++ if (this.action != EnumEntityUseAction.ATTACK && paramPacketDataSerializer.version != 47) ++ { ++ paramPacketDataSerializer.e(); ++ } + } + + public void b(PacketDataSerializer paramPacketDataSerializer) +diff --git a/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java b/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java +new file mode 100644 +index 0000000..0713db5 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java +@@ -0,0 +1,65 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayInWindowClick ++ implements Packet ++{ ++ private int a; ++ private int slot; ++ private int button; ++ private short d; ++ private ItemStack item; ++ private int shift; ++ ++ public void a(PacketListenerPlayIn paramPacketListenerPlayIn) ++ { ++ paramPacketListenerPlayIn.a(this); ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ this.a = paramPacketDataSerializer.readByte(); ++ this.slot = paramPacketDataSerializer.readShort(); ++ this.button = paramPacketDataSerializer.readByte(); ++ this.d = paramPacketDataSerializer.readShort(); ++ this.shift = paramPacketDataSerializer.e(); ++ ++ this.item = paramPacketDataSerializer.i(); ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.writeByte(this.a); ++ paramPacketDataSerializer.writeShort(this.slot); ++ paramPacketDataSerializer.writeByte(this.button); ++ paramPacketDataSerializer.writeShort(this.d); ++ paramPacketDataSerializer.writeByte(this.shift); ++ ++ paramPacketDataSerializer.a(this.item); ++ } ++ ++ public int a() { ++ return this.a; ++ } ++ ++ public int b() { ++ return this.slot; ++ } ++ ++ public int c() { ++ return this.button; ++ } ++ ++ public short d() { ++ return this.d; ++ } ++ ++ public ItemStack e() { ++ return this.item; ++ } ++ ++ public int f() { ++ return this.shift; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java b/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java +index 314a2de..23a406f 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java +@@ -31,7 +31,8 @@ public class PacketPlayOutAttachEntity implements Packet + { + packetdataserializer.writeInt(this.b); + packetdataserializer.writeInt(this.c); +- packetdataserializer.writeByte(this.a); ++ if (packetdataserializer.version == 47) ++ packetdataserializer.writeByte(this.a); + } + + public void a(PacketListenerPlayOut packetlistenerplayout) +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java b/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java +new file mode 100644 +index 0000000..4622309 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java +@@ -0,0 +1,80 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++import org.bukkit.craftbukkit.util.CraftChatMessage; ++ ++public class PacketPlayOutCombatEvent ++ implements Packet ++{ ++ public EnumCombatEventType a; ++ public int b; ++ public int c; ++ public int d; ++ public String e; ++ ++ public PacketPlayOutCombatEvent() ++ { ++ } ++ ++ public PacketPlayOutCombatEvent(CombatTracker paramCombatTracker, EnumCombatEventType paramEnumCombatEventType) ++ { ++ this.a = paramEnumCombatEventType; ++ ++ EntityLiving localEntityLiving = paramCombatTracker.c(); ++ ++ switch (paramEnumCombatEventType.ordinal()) { ++ case 1: ++ this.d = paramCombatTracker.f(); ++ this.c = (localEntityLiving == null ? -1 : localEntityLiving.getId()); ++ break; ++ case 2: ++ this.b = paramCombatTracker.h().getId(); ++ this.c = (localEntityLiving == null ? -1 : localEntityLiving.getId()); ++ this.e = paramCombatTracker.b().c(); ++ } ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ this.a = ((EnumCombatEventType)paramPacketDataSerializer.a(EnumCombatEventType.class)); ++ ++ if (this.a == EnumCombatEventType.END_COMBAT) { ++ this.d = paramPacketDataSerializer.e(); ++ this.c = paramPacketDataSerializer.readInt(); ++ } else if (this.a == EnumCombatEventType.ENTITY_DIED) { ++ this.b = paramPacketDataSerializer.e(); ++ this.c = paramPacketDataSerializer.readInt(); ++ this.e = paramPacketDataSerializer.c(32767); ++ } ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.a(this.a); ++ ++ if (this.a == EnumCombatEventType.END_COMBAT) { ++ paramPacketDataSerializer.b(this.d); ++ paramPacketDataSerializer.writeInt(this.c); ++ } else if (this.a == EnumCombatEventType.ENTITY_DIED) { ++ paramPacketDataSerializer.b(this.b); ++ paramPacketDataSerializer.writeInt(this.c); ++ if (paramPacketDataSerializer.version == 47) ++ paramPacketDataSerializer.a(this.e); ++ else ++ { ++ paramPacketDataSerializer.a(CraftChatMessage.fromString(this.e)[0]); ++ } ++ } ++ } ++ ++ public void a(PacketListenerPlayOut paramPacketListenerPlayOut) ++ { ++ paramPacketListenerPlayOut.a(this); ++ } ++ ++ public static enum EnumCombatEventType ++ { ++ ENTER_COMBAT, END_COMBAT, ENTITY_DIED; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java b/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java +new file mode 100644 +index 0000000..29b1e5c +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java +@@ -0,0 +1,45 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayOutCustomPayload ++ implements Packet ++{ ++ public String a; ++ public PacketDataSerializer b; ++ ++ public PacketPlayOutCustomPayload() ++ { ++ } ++ ++ public PacketPlayOutCustomPayload(String paramString, PacketDataSerializer paramPacketDataSerializer) ++ { ++ this.a = paramString; ++ this.b = paramPacketDataSerializer; ++ ++ if (paramPacketDataSerializer.writerIndex() > 1048576) ++ throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ this.a = paramPacketDataSerializer.c(20); ++ int i = paramPacketDataSerializer.readableBytes(); ++ if ((i < 0) || (i > 1048576)) { ++ throw new IOException("Payload may not be larger than 1048576 bytes"); ++ } ++ this.b = new PacketDataSerializer(paramPacketDataSerializer.readBytes(i)); ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.a(this.a); ++ paramPacketDataSerializer.writeBytes(this.b); ++ } ++ ++ public void a(PacketListenerPlayOut paramPacketListenerPlayOut) ++ { ++ paramPacketListenerPlayOut.a(this); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java b/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java +index ecc2e78..bb41d9d 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java +@@ -24,7 +24,11 @@ public class PacketPlayOutEntityEquipment implements Packet ++{ ++ public int a; ++ public byte b; ++ public MapIcon[] c; ++ public int d; ++ public int e; ++ public int f; ++ public int g; ++ public byte[] h; ++ ++ public PacketPlayOutMap() ++ { ++ } ++ ++ public PacketPlayOutMap(int paramInt1, byte paramByte, Collection paramCollection, byte[] paramArrayOfByte, int paramInt2, int paramInt3, int paramInt4, int paramInt5) ++ { ++ this.a = paramInt1; ++ this.b = paramByte; ++ this.c = ((MapIcon[])paramCollection.toArray(new MapIcon[paramCollection.size()])); ++ this.d = paramInt2; ++ this.e = paramInt3; ++ this.f = paramInt4; ++ this.g = paramInt5; ++ ++ this.h = new byte[paramInt4 * paramInt5]; ++ for (int i = 0; i < paramInt4; i++) ++ for (int j = 0; j < paramInt5; j++) ++ this.h[(i + j * paramInt4)] = paramArrayOfByte[(paramInt2 + i + (paramInt3 + j) * 128)]; ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) ++ throws IOException ++ { ++ this.a = paramPacketDataSerializer.e(); ++ this.b = paramPacketDataSerializer.readByte(); ++ this.c = new MapIcon[paramPacketDataSerializer.e()]; ++ for (int i = 0; i < this.c.length; i++) { ++ int j = (short)paramPacketDataSerializer.readByte(); ++ this.c[i] = new MapIcon((byte)(j >> 4 & 0xF), paramPacketDataSerializer.readByte(), paramPacketDataSerializer.readByte(), (byte)(j & 0xF)); ++ } ++ this.f = paramPacketDataSerializer.readUnsignedByte(); ++ if (this.f > 0) { ++ this.g = paramPacketDataSerializer.readUnsignedByte(); ++ this.d = paramPacketDataSerializer.readUnsignedByte(); ++ this.e = paramPacketDataSerializer.readUnsignedByte(); ++ this.h = paramPacketDataSerializer.a(); ++ } ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.b(this.a); ++ paramPacketDataSerializer.writeByte(this.b); ++ paramPacketDataSerializer.b(this.c.length); ++ if (paramPacketDataSerializer.version != 47) ++ { ++ paramPacketDataSerializer.writeBoolean(this.c.length > 0); ++ } ++ for (MapIcon localMapIcon : this.c) { ++ paramPacketDataSerializer.writeByte((localMapIcon.getType() & 0xF) << 4 | localMapIcon.getRotation() & 0xF); ++ paramPacketDataSerializer.writeByte(localMapIcon.getX()); ++ paramPacketDataSerializer.writeByte(localMapIcon.getY()); ++ } ++ paramPacketDataSerializer.writeByte(this.f); ++ if (this.f > 0) { ++ paramPacketDataSerializer.writeByte(this.g); ++ paramPacketDataSerializer.writeByte(this.d); ++ paramPacketDataSerializer.writeByte(this.e); ++ paramPacketDataSerializer.a(this.h); ++ } ++ } ++ ++ public void a(PacketListenerPlayOut paramPacketListenerPlayOut) ++ { ++ paramPacketListenerPlayOut.a(this); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java b/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java +index c72526a..e85c71c 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java +@@ -4,6 +4,8 @@ import com.google.common.collect.Lists; + import java.io.IOException; + import java.util.ArrayList; + import java.util.Iterator; ++import io.netty.buffer.ByteBuf; ++import io.netty.buffer.Unpooled; + + public class PacketPlayOutMapChunk implements Packet { + +@@ -13,15 +15,24 @@ public class PacketPlayOutMapChunk implements Packet { + public boolean d; + public Chunk mapChunk; + ++ public int size9; ++ public byte[] bytes9; ++ + public PacketPlayOutMapChunk() {} + + public PacketPlayOutMapChunk(Chunk chunk, boolean flag, int i) { + this.a = chunk.locX; + this.b = chunk.locZ; + this.d = flag; +- this.c = a(chunk, flag, !chunk.getWorld().worldProvider.o(), i); ++ ++ boolean world = !chunk.getWorld().worldProvider.o(); ++ ++ this.c = a(chunk, flag, world, i); + chunk.world.spigotConfig.antiXrayInstance.obfuscateSync(chunk.locX, chunk.locZ, c.b, c.a, chunk.world); + mapChunk = chunk; ++ ++ this.bytes9 = new byte[a9(chunk, flag, world, i)]; ++ this.size9 = a9(new PacketDataSerializer(this.f()), chunk, flag, world, i); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { +@@ -37,8 +48,16 @@ public class PacketPlayOutMapChunk implements Packet { + packetdataserializer.writeInt(this.a); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeBoolean(this.d); ++ ++ if (packetdataserializer.version == 47){ + packetdataserializer.writeShort((short) (this.c.b & '\uffff')); + packetdataserializer.a(this.c.a); ++ } else ++ { ++ packetdataserializer.b(this.size9); ++ packetdataserializer.b(this.bytes9.length); ++ packetdataserializer.writeBytes(this.bytes9); ++ } + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { +@@ -119,4 +138,52 @@ public class PacketPlayOutMapChunk implements Packet { + + public ChunkMap() {} + } ++ private ByteBuf f() { ++ ByteBuf byteBuf = Unpooled.wrappedBuffer(this.bytes9); ++ byteBuf.writerIndex(0); ++ return byteBuf; ++ } ++ ++ public static int a9(PacketDataSerializer dataSerializer, Chunk chunk, boolean bl, boolean bl2, int n) { ++ int n2 = 0; ++ ChunkSection[] sectionArray = chunk.getSections(); ++ ++ for (int i = 0; i < sectionArray.length; ++i) { ++ ChunkSection section = sectionArray[i]; ++ if (section == null || bl && section.a()) continue; ++ if ((n & 1 << i) == 0) continue; ++ n2|=1 << i; ++ ++ section.writeSerializer(dataSerializer); ++ ++ dataSerializer.writeBytes(section.getEmittedLightArray().a()); ++ if (!bl2) continue; ++ dataSerializer.writeBytes(section.getSkyLightArray().a()); ++ } ++ if (bl) { ++ dataSerializer.writeBytes(chunk.getBiomeIndex()); ++ } ++ return n2; ++ } ++ ++ protected static int a9(Chunk chunk, boolean bl, boolean bl2, int n) { ++ int n2 = 0; ++ ChunkSection[] sectionArray = chunk.getSections(); ++ ++ for (int i = 0; i < sectionArray.length; ++i) { ++ ChunkSection section = sectionArray[i]; ++ if (section == null || bl && section.a()) continue; ++ if ((n & 1 << i) == 0) continue; ++ ++ n2 += section.getLength(); ++ ++ n2+=section.getEmittedLightArray().a().length; ++ if (!bl2) continue; ++ n2+=section.getSkyLightArray().a().length; ++ } ++ if (bl) { ++ n2+=chunk.getBiomeIndex().length; ++ } ++ return n2; ++ } + } +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java b/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java +index 277d1f2..340787a 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java +@@ -53,7 +53,8 @@ public class PacketPlayOutNamedEntitySpawn implements Packet sounds = new HashMap(); ++ ++ static { ++ sounds.put("ambient.cave.cave", "ambient.cave"); ++ sounds.put("ambient.weather.rain", "weather.rain.above"); ++ sounds.put("ambient.weather.thunder", "entity.lightning.thunder"); ++ sounds.put("dig.cloth", "block.cloth.place"); ++ sounds.put("dig.grass", "block.grass.break"); ++ sounds.put("dig.gravel", "block.gravel.break"); ++ sounds.put("dig.sand", "block.sand.place"); ++ sounds.put("dig.snow", "block.snow.place"); ++ sounds.put("dig.stone", "block.glass.place"); ++ sounds.put("dig.wood", "block.wood.place"); ++ sounds.put("fire.fire", "entity.blaze.burn"); ++ sounds.put("fire.ignite", "item.flintandsteel.use"); ++ sounds.put("fireworks.blast", "entity.firework.blast"); ++ sounds.put("fireworks.blast_far", "entity.firework.blast_far"); ++ sounds.put("fireworks.largeBlast", "entity.firework.large_blast"); ++ sounds.put("fireworks.largeBlast_far", "entity.firework.large_blast_far"); ++ sounds.put("fireworks.launch", "entity.firework.launch"); ++ sounds.put("fireworks.twinkle", "entity.firework.twinkle"); ++ sounds.put("fireworks.twinkle_far", "entity.firework.twinkle_far"); ++ sounds.put("game.hostile.swim", "entity.player.swim"); ++ sounds.put("game.neutral.die", "entity.player.hurt"); ++ sounds.put("game.neutral.hurt.fall.small", "entity.generic.small_fall"); ++ sounds.put("game.neutral.swim.splash", "entity.generic.splash"); ++ sounds.put("game.player.hurt.fall.big", "entity.generic.big_fall"); ++ sounds.put("game.potion.smash", "block.glass.break"); ++ sounds.put("game.tnt.primed", "entity.tnt.primed"); ++ sounds.put("item.fireCharge.use", "item.firecharge.use"); ++ sounds.put("liquid.lava", "block.lava.ambient"); ++ sounds.put("liquid.lavapop", "block.lava.pop"); ++ sounds.put("liquid.water", "block.water.ambient"); ++ sounds.put("minecart.base", "entity.minecart.riding"); ++ sounds.put("minecart.inside", "entity.minecart.inside"); ++ sounds.put("mob.bat.death", "entity.bat.death"); ++ sounds.put("mob.bat.hurt", "entity.bat.hurt"); ++ sounds.put("mob.bat.idle", "entity.bat.ambient"); ++ sounds.put("mob.bat.takeoff", "entity.bat.takeoff"); ++ sounds.put("mob.blaze.breathe", "entity.blaze.ambient"); ++ sounds.put("mob.blaze.death", "entity.blaze.death"); ++ sounds.put("mob.blaze.hit", "entity.blaze.hurt"); ++ sounds.put("mob.cat.hitt", "entity.cat.hurt"); ++ sounds.put("mob.cat.meow", "entity.cat.ambient"); ++ sounds.put("mob.cat.purr", "entity.cat.purr"); ++ sounds.put("mob.cat.purreow", "entity.cat.purreow"); ++ sounds.put("mob.chicken.hurt", "entity.chicken.hurt"); ++ sounds.put("mob.chicken.plop", "entity.chicken.egg"); ++ sounds.put("mob.chicken.say", "entity.chicken.ambient"); ++ sounds.put("mob.chicken.step", "entity.chicken.step"); ++ sounds.put("mob.cow.hurt", "entity.cow.hurt"); ++ sounds.put("mob.cow.say", "entity.cow.ambient"); ++ sounds.put("mob.cow.step", "entity.cow.step"); ++ sounds.put("mob.creeper.death", "entity.creeper.death"); ++ sounds.put("mob.creeper.say", "entity.creeper.hurt"); ++ sounds.put("mob.enderdragon.end", "entity.enderdragon.death"); ++ sounds.put("mob.enderdragon.growl", "entity.enderdragon.growl"); ++ sounds.put("mob.enderdragon.hit", "entity.enderdragon.hurt"); ++ sounds.put("mob.enderdragon.wings", "entity.enderdragon.flap"); ++ sounds.put("mob.endermen.death", "entity.endermen.death"); ++ sounds.put("mob.endermen.hit", "entity.endermen.hurt"); ++ sounds.put("mob.endermen.idle", "entity.endermen.ambient"); ++ sounds.put("mob.endermen.portal", "entity.endermen.teleport"); ++ sounds.put("mob.endermen.scream", "entity.endermen.scream"); ++ sounds.put("mob.endermen.stare", "entity.endermen.stare"); ++ sounds.put("mob.ghast.charge", "entity.ghast.warn"); ++ sounds.put("mob.ghast.death", "entity.ghast.death"); ++ sounds.put("mob.ghast.moan", "entity.ghast.ambient"); ++ sounds.put("mob.ghast.scream", "entity.ghast.hurt"); ++ sounds.put("mob.guardian.attack", "entity.guardian.attack"); ++ sounds.put("mob.guardian.curse", "entity.elder_guardian.curse"); ++ sounds.put("mob.guardian.death", "entity.guardian.death"); ++ sounds.put("mob.guardian.elder.death", "entity.elder_guardian.death"); ++ sounds.put("mob.guardian.elder.hit", "entity.elder_guardian.hurt"); ++ sounds.put("mob.guardian.elder.idle", "entity.elder_guardian.ambient"); ++ sounds.put("mob.guardian.flop", "entity.guardian.flop"); ++ sounds.put("mob.guardian.hit", "entity.guardian.hurt"); ++ sounds.put("mob.guardian.idle", "entity.guardian.ambient"); ++ sounds.put("mob.guardian.land.death", "entity.guardian.death_land"); ++ sounds.put("mob.guardian.land.hit", "entity.elder_guardian.hurt_land"); ++ sounds.put("mob.guardian.land.idle", "entity.elder_guardian.ambient_land"); ++ sounds.put("mob.horse.angry", "entity.horse.angry"); ++ sounds.put("mob.horse.armor", "entity.horse.armor"); ++ sounds.put("mob.horse.breathe", "entity.horse.breathe"); ++ sounds.put("mob.horse.death", "entity.horse.death"); ++ sounds.put("mob.horse.donkey.angry", "entity.donkey.angry"); ++ sounds.put("mob.horse.donkey.death", "entity.mule.death"); ++ sounds.put("mob.horse.donkey.hit", "entity.donkey.hurt"); ++ sounds.put("mob.horse.donkey.idle", "entity.donkey.ambient"); ++ sounds.put("mob.horse.gallop", "entity.horse.gallop"); ++ sounds.put("mob.horse.hit", "entity.horse.hurt"); ++ sounds.put("mob.horse.idle", "entity.horse.ambient"); ++ sounds.put("mob.horse.jump", "entity.horse.jump"); ++ sounds.put("mob.horse.land", "entity.horse.land"); ++ sounds.put("mob.horse.leather", "entity.horse.saddle"); ++ sounds.put("mob.horse.skeleton.death", "entity.skeleton_horse.death"); ++ sounds.put("mob.horse.skeleton.hit", "entity.skeleton_horse.hurt"); ++ sounds.put("mob.horse.skeleton.idle", "entity.skeleton_horse.ambient"); ++ sounds.put("mob.horse.soft", "entity.horse.step"); ++ sounds.put("mob.horse.wood", "entity.horse.step_wood"); ++ sounds.put("mob.horse.zombie.death", "entity.zombie_horse.death"); ++ sounds.put("mob.horse.zombie.hit", "entity.zombie_horse.hurt"); ++ sounds.put("mob.horse.zombie.idle", "entity.zombie_horse.ambient"); ++ sounds.put("mob.irongolem.death", "entity.irongolem.death"); ++ sounds.put("mob.irongolem.hit", "entity.irongolem.hurt"); ++ sounds.put("mob.irongolem.throw", "entity.irongolem.attack"); ++ sounds.put("mob.irongolem.walk", "entity.irongolem.step"); ++ sounds.put("mob.magmacube.big", "entity.magmacube.squish"); ++ sounds.put("mob.magmacube.jump", "entity.magmacube.jump"); ++ sounds.put("mob.magmacube.small", "entity.small_magmacube.squish"); ++ sounds.put("mob.pig.death", "entity.pig.death"); ++ sounds.put("mob.pig.say", "entity.pig.hurt"); ++ sounds.put("mob.pig.step", "entity.pig.step"); ++ sounds.put("mob.rabbit.death", "entity.rabbit.death"); ++ sounds.put("mob.rabbit.hop", "entity.rabbit.jump"); ++ sounds.put("mob.rabbit.hurt", "entity.rabbit.hurt"); ++ sounds.put("mob.rabbit.idle", "entity.rabbit.ambient"); ++ sounds.put("mob.sheep.say", "entity.sheep.death"); ++ sounds.put("mob.sheep.shear", "entity.sheep.shear"); ++ sounds.put("mob.sheep.step", "entity.sheep.step"); ++ sounds.put("mob.silverfish.hit", "entity.endermite.hurt"); ++ sounds.put("mob.silverfish.kill", "entity.silverfish.death"); ++ sounds.put("mob.silverfish.say", "entity.silverfish.ambient"); ++ sounds.put("mob.silverfish.step", "entity.endermite.step"); ++ sounds.put("mob.skeleton.death", "entity.skeleton.death"); ++ sounds.put("mob.skeleton.hurt", "entity.skeleton.hurt"); ++ sounds.put("mob.skeleton.say", "entity.skeleton.ambient"); ++ sounds.put("mob.skeleton.step", "entity.skeleton.step"); ++ sounds.put("mob.slime.attack", "entity.slime.attack"); ++ sounds.put("mob.slime.big", "block.slime.place"); ++ sounds.put("mob.slime.small", "block.slime.fall"); ++ sounds.put("mob.spider.death", "entity.spider.death"); ++ sounds.put("mob.spider.say", "entity.spider.ambient"); ++ sounds.put("mob.spider.step", "entity.spider.step"); ++ sounds.put("mob.villager.death", "entity.villager.death"); ++ sounds.put("mob.villager.haggle", "entity.villager.trading"); ++ sounds.put("mob.villager.hit", "entity.villager.hurt"); ++ sounds.put("mob.villager.idle", "entity.villager.ambient"); ++ sounds.put("mob.villager.no", "entity.villager.no"); ++ sounds.put("mob.villager.yes", "entity.villager.yes"); ++ sounds.put("mob.wither.death", "entity.wither.death"); ++ sounds.put("mob.wither.hurt", "entity.wither.hurt"); ++ sounds.put("mob.wither.idle", "entity.wither.ambient"); ++ sounds.put("mob.wither.shoot", "entity.wither.shoot"); ++ sounds.put("mob.wither.spawn", "entity.wither.spawn"); ++ sounds.put("mob.wolf.bark", "entity.wolf.ambient"); ++ sounds.put("mob.wolf.death", "entity.wolf.death"); ++ sounds.put("mob.wolf.growl", "entity.wolf.growl"); ++ sounds.put("mob.wolf.hurt", "entity.wolf.hurt"); ++ sounds.put("mob.wolf.panting", "entity.wolf.pant"); ++ sounds.put("mob.wolf.shake", "entity.wolf.shake"); ++ sounds.put("mob.wolf.step", "entity.wolf.step"); ++ sounds.put("mob.wolf.whine", "entity.wolf.whine"); ++ sounds.put("mob.zombie.death", "entity.zombie.death"); ++ sounds.put("mob.zombie.hurt", "entity.zombie.hurt"); ++ sounds.put("mob.zombie.infect", "entity.zombie.infect"); ++ sounds.put("mob.zombie.metal", "entity.zombie.attack_iron_door"); ++ sounds.put("mob.zombie.remedy", "entity.zombie.cure"); ++ sounds.put("mob.zombie.say", "entity.zombie.ambient"); ++ sounds.put("mob.zombie.step", "entity.zombie.step"); ++ sounds.put("mob.zombie.unfect", "entity.zombie.unfect"); ++ sounds.put("mob.zombie.wood", "entity.zombie.attack_door_wood"); ++ sounds.put("mob.zombie.woodbreak", "entity.zombie.break_door_wood"); ++ sounds.put("mob.zombiepig.zpig", "entity.zombie_pig.ambient"); ++ sounds.put("mob.zombiepig.zpigangry", "entity.zombie_pig.angry"); ++ sounds.put("mob.zombiepig.zpigdeath", "entity.zombie_pig.death"); ++ sounds.put("mob.zombiepig.zpighurt", "entity.zombie_pig.hurt"); ++ sounds.put("music.game", "music.game"); ++ sounds.put("music.game.creative", "music.creative"); ++ sounds.put("music.game.end", "music.end"); ++ sounds.put("music.game.end.credits", "music.credits"); ++ sounds.put("music.game.end.dragon", "music.dragon"); ++ sounds.put("music.game.nether", "music.nether"); ++ sounds.put("music.menu", "music.menu"); ++ sounds.put("note.bassattack", "block.note.bass"); ++ sounds.put("note.bd", "block.note.basedrum"); ++ sounds.put("note.harp", "block.note.harp"); ++ sounds.put("note.hat", "block.note.hat"); ++ sounds.put("note.snare", "block.note.snare"); ++ sounds.put("portal.portal", "block.portal.ambient"); ++ sounds.put("portal.travel", "block.portal.travel"); ++ sounds.put("portal.trigger", "block.portal.trigger"); ++ sounds.put("random.anvil_break", "block.anvil.destroy"); ++ sounds.put("random.anvil_land", "block.anvil.place"); ++ sounds.put("random.anvil_use", "block.anvil.use"); ++ sounds.put("random.bow", "entity.firework.shoot"); ++ sounds.put("random.bowhit", "block.tripwire.detach"); ++ sounds.put("random.break", "entity.item.break"); ++ sounds.put("random.burp", "entity.player.burp"); ++ sounds.put("random.chestclosed", "block.enderchest.close"); ++ sounds.put("random.chestopen", "block.chest.open"); ++ sounds.put("random.click", "block.stone_pressureplate.click_on"); ++ sounds.put("random.door_close", "block.trapdoor.open"); ++ sounds.put("random.drink", "entity.generic.drink"); ++ sounds.put("random.eat", "entity.generic.eat"); ++ sounds.put("random.explode", "entity.lightning.impact"); ++ sounds.put("random.fizz", "entity.generic.extinguish_fire"); ++ sounds.put("random.levelup", "entity.player.levelup"); ++ sounds.put("random.orb", "entity.experience_orb.touch"); ++ sounds.put("random.pop", "entity.item.pickup"); ++ sounds.put("random.splash", "entity.bobber.splash"); ++ sounds.put("random.successful_hit", "entity.arrow.successful_hit"); ++ sounds.put("random.wood_click", "block.wood_button.click_off"); ++ sounds.put("records.11", "record.11"); ++ sounds.put("records.13", "record.13"); ++ sounds.put("records.blocks", "record.blocks"); ++ sounds.put("records.cat", "record.cat"); ++ sounds.put("records.chirp", "record.chirp"); ++ sounds.put("records.far", "record.far"); ++ sounds.put("records.mall", "record.mall"); ++ sounds.put("records.mellohi", "record.mellohi"); ++ sounds.put("records.stal", "record.stal"); ++ sounds.put("records.strad", "record.strad"); ++ sounds.put("records.wait", "record.wait"); ++ sounds.put("records.ward", "record.ward"); ++ sounds.put("step.cloth", "block.cloth.fall"); ++ sounds.put("step.grass", "block.grass.step"); ++ sounds.put("step.gravel", "block.gravel.hit"); ++ sounds.put("step.ladder", "block.ladder.hit"); ++ sounds.put("step.sand", "block.sand.hit"); ++ sounds.put("step.snow", "block.snow.fall"); ++ sounds.put("step.stone", "block.stone.hit"); ++ sounds.put("step.wood", "block.wood.step"); ++ sounds.put("tile.piston.in", "block.piston.contract"); ++ sounds.put("tile.piston.out", "block.piston.extend"); ++ } ++ + public String a; + public int b; + public int c; +@@ -16,12 +245,13 @@ public class PacketPlayOutNamedSoundEffect + { + c = 0x7fffffff; + } +- ++ private static HashMap so = new HashMap(); + public PacketPlayOutNamedSoundEffect(String s, double d1, double d2, double d3, + float f1, float f2) + { + c = 0x7fffffff; + Validate.notNull(s, "name", new Object[0]); ++ if (!so.containsKey(s) || so.get(s) < System.currentTimeMillis()){so.put(s, System.currentTimeMillis() + 60000); System.out.print("Sound: " + s);} + a = s; + b = (int)(d1 * 8D); + c = (int)(d2 * 8D); +@@ -43,7 +273,11 @@ public class PacketPlayOutNamedSoundEffect + + public void b(PacketDataSerializer packetdataserializer) + { +- packetdataserializer.a(a); ++ String toPlay = a; ++ if (packetdataserializer.version > 47 && sounds.containsKey(toPlay)) ++ toPlay = sounds.get(toPlay); ++ ++ packetdataserializer.a(toPlay); + packetdataserializer.writeInt(b); + packetdataserializer.writeInt(c); + packetdataserializer.writeInt(d); +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutNewAttachEntity.java b/src/main/java/net/minecraft/server/PacketPlayOutNewAttachEntity.java +new file mode 100644 +index 0000000..2467252 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayOutNewAttachEntity.java +@@ -0,0 +1,56 @@ ++package net.minecraft.server; ++ ++import java.io.IOException; ++ ++public class PacketPlayOutNewAttachEntity implements Packet ++{ ++ public int a; ++ public int[] b; ++ ++ public PacketPlayOutNewAttachEntity() ++ { ++ } ++ ++ public PacketPlayOutNewAttachEntity(Entity vehicle, Entity[] riding) ++ { ++ this.a = vehicle.getId(); ++ this.b = new int[riding.length]; ++ ++ for (int i=0; i ++{ ++ public enum EnumPlayerTeleportFlags ++ { ++ ++ X(0), Y(1), Z(2), Y_ROT(3), X_ROT(4); ++ ++ private int f; ++ ++ private EnumPlayerTeleportFlags(int j) ++ { ++ f = j; ++ } ++ ++ private int a() ++ { ++ return 1 << f; ++ } ++ ++ private boolean b(int i) ++ { ++ return (i & a()) == a(); ++ } ++ ++ public static Set a(int i) ++ { ++ EnumSet enumset = EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class); ++ int j = values().length; ++ for(int k = 0; k < j; k++) ++ { ++ EnumPlayerTeleportFlags enumplayerteleportflags = values()[k]; ++ if(enumplayerteleportflags.b(i)) ++ enumset.add(enumplayerteleportflags); ++ } ++ ++ return enumset; ++ } ++ ++ public static int a(Set set) ++ { ++ int i = 0; ++ for(Iterator iterator = set.iterator(); iterator.hasNext();) ++ { ++ EnumPlayerTeleportFlags enumplayerteleportflags = (EnumPlayerTeleportFlags)iterator.next(); ++ i |= enumplayerteleportflags.a(); ++ } ++ ++ return i; ++ } ++ } ++ ++ public double a; ++ public double b; ++ public double c; ++ public float d; ++ public float e; ++ public Set f; ++ ++ public PacketPlayOutPosition() ++ { ++ } ++ ++ public PacketPlayOutPosition(double d1, double d2, double d3, float f1, ++ float f2, Set set) ++ { ++ a = d1; ++ b = d2; ++ c = d3; ++ d = f1; ++ e = f2; ++ f = set; ++ } ++ ++ public void a(PacketDataSerializer packetdataserializer) ++ throws IOException ++ { ++ a = packetdataserializer.readDouble(); ++ b = packetdataserializer.readDouble(); ++ c = packetdataserializer.readDouble(); ++ d = packetdataserializer.readFloat(); ++ e = packetdataserializer.readFloat(); ++ f = EnumPlayerTeleportFlags.a(packetdataserializer.readUnsignedByte()); ++ } ++ ++ public void b(PacketDataSerializer packetdataserializer) ++ throws IOException ++ { ++ packetdataserializer.writeDouble(a); ++ packetdataserializer.writeDouble(b); ++ packetdataserializer.writeDouble(c); ++ packetdataserializer.writeFloat(d); ++ packetdataserializer.writeFloat(e); ++ packetdataserializer.writeByte(EnumPlayerTeleportFlags.a(f)); ++ if (packetdataserializer.version != 47) ++ packetdataserializer.b(0); ++ } ++ ++ public void a(PacketListenerPlayOut packetlistenerplayout) ++ { ++ packetlistenerplayout.a(this); ++ } ++} +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java b/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java +index f300bfc..7ef913f 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java +@@ -12,6 +12,7 @@ public class PacketPlayOutScoreboardTeam + public String c = ""; + public String d = ""; + public String e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; ++ public String collision = "never"; + public int f = -1; + public Collection g = Lists.newArrayList(); + public int h; +@@ -85,6 +86,10 @@ public class PacketPlayOutScoreboardTeam + paramPacketDataSerializer.a(this.c); + paramPacketDataSerializer.a(this.d); + paramPacketDataSerializer.writeByte(this.i); ++ if (paramPacketDataSerializer.version != 47) ++ { ++ paramPacketDataSerializer.a(collision); ++ } + paramPacketDataSerializer.a(this.e); + paramPacketDataSerializer.writeByte(this.f); + } +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java +index 56eeff6..0c60066 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java +@@ -1,6 +1,7 @@ + package net.minecraft.server; + + import java.io.IOException; ++import java.util.UUID; + + public class PacketPlayOutSpawnEntity implements Packet { + +@@ -15,6 +16,7 @@ public class PacketPlayOutSpawnEntity implements Packet { + public int i; + public int j; + public int k; ++ public UUID uuid; + + public PacketPlayOutSpawnEntity() {} + +@@ -31,6 +33,8 @@ public class PacketPlayOutSpawnEntity implements Packet { + this.i = MathHelper.d((entity.isFakeHead() ? entity.fakeYaw : entity.yaw) * 256.0F / 360.0F); + this.j = i; + this.k = j; ++ this.uuid = entity.getUniqueID(); ++ + if (j > 0) { + double d0 = entity.motX; + double d1 = entity.motY; +@@ -65,7 +69,6 @@ public class PacketPlayOutSpawnEntity implements Packet { + this.f = (int) (d1 * 8000.0D); + this.g = (int) (d2 * 8000.0D); + } +- + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { +@@ -87,6 +90,8 @@ public class PacketPlayOutSpawnEntity implements Packet { + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); ++ if (packetdataserializer.version != 47) ++ packetdataserializer.a(this.uuid); + packetdataserializer.writeByte(this.j); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeInt(this.c); +@@ -94,7 +99,7 @@ public class PacketPlayOutSpawnEntity implements Packet { + packetdataserializer.writeByte(this.h); + packetdataserializer.writeByte(this.i); + packetdataserializer.writeInt(this.k); +- if (this.k > 0) { ++ if (packetdataserializer.version != 47 || this.k > 0) { + packetdataserializer.writeShort(this.e); + packetdataserializer.writeShort(this.f); + packetdataserializer.writeShort(this.g); +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java +index 286ad09..9da448e 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java +@@ -2,6 +2,7 @@ package net.minecraft.server; + + import java.io.IOException; + import java.util.List; ++import java.util.UUID; + + public class PacketPlayOutSpawnEntityLiving implements Packet { + +@@ -18,6 +19,7 @@ public class PacketPlayOutSpawnEntityLiving implements Packet m; ++ public UUID uuid; + + public PacketPlayOutSpawnEntityLiving() {} + +@@ -34,6 +36,7 @@ public class PacketPlayOutSpawnEntityLiving implements Packet ++{ ++ public int a; ++ public int b; ++ ++ public PacketPlayOutUnloadChunk() ++ { ++ } ++ ++ public PacketPlayOutUnloadChunk(int paramInt1, int paramInt2) ++ { ++ this.a = paramInt1; ++ this.b = paramInt2; ++ } ++ ++ public void a(PacketListenerPlayOut paramPacketListenerPlayOut) ++ { ++ paramPacketListenerPlayOut.a(this); ++ } ++ ++ public void a(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ } ++ ++ public void b(PacketDataSerializer paramPacketDataSerializer) throws IOException ++ { ++ paramPacketDataSerializer.writeInt(this.a); ++ paramPacketDataSerializer.writeInt(this.b); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java b/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java +index ebf08f6..9a3b275 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java +@@ -6,6 +6,7 @@ + package net.minecraft.server; + + import java.io.IOException; ++import org.bukkit.craftbukkit.util.CraftChatMessage; + + // Referenced classes of package net.minecraft.server.v1_8_R3: + // Packet, IChatBaseComponent, PacketDataSerializer, PacketListenerPlayOut, +@@ -14,6 +15,9 @@ import java.io.IOException; + public class PacketPlayOutUpdateSign + implements Packet + { ++ public World a; ++ public BlockPosition b; ++ public IChatBaseComponent c[]; + + public PacketPlayOutUpdateSign() + { +@@ -34,7 +38,12 @@ public class PacketPlayOutUpdateSign + b = packetdataserializer.c(); + c = new IChatBaseComponent[4]; + for(int i = 0; i < 4; i++) +- c[i] = packetdataserializer.d(); ++ { ++ if (packetdataserializer.version == 47) ++ c[i] = packetdataserializer.d(); ++ else ++ c[i] = CraftChatMessage.fromString(packetdataserializer.c(50))[0]; ++ } + + } + +@@ -43,7 +52,16 @@ public class PacketPlayOutUpdateSign + { + packetdataserializer.a(b); + for(int i = 0; i < 4; i++) +- packetdataserializer.a(c[i]); ++ { ++ if (packetdataserializer.version == 47) ++ { ++ packetdataserializer.a(c[i]); ++ } ++ else ++ { ++ packetdataserializer.a(c[i]); ++ } ++ } + + } + +@@ -56,8 +74,4 @@ public class PacketPlayOutUpdateSign + { + a((PacketListenerPlayOut)packetlistener); + } +- +- public World a; +- public BlockPosition b; +- public IChatBaseComponent c[]; + } +diff --git a/src/main/java/net/minecraft/server/PacketStatusListener.java b/src/main/java/net/minecraft/server/PacketStatusListener.java +index e4bff04..ea99925 100644 +--- a/src/main/java/net/minecraft/server/PacketStatusListener.java ++++ b/src/main/java/net/minecraft/server/PacketStatusListener.java +@@ -121,7 +121,7 @@ public class PacketStatusListener implements PacketStatusInListener { + ping.setFavicon(event.icon.value); + ping.setMOTD(new ChatComponentText(event.getMotd())); + ping.setPlayerSample(playerSample); +- ping.setServerInfo(new ServerPing.ServerData(minecraftServer.getServerModName() + " " + minecraftServer.getVersion(), 47)); // TODO: Update when protocol changes ++ ping.setServerInfo(new ServerPing.ServerData(minecraftServer.getServerModName() + " " + minecraftServer.getVersion(), networkManager.getVersion())); // TODO: Update when protocol changes + + this.networkManager.handle(new PacketStatusOutServerInfo(ping)); + // CraftBukkit end +diff --git a/src/main/java/net/minecraft/server/PlayerChunkMap.java b/src/main/java/net/minecraft/server/PlayerChunkMap.java +index abb24c8..2d8db9c 100644 +--- a/src/main/java/net/minecraft/server/PlayerChunkMap.java ++++ b/src/main/java/net/minecraft/server/PlayerChunkMap.java +@@ -386,7 +386,12 @@ public class PlayerChunkMap { + Chunk chunk = PlayerChunkMap.this.world.getChunkAt(this.location.x, this.location.z); + + if (chunk.isReady()) { +- entityplayer.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk, true, 0)); ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47) ++ { ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutUnloadChunk(chunk.locX, chunk.locZ)); ++ } ++ else ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk, true, 0)); + } + + this.players.remove(entityplayer); // CraftBukkit +diff --git a/src/main/java/net/minecraft/server/PlayerConnection.java b/src/main/java/net/minecraft/server/PlayerConnection.java +index 5edef3e..a8c5b44 100644 +--- a/src/main/java/net/minecraft/server/PlayerConnection.java ++++ b/src/main/java/net/minecraft/server/PlayerConnection.java +@@ -386,7 +386,7 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + f3 = packetplayinflying.e(); + } + +- this.player.l(); ++ //this.player.l(); + this.player.setLocation(this.o, this.p, this.q, f2, f3); + if (!this.checkMovement) { + return; +@@ -692,6 +692,7 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + EnumDirection enumdirection = EnumDirection.fromType1(packetplayinblockplace.getFace()); + + this.player.resetIdleTimer(); ++ // Never called by 1.9 + if (packetplayinblockplace.getFace() == 255) { + if (itemstack == null) { + return; +@@ -701,41 +702,41 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + int itemstackAmount = itemstack.count; + // Spigot start - skip the event if throttled + if (!throttled) { +- // Raytrace to look for 'rogue armswings' +- float f1 = this.player.pitch; +- float f2 = this.player.yaw; +- double d0 = this.player.locX; +- double d1 = this.player.locY + (double) this.player.getHeadHeight(); +- double d2 = this.player.locZ; +- Vec3D vec3d = new Vec3D(d0, d1, d2); +- +- float f3 = MathHelper.cos(-f2 * 0.017453292F - 3.1415927F); +- float f4 = MathHelper.sin(-f2 * 0.017453292F - 3.1415927F); +- float f5 = -MathHelper.cos(-f1 * 0.017453292F); +- float f6 = MathHelper.sin(-f1 * 0.017453292F); +- float f7 = f4 * f5; +- float f8 = f3 * f5; +- double d3 = player.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.CREATIVE ? 5.0D : 4.5D; +- Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); +- MovingObjectPosition movingobjectposition = this.player.world.rayTrace(vec3d, vec3d1, false); +- +- boolean cancelled = false; +- if (movingobjectposition == null || movingobjectposition.type != MovingObjectPosition.EnumMovingObjectType.BLOCK) { +- org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.RIGHT_CLICK_AIR, itemstack); +- cancelled = event.useItemInHand() == Event.Result.DENY; +- } else { +- if (player.playerInteractManager.firedInteract) { +- player.playerInteractManager.firedInteract = false; +- cancelled = player.playerInteractManager.interactResult; +- } else { +- org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, movingobjectposition.a(), movingobjectposition.direction, itemstack, true); ++ // Raytrace to look for 'rogue armswings' ++ float f1 = this.player.pitch; ++ float f2 = this.player.yaw; ++ double d0 = this.player.locX; ++ double d1 = this.player.locY + (double) this.player.getHeadHeight(); ++ double d2 = this.player.locZ; ++ Vec3D vec3d = new Vec3D(d0, d1, d2); ++ ++ float f3 = MathHelper.cos(-f2 * 0.017453292F - 3.1415927F); ++ float f4 = MathHelper.sin(-f2 * 0.017453292F - 3.1415927F); ++ float f5 = -MathHelper.cos(-f1 * 0.017453292F); ++ float f6 = MathHelper.sin(-f1 * 0.017453292F); ++ float f7 = f4 * f5; ++ float f8 = f3 * f5; ++ double d3 = player.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.CREATIVE ? 5.0D : 4.5D; ++ Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); ++ MovingObjectPosition movingobjectposition = this.player.world.rayTrace(vec3d, vec3d1, false); ++ ++ boolean cancelled = false; ++ if (this.networkManager.getVersion() == 47 && (movingobjectposition == null || movingobjectposition.type != MovingObjectPosition.EnumMovingObjectType.BLOCK)) { ++ org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.RIGHT_CLICK_AIR, itemstack); + cancelled = event.useItemInHand() == Event.Result.DENY; ++ } else { ++ if (player.playerInteractManager.firedInteract) { ++ player.playerInteractManager.firedInteract = false; ++ cancelled = player.playerInteractManager.interactResult; ++ } else { ++ org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, movingobjectposition.a(), movingobjectposition.direction, itemstack, true); ++ cancelled = event.useItemInHand() == Event.Result.DENY; ++ } + } +- } + +- if (!cancelled) { +- this.player.playerInteractManager.useItem(this.player, this.player.world, itemstack); +- } ++ if (!cancelled) { ++ this.player.playerInteractManager.useItem(this.player, this.player.world, itemstack); ++ } + } + // Spigot end + +@@ -788,7 +789,7 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + this.player.activeContainer.b(); + this.player.g = false; + // CraftBukkit - TODO CHECK IF NEEDED -- new if structure might not need 'always'. Kept it in for now, but may be able to remove in future +- if (!ItemStack.matches(this.player.inventory.getItemInHand(), packetplayinblockplace.getItemStack()) || always) { ++ if (this.networkManager.getVersion() == 47 && !ItemStack.matches(this.player.inventory.getItemInHand(), packetplayinblockplace.getItemStack()) || always) { + this.sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, slot.rawSlotIndex, this.player.inventory.getItemInHand())); + } + } +@@ -1992,7 +1993,7 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + + itemstack1 = this.player.inventory.getItemInHand(); + if (itemstack1 != null) { +- if (itemstack.getItem() == Items.WRITTEN_BOOK && itemstack1.getItem() == Items.WRITABLE_BOOK) { ++ if (itemstack.getItem() == (networkManager.getVersion() == 47 ? Items.WRITTEN_BOOK : Items.WRITABLE_BOOK) && itemstack1.getItem() == Items.WRITABLE_BOOK) { + // CraftBukkit start + itemstack1 = new ItemStack(Items.WRITTEN_BOOK); + itemstack1.a("author", (NBTBase) (new NBTTagString(this.player.getName()))); +@@ -2247,4 +2248,65 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + + } + } ++ ++ public void a(PacketPlayInUnknownFloats paramPacketPlayInUnknownFloats){System.out.print("Received unknown floats");} ++ ++ public void a(PacketPlayInUnknownPosition paramPacketPlayInUnknownPosition){System.out.print("Received unknown position");} ++ ++ public void a(PacketPlayInLeftClick paramPacketPlayInLeftClick){System.out.print("Received left click");} ++ ++ public void a(PacketPlayInRightClick paramPacketPlayInRightClick) ++ { ++ PlayerConnectionUtils.ensureMainThread(paramPacketPlayInRightClick, this, this.player.u()); ++ // CraftBukkit - if rightclick decremented the item, always send the update packet. */ ++ // this is not here for CraftBukkit's own functionality; rather it is to fix ++ // a notch bug where the item doesn't update correctly. ++ boolean always = false; ++ // CraftBukkit end ++ ++ ItemStack itemstack = this.player.inventory.getItemInHand(); ++ boolean flag = false; ++ ++ this.player.resetIdleTimer(); ++ // Never called by 1.9 ++ if (itemstack == null) { ++ return; ++ } ++ ++ // CraftBukkit start ++ int itemstackAmount = itemstack.count; ++ // Raytrace to look for 'rogue armswings' ++ float f1 = this.player.pitch; ++ float f2 = this.player.yaw; ++ double d0 = this.player.locX; ++ double d1 = this.player.locY + (double) this.player.getHeadHeight(); ++ double d2 = this.player.locZ; ++ Vec3D vec3d = new Vec3D(d0, d1, d2); ++ ++ float f3 = MathHelper.cos(-f2 * 0.017453292F - 3.1415927F); ++ float f4 = MathHelper.sin(-f2 * 0.017453292F - 3.1415927F); ++ float f5 = -MathHelper.cos(-f1 * 0.017453292F); ++ float f6 = MathHelper.sin(-f1 * 0.017453292F); ++ float f7 = f4 * f5; ++ float f8 = f3 * f5; ++ double d3 = player.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.CREATIVE ? 5.0D : 4.5D; ++ Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); ++ MovingObjectPosition movingobjectposition = this.player.world.rayTrace(vec3d, vec3d1, false); ++ ++ boolean cancelled = false; ++ if (movingobjectposition == null || movingobjectposition.type != MovingObjectPosition.EnumMovingObjectType.BLOCK) { ++ org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.RIGHT_CLICK_AIR, itemstack); ++ cancelled = event.useItemInHand() == Event.Result.DENY; ++ } ++ ++ if (!cancelled) { ++ this.player.playerInteractManager.useItem(this.player, this.player.world, itemstack); ++ } ++ // Spigot end ++ ++ // CraftBukkit - notch decrements the counter by 1 in the above method with food, ++ // snowballs and so forth, but he does it in a place that doesn't cause the ++ // inventory update packet to get sent ++ always = (itemstack.count != itemstackAmount) || itemstack.getItem() == Item.getItemOf(Blocks.WATERLILY); ++ } + } +diff --git a/src/main/java/net/minecraft/server/RegistryID.java b/src/main/java/net/minecraft/server/RegistryID.java +new file mode 100644 +index 0000000..86453bf +--- /dev/null ++++ b/src/main/java/net/minecraft/server/RegistryID.java +@@ -0,0 +1,50 @@ ++package net.minecraft.server; ++ ++import com.google.common.base.Predicates; ++import com.google.common.collect.Iterators; ++import com.google.common.collect.Lists; ++import java.util.IdentityHashMap; ++import java.util.Iterator; ++import java.util.List; ++ ++public class RegistryID ++ implements Registry ++{ ++ private final IdentityHashMap a = new IdentityHashMap(512); ++ private final List b = Lists.newArrayList(); ++ ++ public void a(T paramT, int paramInt) { ++ this.a.put(paramT, Integer.valueOf(paramInt)); ++ ++ while (this.b.size() <= paramInt) { ++ this.b.add(null); ++ } ++ ++ this.b.set(paramInt, paramT); ++ } ++ ++ public int b(T paramT) ++ { ++ Integer localInteger = (Integer)this.a.get(paramT); ++ return localInteger == null ? -1 : localInteger.intValue(); ++ } ++ ++ public final T a(int paramInt) ++ { ++ if ((paramInt >= 0) && (paramInt < this.b.size())) { ++ return this.b.get(paramInt); ++ } ++ ++ return null; ++ } ++ ++ public Iterator iterator() ++ { ++ return Iterators.filter(this.b.iterator(), Predicates.notNull()); ++ } ++ ++ public int a() ++ { ++ return this.a.size(); ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/World.java b/src/main/java/net/minecraft/server/World.java +index eca86db..e61032c 100644 +--- a/src/main/java/net/minecraft/server/World.java ++++ b/src/main/java/net/minecraft/server/World.java +@@ -1347,6 +1347,11 @@ public abstract class World implements IBlockAccess { + CrashReport crashreport; + CrashReportSystemDetails crashreportsystemdetails; + ++ for (EntityHuman player : players) ++ { ++ ((EntityPlayer) player).l(); ++ } ++ + for (i = 0; i < this.k.size(); ++i) { + entity = (Entity) this.k.get(i); + // CraftBukkit start - Fixed an NPE +diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +index efbf1a8..dbc7b54 100644 +--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java ++++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +@@ -1,6 +1,7 @@ + package org.bukkit.craftbukkit.entity; + + import com.google.common.base.Preconditions; ++import com.google.common.primitives.Doubles; + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; +@@ -234,6 +235,12 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { + // If this entity is riding another entity, we must dismount before teleporting. + entity.mount(null); + ++ if (!Doubles.isFinite(location.getX()) || !Doubles.isFinite(location.getY()) || !Doubles.isFinite(location.getZ())) ++ { ++ Thread.dumpStack(); ++ return false; ++ } ++ + // Spigot start + if (!location.getWorld().equals(getWorld())) { + entity.teleportTo(location, cause.equals(TeleportCause.NETHER_PORTAL)); +diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java +index 76a9bdb..473f574 100644 +--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java ++++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java +@@ -26,7 +26,7 @@ public class CraftFirework extends CraftEntity implements Firework { + + if (item == null) { + item = new ItemStack(Items.FIREWORKS); +- getHandle().getDataWatcher().watch(FIREWORK_ITEM_INDEX, item); ++ getHandle().setFireworkItem(item); + } + + this.item = CraftItemStack.asCraftMirror(item); +diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +index e979f69..42f0a58 100644 +--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java ++++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +@@ -1301,7 +1301,7 @@ public class CraftPlayer extends CraftHumanEntity implements Player { + + injectScaledMaxHealth(set, true); + +- getHandle().getDataWatcher().watch(6, (float) getScaledHealth()); ++ getHandle().getDataWatcher().watch(6, (float) getScaledHealth(), getHandle().META_HEALTH, (float) getScaledHealth()); + getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateHealth(getScaledHealth(), getHandle().getFoodData().getFoodLevel(), getHandle().getFoodData().getSaturationLevel())); + getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateAttributes(getHandle().getId(), set)); + +diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java +index 18da426..79bd517 100644 +--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java ++++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java +@@ -29,7 +29,7 @@ public class CraftThrownPotion extends CraftProjectile implements ThrownPotion { + // We run this method once since it will set the item stack if there is none. + getHandle().getPotionValue(); + +- return CraftItemStack.asBukkitCopy(getHandle().item); ++ return CraftItemStack.asBukkitCopy(getHandle().getItem()); + } + + public void setItem(ItemStack item) { +@@ -39,7 +39,7 @@ public class CraftThrownPotion extends CraftProjectile implements ThrownPotion { + // The ItemStack must be a potion. + Validate.isTrue(item.getType() == Material.POTION, "ItemStack must be a potion. This item stack was " + item.getType() + "."); + +- getHandle().item = CraftItemStack.asNMSCopy(item); ++ getHandle().setItem(CraftItemStack.asNMSCopy(item)); + } + + @Override +-- +1.9.5.msysgit.0 + diff --git a/Patches/CraftBukkit-Patches/0178-Added-new-stuff-elytra-and-levitation.patch b/Patches/CraftBukkit-Patches/0178-Added-new-stuff-elytra-and-levitation.patch new file mode 100644 index 000000000..e37255cc5 --- /dev/null +++ b/Patches/CraftBukkit-Patches/0178-Added-new-stuff-elytra-and-levitation.patch @@ -0,0 +1,1380 @@ +From db79f5bc9cf52fa7bb9cf080e206d88641fa0617 Mon Sep 17 00:00:00 2001 +From: libraryaddict +Date: Wed, 30 Dec 2015 21:06:12 +1300 +Subject: [PATCH] Added new stuff, elytra and levitation + + +diff --git a/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java b/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java +index 81954a4..34faf5e 100644 +--- a/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java ++++ b/src/main/java/com/mineplex/spigot/MineplexTranslateItem.java +@@ -101,7 +101,10 @@ public class MineplexTranslateItem + { + if (itemstack == null || itemstack.getItem() == null || serializer.version == 47) + { +- writeItemStack(serializer, itemstack); ++ if (itemstack != null && itemstack.getItem() != null && serializer.version == 47 && Item.getId(itemstack.getItem()) == 443) ++ writeItemStack(serializer, new ItemStack(Item.getById(1))); ++ else ++ writeItemStack(serializer, itemstack); + return; + } + +@@ -145,9 +148,6 @@ public class MineplexTranslateItem + case 373: + sendPotion(serializer, itemstack.cloneItemStack()); + return; +- case 387: +- //sendBook(serializer, itemstack.cloneItemStack()); +- //return; + default: + break; + } +@@ -445,117 +445,6 @@ public class MineplexTranslateItem + potionNames[126] = "minecraft:long_invisibility"; + potionNames[127] = null; + +- // b[0] = 0; +- // b[1] = 8193; +- // b[2] = 8194; +- // b[3] = 8195; +- // b[4] = 8196; +- // b[5] = 8197; +- // b[6] = 8198; +- // b[8] = 8200; +- // b[9] = 8265; +- // b[10] = 8202; +- // b[11] = 8203; +- // b[12] = 8204; +- // b[13] = 8205; +- // b[14] = 8206; +- // b[16] = 8207; +- // b[17] = 8193; +- // b[18] = 8194; +- // b[19] = 8195; +- // b[20] = 8196; +- // b[21] = 8197; +- // b[22] = 8198; +- // b[24] = 8200; +- // b[25] = 8265; +- // b[26] = 8202; +- // b[27] = 8203; +- // b[28] = 8204; +- // b[29] = 8205; +- // b[30] = 8206; +- // b[32] = "minecraft:thick"; +- // b[33] = 8225; +- // b[34] = 8226; +- // b[35] = 8195; +- // b[36] = 8228; +- // b[37] = 8229; +- // b[38] = 8198; +- // b[40] = 8200; +- // b[41] = 8233; +- // b[42] = 8202; +- // b[43] = 8235; +- // b[44] = 8236; +- // b[45] = 8205; +- // b[46] = 8206; +- // b[49] = 8225; +- // b[50] = 8226; +- // b[51] = 8195; +- // b[52] = 8228; +- // b[53] = 8229; +- // b[54] = 8198; +- // b[56] = 8200; +- // b[57] = 8233; +- // b[58] = 8202; +- // b[59] = 8235; +- // b[60] = 8236; +- // b[61] = 8205; +- // b[62] = 8206; +- // b[64] = "minecraft:mundane"; +- // b[65] = 8257; +- // b[66] = 8258; +- // b[67] = 8259; +- // b[68] = 8260; +- // b[69] = 8197; +- // b[70] = 8198; +- // b[72] = 8264; +- // b[73] = 8265; +- // b[74] = 8266; +- // b[75] = 8267; +- // b[76] = 8204; +- // b[77] = 8269; +- // b[78] = 8270; +- // b[80] = "minecraft:awkward"; +- // b[81] = 8257; +- // b[82] = 8258; +- // b[83] = 8259; +- // b[84] = 8260; +- // b[85] = 8197; +- // b[86] = 8198; +- // b[88] = 8264; +- // b[89] = 8265; +- // b[90] = 8266; +- // b[91] = 8267; +- // b[92] = 8204; +- // b[93] = 8269; +- // b[94] = 8270; +- // b[96] = "minecraft:thick"; +- // b[97] = 8193; +- // b[98] = 8194; +- // b[99] = 8259; +- // b[100] = 8196; +- // b[101] = 8229; +- // b[102] = 8198; +- // b[104] = 8264; +- // b[105] = 8265; +- // b[106] = 8266; +- // b[107] = 8203; +- // b[108] = 8236; +- // b[109] = 8269; +- // b[110] = 8270; +- // b[113] = 8193; +- // b[114] = 8194; +- // b[115] = 8259; +- // b[116] = 8196; +- // b[117] = 8229; +- // b[118] = 8198; +- // b[120] = 8264; +- // b[121] = 8265; +- // b[122] = 8266; +- // b[123] = 8203; +- // b[124] = 8236; +- // b[125] = 8269; +- // b[126] = 8270; +- + try + { + Field field = EntityTypes.class.getDeclaredField("g"); +diff --git a/src/main/java/net/minecraft/server/DedicatedServer.java b/src/main/java/net/minecraft/server/DedicatedServer.java +index b86369b..4301bc9 100644 +--- a/src/main/java/net/minecraft/server/DedicatedServer.java ++++ b/src/main/java/net/minecraft/server/DedicatedServer.java +@@ -137,6 +137,7 @@ public class DedicatedServer extends MinecraftServer implements IMinecraftServer + this.p.b(); + return false; + } else { ++ Item.REGISTRY.a(443, new MinecraftKey("elytra"), new ItemArmor(ItemArmor.EnumArmorMaterial.ELYTRA, 5, 1).c("elytra")); + if (this.T()) { + this.c("127.0.0.1"); + } else { +diff --git a/src/main/java/net/minecraft/server/Entity.java b/src/main/java/net/minecraft/server/Entity.java +index 96d9312..2f52ea2 100644 +--- a/src/main/java/net/minecraft/server/Entity.java ++++ b/src/main/java/net/minecraft/server/Entity.java +@@ -1763,6 +1763,50 @@ public abstract class Entity implements ICommandListener { + + } + ++ private boolean _canGlideWithoutWings; ++ private boolean _autoWingsFly = true; ++ private float _wingsDeployAt = 1.15F; ++ ++ public void setAutoWingsDeploy(boolean deployWings) ++ { ++ _autoWingsFly = deployWings; ++ } ++ ++ public boolean isAutoWingsDeploy() ++ { ++ return _autoWingsFly; ++ } ++ ++ public float getWingsDeployAt() ++ { ++ return _wingsDeployAt; ++ } ++ ++ public void setWingsDeployAt(float wingsDeployAt) ++ { ++ _wingsDeployAt = wingsDeployAt; ++ } ++ ++ public void setGlidableWithoutWings(boolean canGlideWithoutWings) ++ { ++ _canGlideWithoutWings = canGlideWithoutWings; ++ } ++ ++ public boolean canGlideWithoutWings() ++ { ++ return _canGlideWithoutWings; ++ } ++ ++ public void setGliding(boolean gliding) ++ { ++ b(7, gliding); ++ } ++ ++ public boolean isGliding() ++ { ++ return g(7); ++ } ++ + public int getAirTicks() { + return this.datawatcher.getShort(1); + } +diff --git a/src/main/java/net/minecraft/server/EntityFireworks.java b/src/main/java/net/minecraft/server/EntityFireworks.java +index c918c5f..41e9275 100644 +--- a/src/main/java/net/minecraft/server/EntityFireworks.java ++++ b/src/main/java/net/minecraft/server/EntityFireworks.java +@@ -6,7 +6,7 @@ public class EntityFireworks extends Entity { + + private int ticksFlown; + public int expectedLifespan; +- private final DataIndex> META_ITEM = DataWatcher.getIndex(EntityFireworks.class, DataType.OPT_ITEMSTACK); ++ public static final DataIndex> META_ITEM = DataWatcher.getIndex(EntityFireworks.class, DataType.OPT_ITEMSTACK); + + // Spigot Start + @Override +diff --git a/src/main/java/net/minecraft/server/EntityHuman.java b/src/main/java/net/minecraft/server/EntityHuman.java +index 5294c66..743df69 100644 +--- a/src/main/java/net/minecraft/server/EntityHuman.java ++++ b/src/main/java/net/minecraft/server/EntityHuman.java +@@ -1226,6 +1226,13 @@ public abstract class EntityHuman extends EntityLiving { + + } + ++ public void setGliding(boolean gliding) ++ { ++ super.setGliding(gliding); ++ ++ setSize(0.6F, gliding ? 0.4F : 1.8F); ++ } ++ + public void a(boolean flag, boolean flag1, boolean flag2) { + this.setSize(0.6F, 1.8F); + IBlockData iblockdata = this.world.getType(this.bx); +@@ -1688,6 +1695,11 @@ public abstract class EntityHuman extends EntityLiving { + f -= 0.08F; + } + ++ if (this.isGliding()) ++ { ++ f = 0.4f; ++ } ++ + return f; + } + +diff --git a/src/main/java/net/minecraft/server/EntityLiving.java b/src/main/java/net/minecraft/server/EntityLiving.java +index d0af93f..d074110 100644 +--- a/src/main/java/net/minecraft/server/EntityLiving.java ++++ b/src/main/java/net/minecraft/server/EntityLiving.java +@@ -956,7 +956,7 @@ public abstract class EntityLiving extends Entity { + + if (i > 0) { + // CraftBukkit start +- if (!this.damageEntity(DamageSource.FALL, (float) i)) { ++ if (isGliding() || !this.damageEntity(DamageSource.FALL, (float) i)) { + return; + } + // CraftBukkit end +@@ -1668,6 +1668,7 @@ public abstract class EntityLiving extends Entity { + this.aZ *= 0.98F; + this.ba *= 0.98F; + this.bb *= 0.9F; ++ checkWings(); + SpigotTimings.timerEntityAIMove.startTiming(); // Spigot + this.g(this.aZ, this.ba); + SpigotTimings.timerEntityAIMove.stopTiming(); // Spigot +@@ -1682,6 +1683,37 @@ public abstract class EntityLiving extends Entity { + this.world.methodProfiler.b(); + } + ++ private void checkWings() ++ { ++ if (!isAutoWingsDeploy()) ++ return; ++ ++ boolean gliding = isGliding(); ++ ++ if ((!this.onGround || gliding && motX * motX + motZ * motZ > 0.25) && this.fallDistance >= getWingsDeployAt() && (!(this instanceof EntityPlayer) || (((EntityPlayer) this).playerConnection.networkManager.getVersion() != 47 && !((EntityPlayer) this).getBukkitEntity().isFlying()))) ++ { ++ ItemStack item = getEquipment()[2]; ++ ++ if (canGlideWithoutWings() || (item != null && item.getItem().getName().contains("elytra"))) ++ { ++ gliding = true; ++ } ++ else ++ { ++ gliding = false; ++ } ++ } ++ else ++ { ++ gliding = false; ++ } ++ ++ if (gliding != isGliding()) ++ { ++ setGliding(gliding); ++ } ++ } ++ + protected void doTick() {} + + protected void bL() { +diff --git a/src/main/java/net/minecraft/server/EntityPlayer.java b/src/main/java/net/minecraft/server/EntityPlayer.java +index 9c46797..b1348b9 100644 +--- a/src/main/java/net/minecraft/server/EntityPlayer.java ++++ b/src/main/java/net/minecraft/server/EntityPlayer.java +@@ -247,11 +247,15 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + this.playerConnection.sendPacket(new PacketPlayOutMapChunk((Chunk) arraylist.get(0), true, '\uffff')); + } else { + if (playerConnection.networkManager.getVersion() == 47) +- this.playerConnection.sendPacket(new PacketPlayOutMapChunkBulk(arraylist)); +- else +- for (Chunk chunk1 : (ArrayList) arraylist) + { +- this.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk1, true, '\uffff')); ++ this.playerConnection.sendPacket(new PacketPlayOutMapChunkBulk(arraylist)); ++ } ++ else ++ { ++ for (Chunk chunk1 : (ArrayList) arraylist) ++ { ++ this.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk1, true, '\uffff')); ++ } + } + } + +diff --git a/src/main/java/net/minecraft/server/EnumProtocol.java b/src/main/java/net/minecraft/server/EnumProtocol.java +index eb425dc..f3877e4 100644 +--- a/src/main/java/net/minecraft/server/EnumProtocol.java ++++ b/src/main/java/net/minecraft/server/EnumProtocol.java +@@ -42,7 +42,7 @@ public enum EnumProtocol + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTileEntityData.class, 53, 9); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockAction.class, 36, 10); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockChange.class, 35, 11); +- // Boss bar ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBossBar.class, -1, 12); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutServerDifficulty.class, 65, 13); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTabComplete.class, 58, 14); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutChat.class, 2, 15); +@@ -53,7 +53,7 @@ public enum EnumProtocol + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowItems.class, 48, 20); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowData.class, 49, 21); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetSlot.class, 47, 22); +- // Set cooldown ++ a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetCooldown.class, -1, 23); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCustomPayload.class, 63, 24); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNamedSoundEffect.class, 41, 25); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutKickDisconnect.class, 64, 26); +@@ -110,7 +110,7 @@ public enum EnumProtocol + + + +- a(EnumProtocolDirection.SERVERBOUND, PacketPlayInArmAnimation.class, 10, 26); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInLeftClick.class, -1, 0); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInTabComplete.class, 20, 1); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInChat.class, 1, 2); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInClientCommand.class, 22, 3); +@@ -136,7 +136,7 @@ public enum EnumProtocol + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInHeldItemSlot.class, 9, 23); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSetCreativeSlot.class, 16, 24); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUpdateSign.class, 18, 25); +- a(EnumProtocolDirection.SERVERBOUND, PacketPlayInLeftClick.class, -1, 0); ++ a(EnumProtocolDirection.SERVERBOUND, PacketPlayInArmAnimation.class, 10, 26); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSpectate.class, 24, 27); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInBlockPlace.class, 8, 28); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInRightClick.class, -1, 29); +diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java +index bec9f80..824ec1b 100644 +--- a/src/main/java/net/minecraft/server/HandshakeListener.java ++++ b/src/main/java/net/minecraft/server/HandshakeListener.java +@@ -25,7 +25,7 @@ public class HandshakeListener implements PacketHandshakingInListener { + + int version = packethandshakinginsetprotocol.b(); + //System.out.print(version); +- boolean supported = version == 47 || version == 89 || version == 86; ++ boolean supported = version == 47 || version == 94; + + if (supported) + { +diff --git a/src/main/java/net/minecraft/server/ItemArmor.java b/src/main/java/net/minecraft/server/ItemArmor.java +index cd77ba5..39043fd 100644 +--- a/src/main/java/net/minecraft/server/ItemArmor.java ++++ b/src/main/java/net/minecraft/server/ItemArmor.java +@@ -167,7 +167,7 @@ public class ItemArmor extends Item { + + public static enum EnumArmorMaterial { + +- LEATHER("leather", 5, new int[] { 1, 3, 2, 1}, 15), CHAIN("chainmail", 15, new int[] { 2, 5, 4, 1}, 12), IRON("iron", 15, new int[] { 2, 6, 5, 2}, 9), GOLD("gold", 7, new int[] { 2, 5, 3, 1}, 25), DIAMOND("diamond", 33, new int[] { 3, 8, 6, 3}, 10); ++ LEATHER("leather", 5, new int[] { 1, 3, 2, 1}, 15), CHAIN("chainmail", 15, new int[] { 2, 5, 4, 1}, 12), IRON("iron", 15, new int[] { 2, 6, 5, 2}, 9), GOLD("gold", 7, new int[] { 2, 5, 3, 1}, 25), DIAMOND("diamond", 33, new int[] { 3, 8, 6, 3}, 10), ELYTRA("eltra", 431, new int[] { 1, 1, 1, 1}, 1); + + private final String f; + private final int g; +@@ -194,7 +194,7 @@ public class ItemArmor extends Item { + } + + public Item b() { +- return this == ItemArmor.EnumArmorMaterial.LEATHER ? Items.LEATHER : (this == ItemArmor.EnumArmorMaterial.CHAIN ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.GOLD ? Items.GOLD_INGOT : (this == ItemArmor.EnumArmorMaterial.IRON ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.DIAMOND ? Items.DIAMOND : null)))); ++ return this == ItemArmor.EnumArmorMaterial.LEATHER || this == ItemArmor.EnumArmorMaterial.ELYTRA ? Items.LEATHER : (this == ItemArmor.EnumArmorMaterial.CHAIN ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.GOLD ? Items.GOLD_INGOT : (this == ItemArmor.EnumArmorMaterial.IRON ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.DIAMOND ? Items.DIAMOND : null)))); + } + } + } +diff --git a/src/main/java/net/minecraft/server/ItemBlock.java b/src/main/java/net/minecraft/server/ItemBlock.java +new file mode 100644 +index 0000000..f680859 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/ItemBlock.java +@@ -0,0 +1,102 @@ ++package net.minecraft.server; ++ ++public class ItemBlock extends Item ++{ ++ protected final Block a; ++ ++ public ItemBlock(Block paramBlock) ++ { ++ this.a = paramBlock; ++ } ++ ++ public ItemBlock b(String paramString) ++ { ++ super.c(paramString); ++ return this; ++ } ++ ++ public boolean interactWith(ItemStack paramItemStack, EntityHuman paramEntityHuman, World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3) ++ { ++ IBlockData localIBlockData1 = paramWorld.getType(paramBlockPosition); ++ Block localBlock = localIBlockData1.getBlock(); ++ if (!localBlock.a(paramWorld, paramBlockPosition)) { ++ paramBlockPosition = paramBlockPosition.shift(paramEnumDirection); ++ } ++ ++ if (paramItemStack.count == 0) { ++ return false; ++ } ++ if (!paramEntityHuman.a(paramBlockPosition, paramEnumDirection, paramItemStack)) { ++ return false; ++ } ++ ++ if (paramWorld.a(this.a, paramBlockPosition, false, paramEnumDirection, null, paramItemStack)) { ++ int i = filterData(paramItemStack.getData()); ++ IBlockData localIBlockData2 = this.a.getPlacedState(paramWorld, paramBlockPosition, paramEnumDirection, paramFloat1, paramFloat2, paramFloat3, i, paramEntityHuman); ++ if (paramWorld.setTypeAndData(paramBlockPosition, localIBlockData2, 3)) { ++ localIBlockData2 = paramWorld.getType(paramBlockPosition); ++ ++ if (localIBlockData2.getBlock() == this.a) { ++ a(paramWorld, paramEntityHuman, paramBlockPosition, paramItemStack); ++ this.a.postPlace(paramWorld, paramBlockPosition, localIBlockData2, paramEntityHuman, paramItemStack); ++ } ++ ++ for (IWorldAccess access : paramWorld.u) ++ { ++ if (access instanceof WorldManager) ++ ((WorldManager) access).a(this.a.stepSound.getPlaceSound(), paramBlockPosition.getX() + 0.5F, paramBlockPosition.getY() + 0.5F, paramBlockPosition.getZ() + 0.5F, (this.a.stepSound.getVolume1() + 1.0F) / 2.0F, this.a.stepSound.getVolume2() * 0.8F, paramEntityHuman); ++ } ++ paramItemStack.count -= 1; ++ } ++ return true; ++ } ++ return false; ++ } ++ ++ public static boolean a(World paramWorld, EntityHuman paramEntityHuman, BlockPosition paramBlockPosition, ItemStack paramItemStack) { ++ MinecraftServer localMinecraftServer = MinecraftServer.getServer(); ++ if (localMinecraftServer == null) { ++ return false; ++ } ++ if ((paramItemStack.hasTag()) && (paramItemStack.getTag().hasKeyOfType("BlockEntityTag", 10))) { ++ TileEntity localTileEntity = paramWorld.getTileEntity(paramBlockPosition); ++ ++ if (localTileEntity != null) { ++ if ((!paramWorld.isClientSide) && (localTileEntity.F()) && (!localMinecraftServer.getPlayerList().isOp(paramEntityHuman.getProfile()))) { ++ return false; ++ } ++ NBTTagCompound localNBTTagCompound1 = new NBTTagCompound(); ++ NBTTagCompound localNBTTagCompound2 = (NBTTagCompound)localNBTTagCompound1.clone(); ++ localTileEntity.b(localNBTTagCompound1); ++ ++ NBTTagCompound localNBTTagCompound3 = (NBTTagCompound)paramItemStack.getTag().get("BlockEntityTag"); ++ localNBTTagCompound1.a(localNBTTagCompound3); ++ localNBTTagCompound1.setInt("x", paramBlockPosition.getX()); ++ localNBTTagCompound1.setInt("y", paramBlockPosition.getY()); ++ localNBTTagCompound1.setInt("z", paramBlockPosition.getZ()); ++ ++ if (!localNBTTagCompound1.equals(localNBTTagCompound2)) { ++ localTileEntity.a(localNBTTagCompound1); ++ localTileEntity.update(); ++ return true; ++ } ++ } ++ } ++ return false; ++ } ++ ++ public String e_(ItemStack paramItemStack) ++ { ++ return this.a.a(); ++ } ++ ++ public String getName() ++ { ++ return this.a.a(); ++ } ++ ++ public Block d() ++ { ++ return this.a; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/MobEffectList.java b/src/main/java/net/minecraft/server/MobEffectList.java +index 863e9d8..b34cd62 100644 +--- a/src/main/java/net/minecraft/server/MobEffectList.java ++++ b/src/main/java/net/minecraft/server/MobEffectList.java +@@ -40,6 +40,7 @@ public class MobEffectList { + public static final MobEffectList HEALTH_BOOST = (new MobEffectHealthBoost(21, new MinecraftKey("health_boost"), false, 16284963)).c("potion.healthBoost").b(2, 2).a(GenericAttributes.maxHealth, "5D6F0BA2-1186-46AC-B896-C61C5CEE99CC", 4.0D, 0); + public static final MobEffectList ABSORBTION = (new MobEffectAbsorption(22, new MinecraftKey("absorption"), false, 2445989)).c("potion.absorption").b(2, 2); + public static final MobEffectList SATURATION = (new InstantMobEffect(23, new MinecraftKey("saturation"), false, 16262179)).c("potion.saturation"); ++ public static final MobEffectList LEVITATION = (new MobEffectList(25, new MinecraftKey("levitation"), false, 33333)).c("potion.levitation"); + public static final MobEffectList z = null; + public static final MobEffectList A = null; + public static final MobEffectList B = null; +diff --git a/src/main/java/net/minecraft/server/PacketListenerPlayOut.java b/src/main/java/net/minecraft/server/PacketListenerPlayOut.java +index 361eebb..371ad06 100644 +--- a/src/main/java/net/minecraft/server/PacketListenerPlayOut.java ++++ b/src/main/java/net/minecraft/server/PacketListenerPlayOut.java +@@ -147,4 +147,8 @@ public abstract interface PacketListenerPlayOut extends PacketListener + public abstract void a(PacketPlayOutUnloadChunk paramPacketPlayOutUnloadChunk); + + public abstract void a(PacketPlayOutNewAttachEntity paramPacketPlayOutNewAttachEntity); ++ ++ public abstract void a(PacketPlayOutBossBar paramPacketPlayOutBossBar); ++ ++ public abstract void a(PacketPlayOutSetCooldown paramPacketPlayOutSetCooldown); + } +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java b/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java +index 3032d20..549e035 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java ++++ b/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java +@@ -43,6 +43,6 @@ public class PacketPlayInBlockDig + + public static enum EnumPlayerDigType + { +- START_DESTROY_BLOCK, ABORT_DESTROY_BLOCK, STOP_DESTROY_BLOCK, DROP_ALL_ITEMS, DROP_ITEM, RELEASE_USE_ITEM; ++ START_DESTROY_BLOCK, ABORT_DESTROY_BLOCK, STOP_DESTROY_BLOCK, DROP_ALL_ITEMS, DROP_ITEM, RELEASE_USE_ITEM, SWAP_HELD_ITEMS; + } + } +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutBossBar.java b/src/main/java/net/minecraft/server/PacketPlayOutBossBar.java +new file mode 100644 +index 0000000..1043327 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayOutBossBar.java +@@ -0,0 +1,96 @@ ++package net.minecraft.server; ++ ++import java.util.UUID; ++import java.io.IOException; ++ ++public class PacketPlayOutBossBar ++ implements Packet ++{ ++ public UUID uuid; ++ /** ++ * 0 = Add ++ * 1 = Remove ++ * 2 = Update Health ++ * 3 = Update Title ++ * 4 = Update Style ++ * 5 = Update Flags ++ **/ ++ public int action; ++ public String title; ++ public float health; ++ /** ++ * 0 = Pinkish ++ * 1 = Cyan ++ * 2 = Red ++ * 3 = Lime ++ * 4 = Yellow ++ * 5 = Purple ++ * 6 = White ++ **/ ++ public int color; ++ public int dividers; ++ /** ++ * 0x1 = Darken sky ++ * 0x2 = Dragon Bar ++ **/ ++ public byte flags; ++ ++ public PacketPlayOutBossBar() ++ { ++ } ++ ++ public void a(PacketDataSerializer packetdataserializer) ++ { ++ } ++ ++ public void b(PacketDataSerializer packetdataserializer) ++ { ++ try { ++ packetdataserializer.a(this.uuid); ++ packetdataserializer.b(this.action); ++ ++ if (this.action == 0) ++ { ++ packetdataserializer.a(org.bukkit.craftbukkit.util.CraftChatMessage.fromString(title)[0]); ++ packetdataserializer.writeFloat(health); ++ packetdataserializer.b(color); ++ packetdataserializer.b(dividers); ++ packetdataserializer.writeByte(flags); ++ } ++ ++ if (action == 2) ++ { ++ packetdataserializer.writeFloat(health); ++ } ++ ++ if (action == 3) ++ { ++ packetdataserializer.a(org.bukkit.craftbukkit.util.CraftChatMessage.fromString(title)[0]); ++ } ++ ++ if (action == 4) ++ { ++ packetdataserializer.b(color); ++ packetdataserializer.b(dividers); ++ } ++ ++ if (action == 5) ++ { ++ packetdataserializer.writeByte(flags); ++ } ++ } catch (IOException ex) ++ { ++ ex.printStackTrace(); ++ } ++ } ++ ++ public void a(PacketListenerPlayOut packetlistenerplayout) ++ { ++ packetlistenerplayout.a(this); ++ } ++ ++ public void a(PacketListener packetlistener) ++ { ++ a((PacketListenerPlayOut)packetlistener); ++ } ++} +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java b/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java +index 54c1ec9..ef51cd4 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java +@@ -14,7 +14,7 @@ public class PacketPlayOutMapChunkBulk implements Packet + + public PacketPlayOutMapChunkBulk() {} + +- public PacketPlayOutMapChunkBulk(List list) { ++ public PacketPlayOutMapChunkBulk(List list) {Thread.dumpStack(); + int i = list.size(); + mapChunks = list; + +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java b/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java +index d16b0b7..6c8c8fa 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java +@@ -183,7 +183,9 @@ public class PacketPlayOutNamedSoundEffect + sounds.put("music.menu", "music.menu"); + sounds.put("note.bassattack", "block.note.bass"); + sounds.put("note.bd", "block.note.basedrum"); ++ sounds.put("note.baseattack", "block.note.basedrum"); + sounds.put("note.harp", "block.note.harp"); ++ sounds.put("note.pling", "block.note.harp"); + sounds.put("note.hat", "block.note.hat"); + sounds.put("note.snare", "block.note.snare"); + sounds.put("portal.portal", "block.portal.ambient"); +@@ -245,13 +247,12 @@ public class PacketPlayOutNamedSoundEffect + { + c = 0x7fffffff; + } +- private static HashMap so = new HashMap(); ++ + public PacketPlayOutNamedSoundEffect(String s, double d1, double d2, double d3, + float f1, float f2) + { + c = 0x7fffffff; + Validate.notNull(s, "name", new Object[0]); +- if (!so.containsKey(s) || so.get(s) < System.currentTimeMillis()){so.put(s, System.currentTimeMillis() + 60000); System.out.print("Sound: " + s);} + a = s; + b = (int)(d1 * 8D); + c = (int)(d2 * 8D); +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java b/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java +index 7ef913f..764dba0 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java +@@ -86,11 +86,11 @@ public class PacketPlayOutScoreboardTeam + paramPacketDataSerializer.a(this.c); + paramPacketDataSerializer.a(this.d); + paramPacketDataSerializer.writeByte(this.i); ++ paramPacketDataSerializer.a(this.e); + if (paramPacketDataSerializer.version != 47) + { + paramPacketDataSerializer.a(collision); + } +- paramPacketDataSerializer.a(this.e); + paramPacketDataSerializer.writeByte(this.f); + } + +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutSetCooldown.java b/src/main/java/net/minecraft/server/PacketPlayOutSetCooldown.java +new file mode 100644 +index 0000000..b070cd1 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PacketPlayOutSetCooldown.java +@@ -0,0 +1,44 @@ ++package net.minecraft.server; ++ ++public class PacketPlayOutSetCooldown ++ implements Packet ++{ ++ public int itemId; ++ public int cooldownTicks; ++ ++ public PacketPlayOutSetCooldown() ++ { ++ } ++ ++ public PacketPlayOutSetCooldown(int itemId, int cooldownTicks) ++ { ++ this.itemId = itemId; ++ this.cooldownTicks = cooldownTicks; ++ } ++ ++ public PacketPlayOutSetCooldown(org.bukkit.Material item, int cooldownTicks) ++ { ++ this.itemId = item.getId(); ++ this.cooldownTicks = cooldownTicks; ++ } ++ ++ public void a(PacketDataSerializer packetdataserializer) ++ { ++ } ++ ++ public void b(PacketDataSerializer packetdataserializer) ++ { ++ packetdataserializer.a(itemId); ++ packetdataserializer.a(cooldownTicks); ++ } ++ ++ public void a(PacketListenerPlayOut packetlistenerplayout) ++ { ++ packetlistenerplayout.a(this); ++ } ++ ++ public void a(PacketListener packetlistener) ++ { ++ a((PacketListenerPlayOut)packetlistener); ++ } ++} +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java b/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java +index 9a3b275..ef18545 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java +@@ -53,14 +53,7 @@ public class PacketPlayOutUpdateSign + packetdataserializer.a(b); + for(int i = 0; i < 4; i++) + { +- if (packetdataserializer.version == 47) +- { +- packetdataserializer.a(c[i]); +- } +- else +- { +- packetdataserializer.a(c[i]); +- } ++ packetdataserializer.a(c[i]); + } + + } +diff --git a/src/main/java/net/minecraft/server/PlayerConnection.java b/src/main/java/net/minecraft/server/PlayerConnection.java +index a8c5b44..16f8609 100644 +--- a/src/main/java/net/minecraft/server/PlayerConnection.java ++++ b/src/main/java/net/minecraft/server/PlayerConnection.java +@@ -386,7 +386,7 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + f3 = packetplayinflying.e(); + } + +- //this.player.l(); ++ this.player.l(); + this.player.setLocation(this.o, this.p, this.q, f2, f3); + if (!this.checkMovement) { + return; +@@ -445,7 +445,9 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + + AxisAlignedBB axisalignedbb = this.player.getBoundingBox().grow((double) f4, (double) f4, (double) f4).a(0.0D, -0.55D, 0.0D); + +- if (!this.minecraftServer.getAllowFlight() && !this.player.abilities.canFly && !worldserver.c(axisalignedbb)) { ++ ItemStack item = this.player.getEquipment()[2]; ++ ++ if (!this.player.isGliding() && (item == null || !item.getItem().getName().contains("elytra")) && !this.minecraftServer.getAllowFlight() && !this.player.abilities.canFly && !worldserver.c(axisalignedbb)) { + if (d16 >= -0.03125D) { + ++this.g; + if (this.g > 80) { +@@ -654,6 +656,9 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + return; + } + ++ case 7: ++ this.player.getBukkitEntity().updateInventory(); ++ return; + default: + throw new IllegalArgumentException("Invalid player action"); + } +@@ -1445,6 +1450,13 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + return; + } + ++ if (this.player.activeContainer == this.player.defaultContainer && packetplayinwindowclick.b() >= this.player.activeContainer.c.size()) ++ { ++ this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, packetplayinwindowclick.b(), null)); ++ player.getBukkitEntity().updateInventory(); ++ return; ++ } ++ + InventoryView inventory = this.player.activeContainer.getBukkitView(); + SlotType type = CraftInventoryView.getSlotType(inventory, packetplayinwindowclick.b()); + +@@ -2246,6 +2258,12 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + ; + } + ++ try { ++ PlayerConnection.SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.SWAP_HELD_ITEMS.ordinal()] = 7; ++ } catch (NoSuchFieldError nosuchfielderror15) { ++ ; ++ } ++ + } + } + +@@ -2253,7 +2271,8 @@ public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerList + + public void a(PacketPlayInUnknownPosition paramPacketPlayInUnknownPosition){System.out.print("Received unknown position");} + +- public void a(PacketPlayInLeftClick paramPacketPlayInLeftClick){System.out.print("Received left click");} ++ public void a(PacketPlayInLeftClick paramPacketPlayInLeftClick){//System.out.print("Received left click"); ++ } + + public void a(PacketPlayInRightClick paramPacketPlayInRightClick) + { +diff --git a/src/main/java/net/minecraft/server/PlayerList.java b/src/main/java/net/minecraft/server/PlayerList.java +index d3d19dd..81e231d 100644 +--- a/src/main/java/net/minecraft/server/PlayerList.java ++++ b/src/main/java/net/minecraft/server/PlayerList.java +@@ -1032,10 +1032,21 @@ public abstract class PlayerList { + this.sendPacketNearby((EntityHuman) null, d0, d1, d2, d3, i, packet); + } + ++ public void sendPacketNearby(double d0, double d1, double d2, double d3, int i, Packet packet, Entity entity) { ++ this.sendPacketNearby((EntityHuman) null, d0, d1, d2, d3, i, packet, entity); ++ } ++ + public void sendPacketNearby(EntityHuman entityhuman, double d0, double d1, double d2, double d3, int i, Packet packet) { ++ this.sendPacketNearby(entityhuman, d0, d1, d2, d3, i, packet, null); ++ } ++ ++ public void sendPacketNearby(EntityHuman entityhuman, double d0, double d1, double d2, double d3, int i, Packet packet, Entity dontSendTo) { + for (int j = 0; j < this.players.size(); ++j) { + EntityPlayer entityplayer = (EntityPlayer) this.players.get(j); + ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47 && dontSendTo == entityplayer) ++ continue; ++ + // CraftBukkit start - Test if player receiving packet can see the source of the packet + if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { + continue; +diff --git a/src/main/java/net/minecraft/server/PotionBrewer.java b/src/main/java/net/minecraft/server/PotionBrewer.java +new file mode 100644 +index 0000000..4dcea43 +--- /dev/null ++++ b/src/main/java/net/minecraft/server/PotionBrewer.java +@@ -0,0 +1,407 @@ ++package net.minecraft.server; ++ ++import com.google.common.collect.Lists; ++import com.google.common.collect.Maps; ++import java.util.ArrayList; ++import java.util.Collection; ++import java.util.HashMap; ++import java.util.List; ++import java.util.Map; ++ ++public class PotionBrewer { ++ public static final String a; ++ public static final String b; ++ public static final String c; ++ public static final String d; ++ public static final String e; ++ public static final String f; ++ public static final String g; ++ public static final String h; ++ public static final String i; ++ public static final String j; ++ public static final String k; ++ public static final String l; ++ public static final String m; ++ public static final String n; ++ private static final Map effectDurations; ++ private static final Map effectAmplifiers; ++ private static final Map q; ++ private static final String[] appearances; ++ ++ public static boolean a(int n, int n2) { ++ return (n & 1 << n2) != 0; ++ } ++ ++ private static int c(int n, int n2) { ++ return PotionBrewer.a(n, n2) ? 1 : 0; ++ } ++ ++ private static int d(int n, int n2) { ++ return PotionBrewer.a(n, n2) ? 0 : 1; ++ } ++ ++ public static int a(int n) { ++ return PotionBrewer.a(n, 5, 4, 3, 2, 1); ++ } ++ ++ public static int a(Collection collection) { ++ int n = 3694022; ++ if (collection == null || collection.isEmpty()) { ++ return n; ++ } ++ float f = 0.0f; ++ float f2 = 0.0f; ++ float f3 = 0.0f; ++ float f4 = 0.0f; ++ for (MobEffect mobEffect : collection) { ++ if (!mobEffect.isShowParticles()) continue; ++ int n2 = MobEffectList.byId[mobEffect.getEffectId()].k(); ++ for (int i = 0; i <= mobEffect.getAmplifier(); ++i) { ++ f += (float)(n2 >> 16 & 255) / 255.0f; ++ f2 += (float)(n2 >> 8 & 255) / 255.0f; ++ f3 += (float)(n2 >> 0 & 255) / 255.0f; ++ f4 += 1.0f; ++ } ++ } ++ if (f4 == 0.0f) { ++ return 0; ++ } ++ f = f / f4 * 255.0f; ++ f2 = f2 / f4 * 255.0f; ++ f3 = f3 / f4 * 255.0f; ++ return (int)f << 16 | (int)f2 << 8 | (int)f3; ++ } ++ ++ public static boolean b(Collection collection) { ++ for (MobEffect mobEffect : collection) { ++ if (mobEffect.isAmbient()) continue; ++ return false; ++ } ++ return true; ++ } ++ ++ public static String c(int n) { ++ int n2 = PotionBrewer.a(n); ++ return appearances[n2]; ++ } ++ ++ private static int a(boolean bl, boolean bl2, boolean bl3, int n, int n2, int n3, int n4) { ++ int n5 = 0; ++ if (bl) { ++ n5 = PotionBrewer.d(n4, n2); ++ } else if (n != -1) { ++ if (n == 0 && PotionBrewer.h(n4) == n2) { ++ n5 = 1; ++ } else if (n == 1 && PotionBrewer.h(n4) > n2) { ++ n5 = 1; ++ } else if (n == 2 && PotionBrewer.h(n4) < n2) { ++ n5 = 1; ++ } ++ } else { ++ n5 = PotionBrewer.c(n4, n2); ++ } ++ if (bl2) { ++ n5 *= n3; ++ } ++ if (bl3) { ++ n5 *= -1; ++ } ++ return n5; ++ } ++ ++ private static int h(int n) { ++ int n2 = 0; ++ while (n > 0) { ++ n &= n - 1; ++ ++n2; ++ } ++ return n2; ++ } ++ ++ private static int a(String string, int n, int n2, int n3) { ++ if (n >= string.length() || n2 < 0 || n >= n2) { ++ return 0; ++ } ++ int n4 = string.indexOf(124, n); ++ if (n4 >= 0 && n4 < n2) { ++ int n5 = PotionBrewer.a(string, n, n4 - 1, n3); ++ if (n5 > 0) { ++ return n5; ++ } ++ int n6 = PotionBrewer.a(string, n4 + 1, n2, n3); ++ if (n6 > 0) { ++ return n6; ++ } ++ return 0; ++ } ++ int n7 = string.indexOf(38, n); ++ if (n7 >= 0 && n7 < n2) { ++ int n8 = PotionBrewer.a(string, n, n7 - 1, n3); ++ if (n8 <= 0) { ++ return 0; ++ } ++ int n9 = PotionBrewer.a(string, n7 + 1, n2, n3); ++ if (n9 <= 0) { ++ return 0; ++ } ++ if (n8 > n9) { ++ return n8; ++ } ++ return n9; ++ } ++ boolean bl = false; ++ boolean bl2 = false; ++ boolean bl3 = false; ++ boolean bl4 = false; ++ boolean bl5 = false; ++ int n10 = -1; ++ int n11 = 0; ++ int n12 = 0; ++ int n13 = 0; ++ for (int i = n; i < n2; ++i) { ++ char c = string.charAt(i); ++ if (c >= '0' && c <= '9') { ++ if (bl) { ++ n12 = c - 48; ++ bl2 = true; ++ continue; ++ } ++ n11 *= 10; ++ n11 += c - 48; ++ bl3 = true; ++ continue; ++ } ++ if (c == '*') { ++ bl = true; ++ continue; ++ } ++ if (c == '!') { ++ if (bl3) { ++ n13 += PotionBrewer.a(bl4, bl2, bl5, n10, n11, n12, n3); ++ bl4 = false; ++ bl5 = false; ++ bl = false; ++ bl2 = false; ++ bl3 = false; ++ n12 = 0; ++ n11 = 0; ++ n10 = -1; ++ } ++ bl4 = true; ++ continue; ++ } ++ if (c == '-') { ++ if (bl3) { ++ n13 += PotionBrewer.a(bl4, bl2, bl5, n10, n11, n12, n3); ++ bl4 = false; ++ bl5 = false; ++ bl = false; ++ bl2 = false; ++ bl3 = false; ++ n12 = 0; ++ n11 = 0; ++ n10 = -1; ++ } ++ bl5 = true; ++ continue; ++ } ++ if (c == '=' || c == '<' || c == '>') { ++ if (bl3) { ++ n13 += PotionBrewer.a(bl4, bl2, bl5, n10, n11, n12, n3); ++ bl4 = false; ++ bl5 = false; ++ bl = false; ++ bl2 = false; ++ bl3 = false; ++ n12 = 0; ++ n11 = 0; ++ n10 = -1; ++ } ++ if (c == '=') { ++ n10 = 0; ++ continue; ++ } ++ if (c == '<') { ++ n10 = 2; ++ continue; ++ } ++ if (c != '>') continue; ++ n10 = 1; ++ continue; ++ } ++ if (c != '+' || !bl3) continue; ++ n13 += PotionBrewer.a(bl4, bl2, bl5, n10, n11, n12, n3); ++ bl4 = false; ++ bl5 = false; ++ bl = false; ++ bl2 = false; ++ bl3 = false; ++ n12 = 0; ++ n11 = 0; ++ n10 = -1; ++ } ++ if (bl3) { ++ n13 += PotionBrewer.a(bl4, bl2, bl5, n10, n11, n12, n3); ++ } ++ return n13; ++ } ++ ++ public static List getEffects(int n, boolean bl) { ++ ArrayList arrayList = null; ++ for (MobEffectList mobEffectList : MobEffectList.byId) { ++ int n2; ++ String string; ++ if (mobEffectList == null || mobEffectList.j() && !bl || (string = effectDurations.get(mobEffectList.getId())) == null || (n2 = PotionBrewer.a(string, 0, string.length(), n)) <= 0) continue; ++ int n3 = 0; ++ String string2 = effectAmplifiers.get(mobEffectList.getId()); ++ if (string2 != null && (n3 = PotionBrewer.a(string2, 0, string2.length(), n)) < 0) { ++ n3 = 0; ++ } ++ if (mobEffectList.isInstant()) { ++ n2 = 1; ++ } else { ++ n2 = 1200 * (n2 * 3 + (n2 - 1) * 2); ++ n2 >>= n3; ++ n2 = (int)Math.round((double)n2 * mobEffectList.getDurationModifier()); ++ if ((n & 16384) != 0) { ++ n2 = (int)Math.round((double)n2 * 0.75 + 0.5); ++ } ++ } ++ if (arrayList == null) { ++ arrayList = Lists.newArrayList(); ++ } ++ MobEffect mobEffect = new MobEffect(mobEffectList.getId(), n2, n3); ++ if ((n & 16384) != 0) { ++ mobEffect.setSplash(true); ++ } ++ arrayList.add(mobEffect); ++ } ++ return arrayList; ++ } ++ ++ private static int a(int n, int n2, boolean bl, boolean bl2, boolean bl3) { ++ if (bl3) { ++ if (!PotionBrewer.a(n, n2)) { ++ return 0; ++ } ++ } else { ++ n = bl ? (n &= ~ (1 << n2)) : (bl2 ? ((n & 1 << n2) == 0 ? (n |= 1 << n2) : (n &= ~ (1 << n2))) : (n |= 1 << n2)); ++ } ++ return n; ++ } ++ ++ public static int a(int n, String string) { ++ int n2 = 0; ++ int n3 = string.length(); ++ boolean bl = false; ++ boolean bl2 = false; ++ boolean bl3 = false; ++ boolean bl4 = false; ++ int n4 = 0; ++ for (int i = n2; i < n3; ++i) { ++ char c = string.charAt(i); ++ if (c >= '0' && c <= '9') { ++ n4 *= 10; ++ n4 += c - 48; ++ bl = true; ++ continue; ++ } ++ if (c == '!') { ++ if (bl) { ++ n = PotionBrewer.a(n, n4, bl3, bl2, bl4); ++ bl4 = false; ++ bl2 = false; ++ bl3 = false; ++ bl = false; ++ n4 = 0; ++ } ++ bl2 = true; ++ continue; ++ } ++ if (c == '-') { ++ if (bl) { ++ n = PotionBrewer.a(n, n4, bl3, bl2, bl4); ++ bl4 = false; ++ bl2 = false; ++ bl3 = false; ++ bl = false; ++ n4 = 0; ++ } ++ bl3 = true; ++ continue; ++ } ++ if (c == '+') { ++ if (!bl) continue; ++ n = PotionBrewer.a(n, n4, bl3, bl2, bl4); ++ bl4 = false; ++ bl2 = false; ++ bl3 = false; ++ bl = false; ++ n4 = 0; ++ continue; ++ } ++ if (c != '&') continue; ++ if (bl) { ++ n = PotionBrewer.a(n, n4, bl3, bl2, bl4); ++ bl4 = false; ++ bl2 = false; ++ bl3 = false; ++ bl = false; ++ n4 = 0; ++ } ++ bl4 = true; ++ } ++ if (bl) { ++ n = PotionBrewer.a(n, n4, bl3, bl2, bl4); ++ } ++ return n & 32767; ++ } ++ ++ public static int a(int n, int n2, int n3, int n4, int n5, int n6) { ++ return (PotionBrewer.a(n, n2) ? 16 : 0) | (PotionBrewer.a(n, n3) ? 8 : 0) | (PotionBrewer.a(n, n4) ? 4 : 0) | (PotionBrewer.a(n, n5) ? 2 : 0) | (PotionBrewer.a(n, n6) ? 1 : 0); ++ } ++ ++ static { ++ effectDurations = Maps.newHashMap(); ++ effectAmplifiers = Maps.newHashMap(); ++ a = null; ++ c = "+0-1-2-3&4-4+13"; ++ effectDurations.put(MobEffectList.REGENERATION.getId(), "0 & !1 & !2 & !3 & 0+6"); ++ b = "-0+1-2-3&4-4+13"; ++ effectDurations.put(MobEffectList.FASTER_MOVEMENT.getId(), "!0 & 1 & !2 & !3 & 1+6"); ++ h = "+0+1-2-3&4-4+13"; ++ effectDurations.put(MobEffectList.FIRE_RESISTANCE.getId(), "0 & 1 & !2 & !3 & 0+6"); ++ f = "+0-1+2-3&4-4+13"; ++ effectDurations.put(MobEffectList.HEAL.getId(), "0 & !1 & 2 & !3"); ++ d = "-0-1+2-3&4-4+13"; ++ effectDurations.put(MobEffectList.POISON.getId(), "!0 & !1 & 2 & !3 & 2+6"); ++ e = "-0+3-4+13"; ++ effectDurations.put(MobEffectList.WEAKNESS.getId(), "!0 & !1 & !2 & 3 & 3+6"); ++ effectDurations.put(MobEffectList.HARM.getId(), "!0 & !1 & 2 & 3"); ++ effectDurations.put(MobEffectList.SLOWER_MOVEMENT.getId(), "!0 & 1 & !2 & 3 & 3+6"); ++ g = "+0-1-2+3&4-4+13"; ++ effectDurations.put(MobEffectList.INCREASE_DAMAGE.getId(), "0 & !1 & !2 & 3 & 3+6"); ++ l = "-0+1+2-3+13&4-4"; ++ effectDurations.put(MobEffectList.NIGHT_VISION.getId(), "!0 & 1 & 2 & !3 & 2+6"); ++ effectDurations.put(MobEffectList.INVISIBILITY.getId(), "!0 & 1 & 2 & 3 & 2+6"); ++ m = "+0-1+2+3+13&4-4"; ++ effectDurations.put(MobEffectList.WATER_BREATHING.getId(), "0 & !1 & 2 & 3 & 2+6"); ++ n = "+0+1-2+3&4-4+13"; ++ effectDurations.put(MobEffectList.JUMP.getId(), "0 & 1 & !2 & 3 & 3+6"); ++ effectDurations.put(MobEffectList.LEVITATION.getId(), "0 & 1 & !2 & 3 & 3+6"); ++ j = "+5-6-7"; ++ effectAmplifiers.put(MobEffectList.FASTER_MOVEMENT.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.FASTER_DIG.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.INCREASE_DAMAGE.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.REGENERATION.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.HARM.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.HEAL.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.RESISTANCE.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.POISON.getId(), "5"); ++ effectAmplifiers.put(MobEffectList.JUMP.getId(), "5"); ++ i = "-5+6-7"; ++ k = "+14&13-13"; ++ q = Maps.newHashMap(); ++ appearances = new String[]{"potion.prefix.mundane", "potion.prefix.uninteresting", "potion.prefix.bland", "potion.prefix.clear", "potion.prefix.milky", "potion.prefix.diffuse", "potion.prefix.artless", "potion.prefix.thin", "potion.prefix.awkward", "potion.prefix.flat", "potion.prefix.bulky", "potion.prefix.bungling", "potion.prefix.buttered", "potion.prefix.smooth", "potion.prefix.suave", "potion.prefix.debonair", "potion.prefix.thick", "potion.prefix.elegant", "potion.prefix.fancy", "potion.prefix.charming", "potion.prefix.dashing", "potion.prefix.refined", "potion.prefix.cordial", "potion.prefix.sparkling", "potion.prefix.potent", "potion.prefix.foul", "potion.prefix.odorless", "potion.prefix.rank", "potion.prefix.harsh", "potion.prefix.acrid", "potion.prefix.gross", "potion.prefix.stinky"}; ++ } ++} +\ No newline at end of file +diff --git a/src/main/java/net/minecraft/server/World.java b/src/main/java/net/minecraft/server/World.java +index e61032c..7a00ad3 100644 +--- a/src/main/java/net/minecraft/server/World.java ++++ b/src/main/java/net/minecraft/server/World.java +@@ -82,7 +82,7 @@ public abstract class World implements IBlockAccess { + private int J; + public final Random random = new Random(); + public WorldProvider worldProvider; // CraftBukkit - remove final +- protected List u = Lists.newArrayList(); ++ public List u = Lists.newArrayList(); + protected IChunkProvider chunkProvider; + protected final IDataManager dataManager; + public WorldData worldData; // CraftBukkit - public +@@ -1349,7 +1349,13 @@ public abstract class World implements IBlockAccess { + + for (EntityHuman player : players) + { +- ((EntityPlayer) player).l(); ++ if (((EntityPlayer) player).playerConnection.networkManager.getVersion() == 47) ++ continue; ++ ++ PacketPlayInFlying flyingPacket = new PacketPlayInFlying(); ++ flyingPacket.f = player.onGround; ++ ++ ((EntityPlayer) player).playerConnection.a(flyingPacket); + } + + for (i = 0; i < this.k.size(); ++i) { +diff --git a/src/main/java/net/minecraft/server/WorldManager.java b/src/main/java/net/minecraft/server/WorldManager.java +index 55a2112..5c06ca2 100644 +--- a/src/main/java/net/minecraft/server/WorldManager.java ++++ b/src/main/java/net/minecraft/server/WorldManager.java +@@ -28,6 +28,11 @@ public class WorldManager implements IWorldAccess { + this.a.getPlayerList().sendPacketNearby(d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, this.world.dimension, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1)); + } + ++ public void a(String s, double d0, double d1, double d2, float f, float f1, Entity entity) { ++ // CraftBukkit - this.world.dimension ++ this.a.getPlayerList().sendPacketNearby(d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, this.world.dimension, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1), entity); ++ } ++ + public void a(EntityHuman entityhuman, String s, double d0, double d1, double d2, float f, float f1) { + // CraftBukkit - this.world.dimension + this.a.getPlayerList().sendPacketNearby(entityhuman, d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, this.world.dimension, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1)); +diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java +index b59d142..fd64be4 100644 +--- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java ++++ b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java +@@ -70,6 +70,8 @@ public class CraftPotionEffectType extends PotionEffectType { + return "ABSORPTION"; + case 23: + return "SATURATION"; ++ case 25: ++ return "LEVITATION"; + default: + return "UNKNOWN_EFFECT_TYPE_" + handle.id; + } +diff --git a/src/test/java/org/bukkit/support/AbstractTestingBase.java b/src/test/java/org/bukkit/support/AbstractTestingBase.java +index 3a362b7..f55ddcd 100644 +--- a/src/test/java/org/bukkit/support/AbstractTestingBase.java ++++ b/src/test/java/org/bukkit/support/AbstractTestingBase.java +@@ -17,6 +17,7 @@ import org.junit.BeforeClass; + public abstract class AbstractTestingBase { + public static final List INVALIDATED_MATERIALS = ImmutableList.builder() + .add( ++ Material.ELYTRA, + Material.BREWING_STAND, + Material.BED_BLOCK, + Material.NETHER_WARTS, +-- +1.9.5.msysgit.0 + diff --git a/Patches/CraftBukkit-Patches/0179-Some-debug-and-crash-fixes.patch b/Patches/CraftBukkit-Patches/0179-Some-debug-and-crash-fixes.patch new file mode 100644 index 000000000..4b5ea2931 --- /dev/null +++ b/Patches/CraftBukkit-Patches/0179-Some-debug-and-crash-fixes.patch @@ -0,0 +1,82 @@ +From d1cf06c308d35a765cf2d11b170a9d0f8fabb418 Mon Sep 17 00:00:00 2001 +From: libraryaddict +Date: Wed, 30 Dec 2015 22:38:30 +1300 +Subject: [PATCH] Some debug and crash fixes + + +diff --git a/src/main/java/net/minecraft/server/EntityPlayer.java b/src/main/java/net/minecraft/server/EntityPlayer.java +index b1348b9..147295e 100644 +--- a/src/main/java/net/minecraft/server/EntityPlayer.java ++++ b/src/main/java/net/minecraft/server/EntityPlayer.java +@@ -932,12 +932,14 @@ public class EntityPlayer extends EntityHuman implements ICrafting { + + protected void a(MobEffect mobeffect, boolean flag) { + super.a(mobeffect, flag); +- this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.getId(), mobeffect)); ++ if (this.playerConnection.networkManager.getVersion() > 47 || mobeffect.getEffectId() != 25) ++ this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.getId(), mobeffect)); + } + + protected void b(MobEffect mobeffect) { + super.b(mobeffect); +- this.playerConnection.sendPacket(new PacketPlayOutRemoveEntityEffect(this.getId(), mobeffect)); ++ if (this.playerConnection.networkManager.getVersion() > 47 || mobeffect.getEffectId() != 25) ++ this.playerConnection.sendPacket(new PacketPlayOutRemoveEntityEffect(this.getId(), mobeffect)); + } + + public void enderTeleportTo(double d0, double d1, double d2) { +diff --git a/src/main/java/net/minecraft/server/EntityTrackerEntry.java b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +index 39f0b73..e5c947f 100644 +--- a/src/main/java/net/minecraft/server/EntityTrackerEntry.java ++++ b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +@@ -428,7 +428,8 @@ public class EntityTrackerEntry { + while (iterator.hasNext()) { + MobEffect mobeffect = (MobEffect) iterator.next(); + +- entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.tracker.getId(), mobeffect)); ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47 || mobeffect.getEffectId() != 25) ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.tracker.getId(), mobeffect)); + } + } + } +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java b/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java +index ef51cd4..54c1ec9 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java +@@ -14,7 +14,7 @@ public class PacketPlayOutMapChunkBulk implements Packet + + public PacketPlayOutMapChunkBulk() {} + +- public PacketPlayOutMapChunkBulk(List list) {Thread.dumpStack(); ++ public PacketPlayOutMapChunkBulk(List list) { + int i = list.size(); + mapChunks = list; + +diff --git a/src/main/java/net/minecraft/server/PlayerList.java b/src/main/java/net/minecraft/server/PlayerList.java +index 81e231d..42d9e76 100644 +--- a/src/main/java/net/minecraft/server/PlayerList.java ++++ b/src/main/java/net/minecraft/server/PlayerList.java +@@ -168,7 +168,8 @@ public abstract class PlayerList { + while (iterator.hasNext()) { + MobEffect mobeffect = (MobEffect) iterator.next(); + +- playerconnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobeffect)); ++ if (playerconnection.networkManager.getVersion() > 47 || mobeffect.getEffectId() != 25) ++ playerconnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobeffect)); + } + + entityplayer.syncInventory(); +@@ -615,7 +616,9 @@ public abstract class PlayerList { + entityplayer.updateAbilities(); + for (Object o1 : entityplayer.getEffects()) { + MobEffect mobEffect = (MobEffect) o1; +- entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobEffect)); ++ ++ if (entityplayer.playerConnection.networkManager.getVersion() > 47 || mobEffect.getEffectId() != 25) ++ entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobEffect)); + } + // entityplayer1.syncInventory(); + // CraftBukkit end +-- +1.9.5.msysgit.0 + diff --git a/Patches/CraftBukkit-Patches/0180-Current-patch-stuff.patch b/Patches/CraftBukkit-Patches/0180-Current-patch-stuff.patch new file mode 100644 index 000000000..3c043be72 --- /dev/null +++ b/Patches/CraftBukkit-Patches/0180-Current-patch-stuff.patch @@ -0,0 +1,319 @@ +From 0d1bec3dad53441ead8ac0f22e2464a924fb8818 Mon Sep 17 00:00:00 2001 +From: git +Date: Thu, 25 Feb 2016 18:20:02 +1300 +Subject: [PATCH] Current patch stuff + + +diff --git a/src/main/java/net/minecraft/server/EntityEnderman.java b/src/main/java/net/minecraft/server/EntityEnderman.java +index 5c09068..45a9acb 100644 +--- a/src/main/java/net/minecraft/server/EntityEnderman.java ++++ b/src/main/java/net/minecraft/server/EntityEnderman.java +@@ -160,6 +160,8 @@ public class EntityEnderman extends EntityMonster { + } + + protected boolean k(double d0, double d1, double d2) { ++ if (isVegetated()) ++ return false; + double d3 = this.locX; + double d4 = this.locY; + double d5 = this.locZ; +diff --git a/src/main/java/net/minecraft/server/EntityLiving.java b/src/main/java/net/minecraft/server/EntityLiving.java +index d074110..e9a324a 100644 +--- a/src/main/java/net/minecraft/server/EntityLiving.java ++++ b/src/main/java/net/minecraft/server/EntityLiving.java +@@ -550,13 +550,13 @@ public abstract class EntityLiving extends Entity { + protected void B() { + if (this.effects.isEmpty()) { + this.bj(); +- this.setInvisible(false); ++ this.setInvisible(isMineplexInvisible()); + } else { + int i = PotionBrewer.a(this.effects.values()); + + this.datawatcher.watch(8, Byte.valueOf((byte) (PotionBrewer.b(this.effects.values()) ? 1 : 0)), META_AMBIENT_POTION, PotionBrewer.b(this.effects.values())); + this.datawatcher.watch(7, Integer.valueOf(i), META_POTION_COLOR, i); +- this.setInvisible(this.hasEffect(MobEffectList.INVISIBILITY.id)); ++ this.setInvisible(isMineplexInvisible() || this.hasEffect(MobEffectList.INVISIBILITY.id)); + } + + } +diff --git a/src/main/java/net/minecraft/server/EnumProtocol.java b/src/main/java/net/minecraft/server/EnumProtocol.java +index f3877e4..0343bf8 100644 +--- a/src/main/java/net/minecraft/server/EnumProtocol.java ++++ b/src/main/java/net/minecraft/server/EnumProtocol.java +@@ -219,7 +219,11 @@ public enum EnumProtocol + public Integer a(EnumProtocolDirection enumprotocoldirection, Packet packet, boolean is1_8) + { + Entry entry = (Entry) ((BiMap)j.get(enumprotocoldirection)).inverse().get(packet.getClass()); +- if ((Integer) (is1_8 ? entry.getKey() : entry.getValue()) < 0){System.out.print("Trying to send unsupported " + packet.getClass().getSimpleName());Thread.dumpStack();} ++ if ((Integer) (is1_8 ? entry.getKey() : entry.getValue()) < 0) ++ { ++ System.out.print("Trying to send unsupported " + packet.getClass().getSimpleName()); ++ Thread.dumpStack(); ++ } + return (Integer) (is1_8 ? entry.getKey() : entry.getValue()); + } + +diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java +index 824ec1b..9d27032 100644 +--- a/src/main/java/net/minecraft/server/HandshakeListener.java ++++ b/src/main/java/net/minecraft/server/HandshakeListener.java +@@ -25,7 +25,7 @@ public class HandshakeListener implements PacketHandshakingInListener { + + int version = packethandshakinginsetprotocol.b(); + //System.out.print(version); +- boolean supported = version == 47 || version == 94; ++ boolean supported = version == 47 || version == 104; + + if (supported) + { +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutEntity.java b/src/main/java/net/minecraft/server/PacketPlayOutEntity.java +index 702d33d..c3a067e 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutEntity.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutEntity.java +@@ -5,9 +5,9 @@ import java.io.IOException; + public class PacketPlayOutEntity implements Packet { + + public int a; +- public byte b; +- public byte c; +- public byte d; ++ public short b; ++ public short c; ++ public short d; + public byte e; + public byte f; + public boolean g; +@@ -87,9 +87,18 @@ public class PacketPlayOutEntity implements Packet { + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + super.b(packetdataserializer); +- packetdataserializer.writeByte(this.b); +- packetdataserializer.writeByte(this.c); +- packetdataserializer.writeByte(this.d); ++ if (packetdataserializer.version != 47) ++ { ++ packetdataserializer.writeShort(this.b); ++ packetdataserializer.writeShort(this.c); ++ packetdataserializer.writeShort(this.d); ++ } ++ else ++ { ++ packetdataserializer.writeByte(this.b); ++ packetdataserializer.writeByte(this.c); ++ packetdataserializer.writeByte(this.d); ++ } + packetdataserializer.writeBoolean(this.g); + } + } +@@ -123,9 +132,18 @@ public class PacketPlayOutEntity implements Packet { + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + super.b(packetdataserializer); +- packetdataserializer.writeByte(this.b); +- packetdataserializer.writeByte(this.c); +- packetdataserializer.writeByte(this.d); ++ if (packetdataserializer.version != 47) ++ { ++ packetdataserializer.writeShort(this.b); ++ packetdataserializer.writeShort(this.c); ++ packetdataserializer.writeShort(this.d); ++ } ++ else ++ { ++ packetdataserializer.writeByte(this.b); ++ packetdataserializer.writeByte(this.c); ++ packetdataserializer.writeByte(this.d); ++ } + packetdataserializer.writeByte(this.e); + packetdataserializer.writeByte(this.f); + packetdataserializer.writeBoolean(this.g); +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java b/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java +index 4730b34..3fa9fe4 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java +@@ -44,9 +44,15 @@ public class PacketPlayOutEntityTeleport implements Packet { + if (packetdataserializer.version != 47) + packetdataserializer.a(this.uuid); + packetdataserializer.writeByte(this.j); +- packetdataserializer.writeInt(this.b); +- packetdataserializer.writeInt(this.c); +- packetdataserializer.writeInt(this.d); ++ if (packetdataserializer.version != 47){ ++ packetdataserializer.writeDouble(this.b/32D); ++ packetdataserializer.writeDouble(this.c/32D); ++ packetdataserializer.writeDouble(this.d/32D); ++ }else { ++ packetdataserializer.writeInt(this.b); ++ packetdataserializer.writeInt(this.c); ++ packetdataserializer.writeInt(this.d); ++ } + packetdataserializer.writeByte(this.h); + packetdataserializer.writeByte(this.i); + packetdataserializer.writeInt(this.k); +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java +index 4f2b03e..0a39433 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java +@@ -42,9 +42,15 @@ public class PacketPlayOutSpawnEntityExperienceOrb + throws IOException + { + packetdataserializer.b(a); +- packetdataserializer.writeInt(b); +- packetdataserializer.writeInt(c); +- packetdataserializer.writeInt(d); ++ if (packetdataserializer.version != 47){ ++ packetdataserializer.writeDouble(this.b/32D); ++ packetdataserializer.writeDouble(this.c/32D); ++ packetdataserializer.writeDouble(this.d/32D); ++ }else { ++ packetdataserializer.writeInt(this.b); ++ packetdataserializer.writeInt(this.c); ++ packetdataserializer.writeInt(this.d); ++ } + packetdataserializer.writeShort(e); + } + +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java +index 9da448e..ea7c98b 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java +@@ -88,9 +88,15 @@ public class PacketPlayOutSpawnEntityLiving implements Packet +Date: Sun, 28 Feb 2016 00:37:30 +1300 +Subject: [PATCH] Changed maven version, fixed entity movement, fixed sound + packet + + +diff --git a/pom.xml b/pom.xml +index 91627ff..1ea9f81 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -4,7 +4,7 @@ + org.spigotmc + spigot + jar +- 1.8.8-R0.1-SNAPSHOT ++ 1.8.8-1.9-SNAPSHOT + Spigot + http://www.spigotmc.org + +diff --git a/src/main/java/net/minecraft/server/EntityTrackerEntry.java b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +index e5c947f..9cd9be6 100644 +--- a/src/main/java/net/minecraft/server/EntityTrackerEntry.java ++++ b/src/main/java/net/minecraft/server/EntityTrackerEntry.java +@@ -145,6 +145,7 @@ public class EntityTrackerEntry { + int k1 = j - this.yLoc; + int l1 = k - this.zLoc; + Object object = null; ++ Object object2 = null; + boolean flag = Math.abs(j1) >= 4 || Math.abs(k1) >= 4 || Math.abs(l1) >= 4 || this.m % 60 == 0; + boolean flag1 = Math.abs(l - this.yRot) >= 4 || Math.abs(i1 - this.xRot) >= 4; + +@@ -163,10 +164,12 @@ public class EntityTrackerEntry { + + if (this.m > 0 || this.tracker instanceof EntityArrow) { + if (j1 >= -128 && j1 < 128 && k1 >= -128 && k1 < 128 && l1 >= -128 && l1 < 128 && this.v <= 400 && !this.x && this.y == this.tracker.onGround) { ++ object2 = new PacketPlayOutEntityTeleport(this.tracker.getId(), i, j, k, (byte) l, (byte) i1, this.tracker.onGround); + if ((!flag || !flag1) && !(this.tracker instanceof EntityArrow)) { + if (flag) { + object = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(this.tracker.getId(), (byte) j1, (byte) k1, (byte) l1, this.tracker.onGround); + } else if (flag1) { ++ object2 = null; + object = new PacketPlayOutEntity.PacketPlayOutEntityLook(this.tracker.getId(), (byte) l, (byte) i1, this.tracker.onGround); + } + } else { +@@ -200,7 +203,15 @@ public class EntityTrackerEntry { + } + + if (object != null) { +- this.broadcast((Packet) object); ++ ++ Iterator iterator = this.trackedPlayers.iterator(); ++ ++ while (iterator.hasNext()) { ++ EntityPlayer entityplayer = (EntityPlayer) iterator.next(); ++ Packet packetToSend = object2 == null || entityplayer.playerConnection.networkManager.getVersion() == 47 ? (Packet) object : (Packet) object2; ++ ++ entityplayer.playerConnection.sendPacket(packetToSend); ++ } + } + + this.b(); +diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java +index 9d27032..21dbf3b 100644 +--- a/src/main/java/net/minecraft/server/HandshakeListener.java ++++ b/src/main/java/net/minecraft/server/HandshakeListener.java +@@ -25,7 +25,7 @@ public class HandshakeListener implements PacketHandshakingInListener { + + int version = packethandshakinginsetprotocol.b(); + //System.out.print(version); +- boolean supported = version == 47 || version == 104; ++ boolean supported = version == 47 || version >= 104; + + if (supported) + { +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutEntity.java b/src/main/java/net/minecraft/server/PacketPlayOutEntity.java +index c3a067e..8436897 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutEntity.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutEntity.java +@@ -5,9 +5,9 @@ import java.io.IOException; + public class PacketPlayOutEntity implements Packet { + + public int a; +- public short b; +- public short c; +- public short d; ++ public byte b; ++ public byte c; ++ public byte d; + public byte e; + public byte f; + public boolean g; +@@ -89,9 +89,9 @@ public class PacketPlayOutEntity implements Packet { + super.b(packetdataserializer); + if (packetdataserializer.version != 47) + { +- packetdataserializer.writeShort(this.b); +- packetdataserializer.writeShort(this.c); +- packetdataserializer.writeShort(this.d); ++ packetdataserializer.writeShort((short) this.b); ++ packetdataserializer.writeShort((short) this.c); ++ packetdataserializer.writeShort((short) this.d); + } + else + { +@@ -134,9 +134,9 @@ public class PacketPlayOutEntity implements Packet { + super.b(packetdataserializer); + if (packetdataserializer.version != 47) + { +- packetdataserializer.writeShort(this.b); +- packetdataserializer.writeShort(this.c); +- packetdataserializer.writeShort(this.d); ++ packetdataserializer.writeShort((short) this.b); ++ packetdataserializer.writeShort((short) this.c); ++ packetdataserializer.writeShort((short) this.d); + } + else + { +diff --git a/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java b/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java +index b72b7d7..bcfdab9 100644 +--- a/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java ++++ b/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java +@@ -279,7 +279,8 @@ public class PacketPlayOutNamedSoundEffect + toPlay = sounds.get(toPlay); + + packetdataserializer.a(toPlay); +- packetdataserializer.b(0); ++ if (packetdataserializer.version > 47) ++ packetdataserializer.b(0); + packetdataserializer.writeInt(b); + packetdataserializer.writeInt(c); + packetdataserializer.writeInt(d); +-- +1.9.5.msysgit.0 + diff --git a/Patches/CraftBukkit-Patches/0182-Update-to-1.9-fix-blocking.patch b/Patches/CraftBukkit-Patches/0182-Update-to-1.9-fix-blocking.patch new file mode 100644 index 000000000..1bd644b81 --- /dev/null +++ b/Patches/CraftBukkit-Patches/0182-Update-to-1.9-fix-blocking.patch @@ -0,0 +1,60 @@ +From 48550b9915d18d2d4a528c4028c8fa35a97a036c Mon Sep 17 00:00:00 2001 +From: git +Date: Tue, 1 Mar 2016 09:29:32 +1300 +Subject: [PATCH] Update to 1.9, fix blocking + + +diff --git a/src/main/java/net/minecraft/server/Entity.java b/src/main/java/net/minecraft/server/Entity.java +index 2f52ea2..c2ce92f 100644 +--- a/src/main/java/net/minecraft/server/Entity.java ++++ b/src/main/java/net/minecraft/server/Entity.java +@@ -1745,6 +1745,14 @@ public abstract class Entity implements ICommandListener { + } + + public void f(boolean flag) { ++ if (this instanceof EntityPlayer) ++ { ++ EntityPlayer player = (EntityPlayer) this; ++ ++ if (player.playerConnection.networkManager.getVersion() != 47 && player.bS() && player.getHeldItem().getItem().e(player.getHeldItem()) == EnumAnimation.BLOCK) ++ return; ++ } ++ + this.b(4, flag); + } + +diff --git a/src/main/java/net/minecraft/server/EntityHuman.java b/src/main/java/net/minecraft/server/EntityHuman.java +index 743df69..998ea69 100644 +--- a/src/main/java/net/minecraft/server/EntityHuman.java ++++ b/src/main/java/net/minecraft/server/EntityHuman.java +@@ -124,8 +124,13 @@ public abstract class EntityHuman extends EntityLiving { + + } + ++ public ItemStack getHeldItem() ++ { ++ return this.g; ++ } ++ + public boolean isBlocking() { +- return this.bS() && this.g.getItem().e(this.g) == EnumAnimation.BLOCK; ++ return ((EntityPlayer) this).playerConnection.networkManager.getVersion() == 47 && this.bS() && this.g.getItem().e(this.g) == EnumAnimation.BLOCK; + } + + public void t_() { +diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java +index 21dbf3b..0d8aff4 100644 +--- a/src/main/java/net/minecraft/server/HandshakeListener.java ++++ b/src/main/java/net/minecraft/server/HandshakeListener.java +@@ -25,7 +25,7 @@ public class HandshakeListener implements PacketHandshakingInListener { + + int version = packethandshakinginsetprotocol.b(); + //System.out.print(version); +- boolean supported = version == 47 || version >= 104; ++ boolean supported = version == 47 || version == 107; + + if (supported) + { +-- +1.9.5.msysgit.0 + diff --git a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/motd/MotdManager.java b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/motd/MotdManager.java index bd0c46a94..cf1263ae1 100644 --- a/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/motd/MotdManager.java +++ b/Plugins/Mineplex.Bungee.Mineplexer/src/mineplex/bungee/motd/MotdManager.java @@ -54,12 +54,12 @@ public class MotdManager implements Listener, Runnable //String motdLine = "§f§l◄ §c§lMaintenance§f§l ►"; //String motdLine = "§f§l◄ §a§lCarl the Creeper§f§l ►"; // String motdLine = " §2§l§n M O N S T E R M A Z E B E T A §f"; - String motdLine = " §f❄ §2§lMerry Christmas §f❄ §2§lElf Presents §f❄"; + String motdLine = " §f> §4§lCLANS BETA §f- §c§lOpen to Everyone §f<"; // String motdLine = " §f❄ §2§lServer Maintenance §f❄ §2§lBe Back Soon §f❄"; //String motdLine = " §d§lRank Sale §a§l40% Off"); //String motdLine = " §f§l◄§c§lMAINTENANCE§f§l►"); - updateMainMotd(" §c§m §f§m §c§m §f§m §2§l§m[ §r §c§lMineplex§r §f§lGames§r §2§l§m ]§f§m §c§m §f§m §c§m §r", motdLine); + updateMainMotd(" §f§m §8§l§m[ §r §9§lMineplex§r §f§lGames§r §8§l§m ]§f§m §r", motdLine); System.out.println("Updated Bungee MOTD"); } } diff --git a/Plugins/Mineplex.Cache/src/mineplex/cache/player/PlayerCache.java b/Plugins/Mineplex.Cache/src/mineplex/cache/player/PlayerCache.java index 232352662..804515ad2 100644 --- a/Plugins/Mineplex.Cache/src/mineplex/cache/player/PlayerCache.java +++ b/Plugins/Mineplex.Cache/src/mineplex/cache/player/PlayerCache.java @@ -39,7 +39,7 @@ public class PlayerCache catch (Exception exception) { System.out.println("Error adding player info in PlayerCache : " + exception.getMessage()); -// exception.printStackTrace(); + exception.printStackTrace(); } } @@ -47,15 +47,7 @@ public class PlayerCache { try { - System.out.println("Getting PlayerCache for " + uuid.toString()); PlayerInfo playerInfo = _repository.getElement(uuid.toString()); - System.out.println("Got playerINfo: " + playerInfo); - if (playerInfo != null) - { - System.out.println("account id: " + playerInfo.getAccountId()); - System.out.println("name: " + playerInfo.getName()); - } - return playerInfo; } catch (Exception exception) @@ -66,7 +58,18 @@ public class PlayerCache return null; } - + + /** + * Attempts to grab a player's account ID from the cache + * @param uuid Minecraft Account UUID + * @return The account id of the player, or -1 if the player is not in the cache + */ + public int getAccountId(UUID uuid) + { + PlayerInfo info = getPlayer(uuid); + return info == null ? -1 : info.getAccountId(); + } + public void clean() { _repository.clean(); diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/DefaultHashMap.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/DefaultHashMap.java new file mode 100644 index 000000000..142060041 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/DefaultHashMap.java @@ -0,0 +1,35 @@ +package mineplex.core.common; + +import java.util.HashMap; +import java.util.function.Function; + +public class DefaultHashMap +{ + private HashMap _map; + + private Function _defaultPopulator; + + public DefaultHashMap(Function defaultPopulator) + { + _map = new HashMap(); + + _defaultPopulator = defaultPopulator; + } + + public V get(K key) + { + _map.putIfAbsent(key, _defaultPopulator.apply(key)); + + return _map.get(key); + } + + public void put(K key, V value) + { + _map.put(key, value); + } + + public void remove(K key) + { + _map.remove(key); + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/GsonLocation.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/GsonLocation.java new file mode 100644 index 000000000..2e4ac3446 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/GsonLocation.java @@ -0,0 +1,80 @@ +package mineplex.core.common; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +public class GsonLocation +{ + private String _world; + private double _posX; + private double _posY; + private double _posZ; + private float _yaw; + private float _pitch; + + public GsonLocation(Location location) + { + _world = location.getWorld().getName(); + _posX = location.getX(); + _posY = location.getY(); + _posZ = location.getZ(); + _yaw = location.getYaw(); + _pitch = location.getPitch(); + } + + public GsonLocation(String world, double x, double y, double z) + { + this(Bukkit.getWorld(world), x, y, z, .0f, .0f); + } + + public GsonLocation(String world, double x, double y, double z, float yaw, float pitch) + { + this(Bukkit.getWorld(world), x, y, z, yaw, pitch); + } + + public GsonLocation(World world, double x, double y, double z, float yaw, float pitch) + { + _world = world.getName(); + _posX = x; + _posY = y; + _posZ = z; + _yaw = yaw; + _pitch = pitch; + } + + public GsonLocation(double x, double y, double z) + { + this(x, y, z, .0f, .0f); + } + + public GsonLocation(double x, double y, double z, float yaw, float pitch) + { + this("world", x, y, z, yaw, pitch); + } + + public Location bukkit() + { + return new Location(Bukkit.getWorld(_world), _posX, _posY, _posZ); + } + + public String getWorld() + { + return _world; + } + + public double getX() + { + return _posX; + } + + public double getY() + { + return _posY; + } + + public double getZ() + { + return _posZ; + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MaterialData.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MaterialData.java new file mode 100644 index 000000000..cf8210198 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MaterialData.java @@ -0,0 +1,46 @@ +package mineplex.core.common; + +import org.bukkit.Material; + +public class MaterialData +{ + private final Material _material; + private final byte _data; + + private MaterialData(Material material, byte data) + { + _material = material; + _data = data; + } + + public static MaterialData of(Material material) + { + return new MaterialData(material, (byte) 0); + } + + public static MaterialData of(Material material, byte data) + { + return new MaterialData(material, data); + } + + @Override + public boolean equals(Object o) + { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MaterialData that = (MaterialData) o; + + if (_data != that._data) return false; + return _material == that._material; + + } + + @Override + public int hashCode() + { + int result = _material.hashCode(); + result = 31 * result + (int) _data; + return result; + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MinecraftVersion.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MinecraftVersion.java new file mode 100644 index 000000000..d95ae1d36 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/MinecraftVersion.java @@ -0,0 +1,8 @@ +package mineplex.core.common; + +public enum MinecraftVersion +{ + ALL, + Version1_9, + Version1_8 +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/Pair.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/Pair.java index b39c3dce5..7ec401ed6 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/Pair.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/Pair.java @@ -8,7 +8,7 @@ public class Pair implements Serializable { private L left; private R right; - + public static Pair create(L left, R right) { return new Pair(left, right); diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/DataLocationMap.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/DataLocationMap.java new file mode 100644 index 000000000..147732edd --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/DataLocationMap.java @@ -0,0 +1,83 @@ +package mineplex.core.common.block; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; + +import org.bukkit.DyeColor; +import org.bukkit.Location; + +public class DataLocationMap +{ + private EnumMap> _goldDataMap; + private EnumMap> _ironDataMap; + private EnumMap> _spongeDataMap; + + public DataLocationMap() + { + _goldDataMap = new EnumMap<>(DyeColor.class); + _ironDataMap = new EnumMap<>(DyeColor.class); + _spongeDataMap = new EnumMap<>(DyeColor.class); + } + + public List getGoldLocations(DyeColor color) + { + List list = _goldDataMap.get(color); + return list == null ? Collections.emptyList() : list; + } + + public void addGoldLocation(DyeColor color, Location location) + { + if (_goldDataMap.containsKey(color)) + { + _goldDataMap.get(color).add(location); + } + else + { + List list = new ArrayList<>(); + list.add(location); + _goldDataMap.put(color, list); + } + } + + public List getIronLocations(DyeColor color) + { + List list = _ironDataMap.get(color); + return list == null ? Collections.emptyList() : list; + } + + public void addIronLocation(DyeColor color, Location location) + { + if (_ironDataMap.containsKey(color)) + { + _ironDataMap.get(color).add(location); + } + else + { + List list = new ArrayList<>(); + list.add(location); + _ironDataMap.put(color, list); + } + } + + public void addSpongeLocation(DyeColor color, Location location) { + if (_spongeDataMap.containsKey(color)) + { + _spongeDataMap.get(color).add(location); + } + else + { + List list = new ArrayList<>(); + list.add(location); + _spongeDataMap.put(color, list); + } + } + + public List getSpongeLocations(DyeColor color) + { + List list = _spongeDataMap.get(color); + return list == null ? Collections.emptyList() : list; + } + +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/schematic/Schematic.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/schematic/Schematic.java index b64056a47..43e8d5c8e 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/schematic/Schematic.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/block/schematic/Schematic.java @@ -1,8 +1,11 @@ package mineplex.core.common.block.schematic; +import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.block.Block; + +import mineplex.core.common.block.DataLocationMap; +import mineplex.core.common.util.UtilBlock; public class Schematic { @@ -21,8 +24,10 @@ public class Schematic _blockData = blockData; } - public void paste(Location originLocation) + public DataLocationMap paste(Location originLocation, boolean ignoreAir) { + DataLocationMap locationMap = new DataLocationMap(); + int startX = originLocation.getBlockX(); int startY = originLocation.getBlockY(); int startZ = originLocation.getBlockZ(); @@ -34,21 +39,107 @@ public class Schematic for (int z = 0; z < _length; z++) { int index = getIndex(x, y, z); - Block block = originLocation.getWorld().getBlockAt(startX + x, startY + y, startZ + z); // some blocks were giving me negative id's in the schematic (like stairs) // not sure why but the math.abs is my simple fix int materialId = Math.abs(_blocks[index]); - Material material = Material.getMaterial(materialId); - if (material == null) + if (ignoreAir && materialId == 0) // Air { - System.out.println(materialId + " data: " + _blockData[index]); continue; } - block.setTypeIdAndData(materialId, _blockData[index], false); + else if (materialId == 147) // Gold Plate + { + // Check for data wool at location below the gold plate + if (addDataWool(locationMap, true, originLocation, x, y - 1, z)) + continue; + } + else if (materialId == 148) // Iron Plate + { + // Check for data wool at location below the gold plate + if (addDataWool(locationMap, false, originLocation, x, y - 1, z)) + continue; + } + else if (materialId == Material.SPONGE.getId()) + { + if (addSpongeLocation(locationMap, originLocation, x, y + 1, z)) + continue; + } + else if (materialId == 35) + { + // Check if this is a dataloc so we can skip setting the block + int aboveIndex = getIndex(x, y + 1, z); + if (hasIndex(aboveIndex)) + { + if (Math.abs(_blocks[aboveIndex]) == Material.GOLD_PLATE.getId() || Math.abs(_blocks[aboveIndex]) == Material.IRON_PLATE.getId()) + continue; + } + int belowIndex = getIndex(x, y - 1, z); + if (hasIndex(belowIndex)) + { + if(Math.abs(_blocks[belowIndex]) == Material.SPONGE.getId()) + continue; + } + } + + + UtilBlock.setQuick(originLocation.getWorld(), startX + x, startY + y, startZ + z, materialId, _blockData[index]); } } } + + return locationMap; + } + + /** + * Checks the schematic location for x, y, z and adds the a Location to the DataLocationMap if it is a wool block + * + * @return true if a location was added to the DataLocationMap + */ + private boolean addDataWool(DataLocationMap map, boolean gold, Location origin, int x, int y, int z) + { + int index = getIndex(x, y, z); + if (hasIndex(index)) + { + int materialId = Math.abs(_blocks[index]); + if (materialId == 35) // WOOL + { + byte data = _blockData[index]; + DyeColor color = DyeColor.getByWoolData(data); + if (color != null) + { + if (gold) + { + map.addGoldLocation(color, origin.clone().add(x, y, z)); + } + else + { + map.addIronLocation(color, origin.clone().add(x, y, z)); + } + return true; + } + } + } + return false; + } + + private boolean addSpongeLocation(DataLocationMap map, Location origin, int x, int y, int z) + { + int index = getIndex(x, y, z); + if (hasIndex(index)) + { + int materialId = Math.abs(_blocks[index]); + if (materialId == 35) // WOOL + { + byte data = _blockData[index]; + DyeColor color = DyeColor.getByWoolData(data); + if (color != null) + { + map.addSpongeLocation(color, origin.clone().add(x, y - 1, z)); + return true; + } + } + } + return false; } public int getSize() @@ -61,6 +152,11 @@ public class Schematic return y * _width * _length + z * _width + x; } + public boolean hasIndex(int index) + { + return index < _blocks.length; + } + public short getBlock(int x, int y, int z) { return _blocks[getIndex(x, y, z)]; @@ -99,6 +195,6 @@ public class Schematic @Override public String toString() { - return String.format("width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d", _width, _length, _height, _blocks.length, _blockData.length); + return String.format("Schematic [width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d]", _width, _length, _height, _blocks.length, _blockData.length); } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/events/PlayerRecieveBroadcastEvent.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/events/PlayerRecieveBroadcastEvent.java new file mode 100644 index 000000000..4cf361fb6 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/events/PlayerRecieveBroadcastEvent.java @@ -0,0 +1,52 @@ +package mineplex.core.common.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PlayerRecieveBroadcastEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private String _message; + + private boolean _cancelled; + + public PlayerRecieveBroadcastEvent(Player player, String message) + { + _player = player; + _message = message; + } + + public Player getPlayer() + { + return _player; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public String getMessage() + { + return _message; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/function/Result.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/function/Result.java new file mode 100644 index 000000000..cb45540e3 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/function/Result.java @@ -0,0 +1,7 @@ +package mineplex.core.common.function; + +@FunctionalInterface +public interface Result +{ + public void Get(T result); +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/generator/VoidGenerator.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/generator/VoidGenerator.java new file mode 100644 index 000000000..085678e9c --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/generator/VoidGenerator.java @@ -0,0 +1,15 @@ +package mineplex.core.common.generator; + +import java.util.Random; + +import org.bukkit.World; +import org.bukkit.generator.ChunkGenerator; + +public class VoidGenerator extends ChunkGenerator +{ + @Override + public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) + { + return createChunkData(world); + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/skin/SkinData.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/skin/SkinData.java index ebc0fdb1b..7aa895666 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/skin/SkinData.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/skin/SkinData.java @@ -19,7 +19,6 @@ import net.minecraft.server.v1_8_R3.NBTTagString; public class SkinData { - private static long _nameCount = -99999999999999L; public final static SkinData MOOSHROOM = new SkinData("eyJ0aW1lc3RhbXAiOjE0NDk4NzI0OTU0MTcsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzIxOWJlYTU0Y2FkN2Q1OGFiNWRhNDA2YjBhOTJhYjNhODI0MjI1MjY2Nzc3ZTUzNGI3ZGI2YzM3MmRkZmY3ZiJ9fX0=","UoSif81+UyvkcaanU8KAMYBpw9mefAmWehE2liDUFvk+y0X/9NovsxTYVpIDCltTSpLW3sNgamvbj4Ybs+s6DbudPiEkvh0ER7Bv2v29UJw7RzIdr6/1g548X12zcnh5iPGz/P75uNRnSfTFQx0ed8P/GNkPIjWpDuJFxEj6KcPzrCAGMx+BVw1VwryBIYf9cCDHky8z0bxR89rjiIvPTBFI6MRhqI3vgpEBTySHDS+Ki0Hwl5oa3PwS6+jgYx/4RSfFsb+BawcvDk2Xpkt5UimvqZ5BceYLIfCt4KbShYipgLXLfYUZrntjPemd3SxthjxUuA07i44UxRdiC8uqy1twLT/HUS28gpk68lA/id9tKFwu1CUzshgcmvQPt3ghtNViNziR/2t7D/+5D31Vzmhf6n7Pnpdirt/5frMi2BKMMs7pLa0EF8CrrDU7QCwPav+EZVGFvVZbxSkCDq+n3IQ3PUWSCzy6KPxpdOlUjD0pAfLoiNj0P8u4+puQtID76r/St8ExchYl2dodUImu1ZETWeFUClF3ZGat62evx8uRQEI2W4dsVwj40VUfjaAuvyDzuouaKTrCzJXLQZZjR1B8URvuK61fGX0nhW607mEi6DE+nxP2ZoBrROEX4e37Ap6+TQn9Q8tKDPdcxtwSOpPO4Qkncjn/mGtP9lZU/DQ="); @@ -33,6 +32,9 @@ public class SkinData public final static SkinData LOVESTRUCK = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTUxMTAyNDMyNjUsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzczMTY5YWQwZTUyYjM1N2NiZGYxZDU0NGVkNGNmOWJmOTI4YmI0ZWNlMDhlY2YyY2M0YmYyYTlmMjJhODI4MmQifX19", "LL4RiSKQoTZamRQ4QG6izpvhgFu5gAqW4eZxcWAihk7GkhyxifpJpBTOzKrj5hH9fCUfYkkijVWUYTEcVSVRWhocp2HXW59TbKfxOeMvHU5vTMwgpwm6PnUfwuTsRPSLC7WMnEreI3cjOxPVmXbTniOSd+o8j4oOIgwFS+VLPiYLh5Jl16i5I/9ekafl3/x41NISKWl62geqO2jPWehlk+r3soiRJsxaKw20T61GSNLu19iA96Rz2T2tUHB4opm8hbLgoiNL2g1affTjq3cZPLHH4JWF3vPhqLB5uw6xb55vFLM/PP0YiEMIi7YZOfRGeaPp7uXbXgHeew+7PG9UDVMfqbwANQY4ndECijZoei54+xX3MDXkMhQsc5S+FLnGH6e4d008v81eEOyzJUPkKbGxLCBgTUb1s4IHwomCr30twPlo1IuFBOY1qeVvZUfAfPJsREuj5q/oCAoYFgupmb3ClWECnwwaH/T4wdHjfSBHoZQdLzcgDOAl0b5EXxWmYBECqk/WA4TrYIDVGdwkqjI0RkPLUoxTj6135KO+F7P7PwhU9WBGeW8hHq918DBL0fjQVHjrzvolTqwmw6nySSePnPOxFX/iwtHWzpBa9V6kUNNN+V7OGTgRr0H/yUxB+oq1F8UBqyqT4YpqxXCSD36derF/Xt5IdpTbEbGBpm0="); public final static SkinData SECRET_PACKAGE = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTUxMTAzNzE3OTIsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2QyNWI5YTRjOWRhOThkZTliZmIwZDNjOWI1M2MzMjJhMjgxN2IyMTMxOTQzY2E1YWM2NTBjZThmMzEzZjdhIn19fQ==", "Wb5T0Zhp1RVt78V/i8dYrwZCNT0xZIRe3LvL0bngH498f8Jrl43KHgTi4f299zE9giVynkTogGhJ8inq/xqFCRctl7Nn9L3LVu78uQwt+fs+o+kw/Qc+lggFSjEIc+fc13AZndpec0Df46Kh/OGD7NXbtbLb6TE/0dU2RwQlvZrZ/QHYJb8OJ6aUcnHvAZim8NUtG/nlZtSClepHVSuKdNnfzoF9rFVFA/x4jTr6mZYPZ33YgQd2oTAPk+qE3iN+0InjZQNs2YLoKFmFrgzn+tGvNApC0siF0HEZGQCFIwJOtnBsasGoxujIrln/ZdOil+5ac4VWInXr8lKgY0Q3Ocy8/0cJl+E/XqB+ztG29zhB8B1zdHBfJr+MgeSIqBCPx4SCtY6r7gnMlQYG+uVx5NP3S5aJW/cEfDyXmpCykIcBPzeErnKC0SiAqXkCVNjWJpX6qRWvWMXqS69w6ht6qHvEY2GxlZUb5AP+JgFlsl3hJDms6EPvM4zNL0Ko4oWIBzwYRQXiemrP9TGgyo0aL1RcQ0JgBFO2hSo37PK0YL3tUPgteJXzm21wu0TiZLkLCWSgMUfYfvVnhTa+xzod0xvfujpN6Y1DUTdcf8WS8TRYw2JigSkWrRW0fXPBCtTtQN5jiwM5/HrTpNLzg03J6SpfZ+rr8Rhq0S/8beQOMas="); + public final static SkinData CHISS = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTk1NDI5NjgyNDEsInByb2ZpbGVJZCI6IjFkMmJmZTYxN2ViZDQ0NWRiYTdkODM1NGEwZmZkMWVhIiwicHJvZmlsZU5hbWUiOiJDaGlzcyIsInNpZ25hdHVyZVJlcXVpcmVkIjp0cnVlLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTg3MmNkMzRjY2IzMTIxYjRjNmEzOGFjM2JmOGVkM2UwMzk3YmQ2YTg4NDI4YjdhZmM2ZTUyNTI4NTVhMzQzIiwibWV0YWRhdGEiOnsibW9kZWwiOiJzbGltIn19fX0=", "hNTLRA2acZYx2dM90lnJN8FMK/ceD3+AxKNdD5FrXzxGtYL4C1Jr/vbTE0UosmwFP3wScNEW/fuDOjeZRjZHMJdvgDZMlMK/5KDhOY6sj/RS9RckztsgummSyjH/hdDn7TWWfhZLMbiia/K0VReI9eq2yD6zGQpvMlz5hB/5SX5YHWXvCah3TL4UzYSlSVDlwY/Q3sVuIZUr8m/LIXJwniJKLGo6tUgtiJd9eseOsbBpVjzCUtLD8A9WBe2/eODgmLfqEvXESIoDRG8vL2nPSXWma/YolYHIl32/i+ZxVD7dRRaXQFYSiLI24EtzX1pPhMjyaTLazP9abH43J6J31w02pKM7N/xTa62020L/YfRRKGT5lygEDb1NMoSpAjszPxah+Ra2/L+yUWEI8cMES6I4mIJ00tclPjWK01xhIn3tqg+y2gqsGHwPhu/7vmF5NirNfKFw0qciKNBfbCAF7ae+mkUKjmAPuvBUBqQb7BOcpNVWsCo/XvzmiZZYsf5P4Uwz8LqUK4uH6V/5dg7lY2Xg3+IUylsrDqLGFDI8iy/NdjIQMbuRadh4IDO6DcmxBri2Ax4JNBPBTnRezge8uq37MZcft/IXQgFWKB9RtidVEACaTOkRj27k+Ojnkki+j44k0wZB47hiXFUHMCHl3a0SVdQe15ZbVsQj/HAvAS0="); + public final static SkinData DEFEK7 = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTk1NDI3ODkwNTksInByb2ZpbGVJZCI6Ijg5ZDQ2M2Y3MjNlYzQ3MGE4MjQ0NDU3ZjBjOGQ4NjFjIiwicHJvZmlsZU5hbWUiOiJkZWZlazciLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2JmYWNjOWM4ZjhlY2E1OWU0NTE4MTUxZmE4OGFiMDZjOTFmNjM3OTE2NzJmMTRlNGYzODY3YTI2OTVlN2NmYmYifSwiQ0FQRSI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzIyYjljNWVhNzYzYzg2ZmM1Y2FlYTMzZDgyYjBmYTY1YTdjMjI4ZmQzMjFiYTU0NzY2ZWE5NWEzZDBiOTc5MyJ9fX0=", "jBoRvkhQXz+nap8yJJIZ+4HClMItWODumeSOYjXytP3WWKHK0UMq0xC/keXsnmvo89lMRdRbknPt2ZX5Flgyjgr4Rt0KtDvpL/hG4BUsTWryUZZMKxdd6DkZXYRtTogLUfHeDYIz+cZQ0aXGMtvX/ZYTXJfMi6FYbIHY/qEEDnWhDX5y+SPpaJaZByPsvzi+qbfcFGnJ6nqi9ccyZYnYpnI2IVBM/yO/VRXWHxfqvJ0VVvv5KsGmVbko2Jxo0SDCxUL2UTH2+eol53FxhkkC+m2geC14k1zsZQLHDF3BgAG9+kFJ4UEoYRKF2Gy1FxeDCJtjYNdrYR8fdaUKRMcpBgEs+ZGe2U9EVVS/ZcBCjB7S+1Ne2bPzPFzTQPuBoMgggo1xbxBmQ5NyhYo4gwgj/xjSLIhb+5h7ioN1URfSRcfYdVv6RRO9l/u9l09jEom8y/jGRviefpEr+/e9iAl5Dd/6nzQgosBQja3NSfqYZmyuet2eI9zu61CObDTpR6yaCbNgBe/lWofRfULdpJpgjb4UNTBom3q82FcCiOe02OekGPw4+YlilhICBhajF5JzN8FKAdqI1osDcX3KuJgikYIW3voNaOP5YN3GXgilJNdou20KFC8ICq68HglgX7/0rLrWKIEoswnINIM6HcJbQuXncVPwQhV6K34Hlt/Na60="); + private Property _skinProperty; public SkinData(String value, String signature) diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/C.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/C.java index bab76df51..cbaa6ea16 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/C.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/C.java @@ -75,6 +75,8 @@ public class C public static String chatAdminHead = "" + ChatColor.DARK_PURPLE; public static String chatAdminBody = "" + ChatColor.LIGHT_PURPLE; + public static String cClansNether = "" + ChatColor.RED; + public static String listTitle = "" + ChatColor.WHITE; public static String listValue = "" + ChatColor.YELLOW; public static String listValueOn = "" + ChatColor.GREEN; diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/EnclosedObject.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/EnclosedObject.java new file mode 100644 index 000000000..50f548a46 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/EnclosedObject.java @@ -0,0 +1,31 @@ +package mineplex.core.common.util; + +public class EnclosedObject +{ + private T _value; + + public EnclosedObject() + { + this((T) null); + } + + public EnclosedObject(T t) + { + _value = t; + } + + public T Get() + { + return _value; + } + + public T Set(T value) + { + return _value = value; + } + + public String toString() + { + return _value.toString(); + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/F.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/F.java index 998b57d7c..668220aa2 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/F.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/F.java @@ -48,7 +48,7 @@ public class F { return C.mElem + elem.toString() + ChatColor.RESET + C.mBody; } - + public static String name(String elem) { return C.mElem + elem + C.mBody; @@ -215,4 +215,9 @@ public class F ? "an" : "a"; } + public static String clansNether(String word) + { + return C.cClansNether + word + C.mBody; + } + } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/FileUtil.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/FileUtil.java index 61a9f3ad5..871e2d55f 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/FileUtil.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/FileUtil.java @@ -7,7 +7,7 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -public class FileUtil +public class FileUtil { public static void DeleteFolder(File folder) { diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/MapBuilder.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/MapBuilder.java new file mode 100644 index 000000000..5e54c7e0c --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/MapBuilder.java @@ -0,0 +1,27 @@ +package mineplex.core.common.util; + +import java.util.HashMap; +import java.util.Map; + +public class MapBuilder +{ + private Map _map; + + public MapBuilder() + { + _map = new HashMap<>(); + } + + public MapBuilder Put(K key, V value) + { + _map.put(key, value); + + return this; + } + + public Map GetMap() + { + return _map; + } + +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautArrayList.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautArrayList.java index 29235ec86..3fa3f7507 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautArrayList.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautArrayList.java @@ -5,11 +5,22 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import java.util.function.Consumer; +import java.util.stream.Stream; -public class NautArrayList +public class NautArrayList implements Iterable { private ArrayList _wrappedArrayList = new ArrayList(); - + + public NautArrayList() + { + } + + public NautArrayList(Elem[] elements) + { + UtilCollections.addAll(elements, _wrappedArrayList); + } + public boolean add(Elem elem) { return _wrappedArrayList.add(elem); @@ -129,4 +140,19 @@ public class NautArrayList { return _wrappedArrayList.toArray(); } + + public void forEach(Consumer consumer) + { + _wrappedArrayList.forEach(consumer); + } + + public Stream stream() + { + return _wrappedArrayList.stream(); + } + + public List getWrapped() + { + return _wrappedArrayList; + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautHashMap.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautHashMap.java index e6d74c9d5..2f43abed9 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautHashMap.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NautHashMap.java @@ -3,12 +3,26 @@ package mineplex.core.common.util; import java.util.Collection; import java.util.HashMap; import java.util.Map.Entry; + +import org.apache.commons.lang3.Validate; + import java.util.Set; public class NautHashMap { private HashMap _wrappedHashMap = new HashMap(); - + + public NautHashMap() + { + } + + public NautHashMap(KeyType[] keys, ValueType[] values) + { + Validate.isTrue(keys.length == values.length, "Keys array and values array must be the same size when making a Map"); + + UtilCollections.loop(0, keys.length, i -> _wrappedHashMap.put(keys[i.intValue()], values[i.intValue()])); + } + public boolean containsKey(KeyType key) { return _wrappedHashMap.containsKey(key); diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NonFinalInteger.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NonFinalInteger.java deleted file mode 100644 index 6638cbed9..000000000 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NonFinalInteger.java +++ /dev/null @@ -1,33 +0,0 @@ -package mineplex.core.common.util; - -public class NonFinalInteger -{ - private int _value; - - public NonFinalInteger() - { - this(0); - } - - public NonFinalInteger(int value) - { - _value = value; - } - - public NonFinalInteger add(int value) - { - _value += value; - return this; - } - - public NonFinalInteger subtract(int value) - { - _value -= value; - return this; - } - - public int get() - { - return _value; - } -} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumberFloater.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumberFloater.java new file mode 100644 index 000000000..7a07934f5 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumberFloater.java @@ -0,0 +1,28 @@ +package mineplex.core.common.util; + +public class NumberFloater +{ + private double _min; + private double _max; + private double _modifyPerCall; + + private double _cur; + private boolean _up; + + public NumberFloater(double min, double max, double modify) + { + _min = min; + _max = max; + _modifyPerCall = modify; + } + + public double pulse() + { + if (_up && (_cur = UtilMath.clamp(_cur += _modifyPerCall, _min, _max)) >= _max) + _up = false; + else if ((_cur = UtilMath.clamp(_cur -= _modifyPerCall, _min, _max)) <= _min) + _up = true; + + return _cur; + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumericalPulser.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumericalPulser.java deleted file mode 100644 index e0de3e7d2..000000000 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/NumericalPulser.java +++ /dev/null @@ -1,42 +0,0 @@ -package mineplex.core.common.util; - -public class NumericalPulser -{ - private double _min; - private double _max; - private double _modifyPerCall; - - private double _cur; - private boolean _up; - - public NumericalPulser(double min, double max, double modify) - { - _min = min; - _max = max; - _modifyPerCall = modify; - } - - public double pulse() - { - if (_up) - { - _cur = UtilMath.clamp(_cur += _modifyPerCall, _min, _max); - - if (_cur >= _max) - { - _up = false; - } - } - else - { - _cur = UtilMath.clamp(_cur -= _modifyPerCall, _min, _max); - - if (_cur <= _min) - { - _up = true; - } - } - - return _cur; - } -} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/ProfileLoader.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/ProfileLoader.java index bcc4ffb42..dffb82f70 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/ProfileLoader.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/ProfileLoader.java @@ -88,7 +88,7 @@ public class ProfileLoader } catch (Exception e) { - ; // Failed to load skin + e.printStackTrace(); } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/RGBData.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/RGBData.java index 912516d17..adbe9749c 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/RGBData.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/RGBData.java @@ -1,5 +1,7 @@ package mineplex.core.common.util; +import org.bukkit.util.Vector; + public class RGBData { private double _red; @@ -50,4 +52,19 @@ public class RGBData + "green=" + (int) (_green * 255) + ", " + "blue=" + (int) (_blue * 255) + "]"; } + + public Vector ToVector() + { + return new Vector(Math.max(0.001, _red), _green, _blue); + } + + public RGBData Darken() + { + return new RGBData(getFullRed() - 25, getFullGreen() - 25, getFullBlue() - 25); + } + + public RGBData Lighten() + { + return new RGBData(getFullRed() + 25, getFullGreen() + 25, getFullBlue() + 25); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/SpigotUtil.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/SpigotUtil.java new file mode 100644 index 000000000..e04688375 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/SpigotUtil.java @@ -0,0 +1,31 @@ +package mineplex.core.common.util; + +import com.google.common.base.Optional; +import net.minecraft.server.v1_8_R3.EntityTameableAnimal; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftTameableAnimal; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Tameable; + +public class SpigotUtil +{ + // Explanation: + // - Tameable animals (wolves, ocelots) keep track of their most + // recent owner. + // - When an animal is assigned a new owner, its data watcher is + // updated with the new owner's UUID + // - During this process, the old owner's UUID is checked against + // the new one + // - If the animal didn't have a previous owner, the old owner's + // UUID is the empty string. + // - UUID.fromString() is called on the empty string, and throws + // an exception. + // + // We can mitigate this issue by manually setting a previous owner + // UUID before we call Tameable#setOwner(AnimalTamer) + // + // (note: this does not apply to horses) + public static void setOldOwner_RemoveMeWhenSpigotFixesThis(Tameable tameable, AnimalTamer tamer) + { + ((CraftTameableAnimal)tameable).getHandle().getDataWatcher().watch(17, tamer.getUniqueId().toString(), EntityTameableAnimal.META_OWNER, Optional.absent()); + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilAlg.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilAlg.java index 744cc2462..1945a0e1b 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilAlg.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilAlg.java @@ -2,10 +2,14 @@ package mineplex.core.common.util; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; +import java.util.LinkedList; import java.util.List; +import java.util.Random; import java.util.Set; import java.util.TreeSet; +import java.util.stream.Stream; import org.bukkit.Location; import org.bukkit.block.Block; @@ -167,6 +171,34 @@ public class UtilAlg return element; } + public static List getBox(Block cornerA, Block cornerB) + { + if (cornerA == null || cornerB == null || (cornerA.getWorld() != cornerB.getWorld())) + return Collections.emptyList(); + + ArrayList list = new ArrayList<>(); + + int minX = Math.min(cornerA.getX(), cornerB.getX()); + int minY = Math.min(cornerA.getY(), cornerB.getY()); + int minZ = Math.min(cornerA.getZ(), cornerB.getZ()); + int maxX = Math.max(cornerA.getX(), cornerB.getX()); + int maxY = Math.max(cornerA.getY(), cornerB.getY()); + int maxZ = Math.max(cornerA.getZ(), cornerB.getZ()); + + for (int x = minX; x <= maxX; x++) + { + for (int y = minY; y <= maxY; y++) + { + for (int z = minZ; z <= maxZ; z++) + { + list.add(cornerA.getWorld().getBlockAt(x, y, z)); + } + } + } + + return list; + } + public static boolean inBoundingBox(Location loc, Location cornerA, Location cornerB) { if (loc.getX() <= Math.min(cornerA.getX(), cornerB.getX())) return false; @@ -184,6 +216,24 @@ public class UtilAlg return true; } + + public static boolean inBoundingBox(Location loc, Vector cornerA, Vector cornerB) + { + if (loc.getX() <= Math.min(cornerA.getX(), cornerB.getX())) return false; + if (loc.getX() >= Math.max(cornerA.getX(), cornerB.getX())) return false; + + if (cornerA.getY() != cornerB.getY()) + { + if (loc.getY() <= Math.min(cornerA.getY(), cornerB.getY())) return false; + if (loc.getY() >= Math.max(cornerA.getY(), cornerB.getY())) return false; + } + + if (loc.getZ() <= Math.min(cornerA.getZ(), cornerB.getZ())) return false; + if (loc.getZ() >= Math.max(cornerA.getZ(), cornerB.getZ())) return false; + + return true; + } + public static Vector cross(Vector a, Vector b) { double x = a.getY()*b.getZ() - a.getZ()*b.getY(); @@ -218,7 +268,7 @@ public class UtilAlg return cross(vec, getRight(vec)); } - public static Location getAverageLocation(ArrayList locs) + public static Location getAverageLocation(List locs) { if (locs.isEmpty()) return null; @@ -236,8 +286,27 @@ public class UtilAlg return vec.toLocation(locs.get(0).getWorld()); } + + public static Location getAverageBlockLocation(List locs) + { + if (locs.isEmpty()) + return null; + + Vector vec = new Vector(0,0,0); + double amount = 0; + + for (Block loc : locs) + { + vec.add(loc.getLocation().toVector()); + amount++; + } + + vec.multiply(1d/amount); + + return vec.toLocation(locs.get(0).getWorld()); + } - public static Vector getAverageBump(Location source, ArrayList locs) + public static Vector getAverageBump(Location source, List locs) { if (locs.isEmpty()) return null; @@ -550,4 +619,25 @@ public class UtilAlg return new AxisAlignedBB(a.getX(), a.getY(), a.getZ(), b.getX(), b.getY(), b.getZ()); } + public static Location moveForward(Location location, double strength, float yaw, boolean reverse) + { + double x = location.getX(); + double z = location.getZ(); + + double rad = Math.toRadians(yaw); + + x = reverse ? (x + strength * Math.sin(rad)) : (x - strength * Math.sin(rad)); + z = reverse ? (z - strength * Math.cos(rad)) : (z + strength * Math.cos(rad)); + + return new Location(location.getWorld(), x, location.getY(), z, location.getYaw(), location.getPitch()); + } + + public static Location getRandomLocation(Location center, int radius) + { + Random r = new Random(); + int x = r.nextInt(radius * 2) - radius; + int y = r.nextInt(radius * 2) - radius; + int z = r.nextInt(radius * 2) - radius; + return center.clone().add(x, y, z); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilBlock.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilBlock.java index 8298bd7f1..f84c2b83a 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilBlock.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilBlock.java @@ -3,6 +3,7 @@ package mineplex.core.common.util; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Queue; import org.bukkit.Location; import org.bukkit.Material; @@ -30,6 +31,7 @@ import org.bukkit.material.Bed; import net.minecraft.server.v1_8_R3.BlockPosition; import net.minecraft.server.v1_8_R3.Blocks; import net.minecraft.server.v1_8_R3.EnumDirection; +import net.minecraft.server.v1_8_R3.IBlockData; import net.minecraft.server.v1_8_R3.Item; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.MinecraftKey; @@ -467,7 +469,12 @@ public class UtilBlock public static Block getHighest(World world, Location location) { - return getHighest(world, location.getBlockX(), location.getBlockZ(), null); + return getHighest(world, location.getBlockX(), location.getBlockZ()); + } + + public static Block getHighest(World world, Block block) + { + return getHighest(world, block.getLocation()); } public static Block getHighest(World world, int x, int z, HashSet ignore) @@ -1423,4 +1430,78 @@ public class UtilBlock return itemStacks; } + + public static Location nearestFloor(Location location) + { + if (!UtilItem.isBoundless(location.getBlock().getType())) + { + return location.clone(); + } + + Location gr = location.clone(); + + while (UtilItem.isBoundless(gr.getBlock().getType()) && gr.getY() > 0) + { + gr.subtract(0, 0.5, 0); + } + + return gr.getBlock().getLocation(); + } + + public static boolean setSilent(Block block, Material type) + { + return setSilent(block, type, (byte) 0); + } + + /** + * Sets block data without causing a block update. + */ + public static boolean setSilent(Block block, Material type, byte data) + { + BlockState state = block.getState(); + + state.setType(type); + state.setRawData(data); + + return state.update(false, false); + } + + public static void setQuick(World world, int x, int y, int z, int type, byte data) + { + int cx = x >> 4; + int cz = z >> 4; + if (!world.isChunkLoaded(cx, cz)) + { + world.loadChunk(cx, cz, true); + } + + net.minecraft.server.v1_8_R3.Chunk chunk = ((CraftWorld) world).getHandle().getChunkAt(x >> 4, z >> 4); + BlockPosition pos = new BlockPosition(x, y, z); + IBlockData ibd = net.minecraft.server.v1_8_R3.Block.getById(type).fromLegacyData(data); + chunk.a(pos, ibd); + } + + /** + * @return true if all of the blocks within the specified radius of the specified origin block are boundless ({@link UtilItem#isBoundless}.) + */ + public static boolean boundless(Location origin, double radius) + { + for (Block block : getInRadius(origin, radius).keySet()) + { + if (!UtilItem.isBoundless(block.getType())) + { + return false; + } + } + + return true; + } + + /** + * @return true if there are any non-boundless ({@link UtilItem#isBoundless}) blocks within the specified radius of the specified origin block. + */ + public static boolean boundless(Block origin, double radius) + { + return boundless(origin.getLocation(), radius); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilCollections.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilCollections.java new file mode 100644 index 000000000..d2eef098c --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilCollections.java @@ -0,0 +1,278 @@ +package mineplex.core.common.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; + +import com.google.common.collect.Lists; + +public class UtilCollections +{ + public static Random Random = new Random(); + + @SafeVarargs + public static NautArrayList newNautList(E... elements) + { + return new NautArrayList(elements); + } + + public static NautArrayList newNautList() + { + return new NautArrayList(); + } + + public static NautHashMap newNautMap(K[] keys, V[] values) + { + return new NautHashMap(keys, values); + } + + public static NautHashMap newNautMap() + { + return new NautHashMap(); + } + + public static T getLast(List list) + { + return list.isEmpty() ? null : list.get(list.size() - 1); + } + + public static T getFirst(List list) + { + return list.isEmpty() ? null : list.get(0); + } + + public static T getLast(NautArrayList list) + { + return list.isEmpty() ? null : list.get(list.size() - 1); + } + + public static T getFirst(NautArrayList list) + { + return list.isEmpty() ? null : list.get(0); + } + + public static void forEach(E[] elements, Function filter, Consumer consumer) + { + for (int i = 0; i < elements.length; i++) + { + consumer.accept(filter.apply(elements[i])); + } + } + + public static void forEach(E[] elements, Consumer consumer) + { + for (int i = 0; i < elements.length; i++) + { + consumer.accept(elements[i]); + } + } + + public static void forEach(E[] elements, BiConsumer consumer) + { + for (int i = 0; i < elements.length; i++) + { + consumer.accept(Integer.valueOf(i), elements[i]); + } + } + + public static void addAll(E[] elements, Collection collection) + { + forEach(elements, collection::add); + } + + public static void loop(int min, int max, Consumer consumer) + { + for (int i = min; i < max; i++) + { + consumer.accept(Integer.valueOf(i)); + } + } + + public static byte[] ensureSize(byte[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static boolean[] ensureSize(boolean[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static int[] ensureSize(int[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static long[] ensureSize(long[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static short[] ensureSize(short[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static char[] ensureSize(char[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static float[] ensureSize(float[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static double[] ensureSize(double[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static T[] ensureSize(T[] array, int size) + { + if (array.length <= size) + { + return array; + } + + return Arrays.copyOf(array, size); + } + + public static byte random(byte[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static short random(short[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static char random(char[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static boolean random(boolean[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static int random(int[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static long random(long[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static double random(double[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static float random(float[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static T random(T[] array) + { + return array[Random.nextInt(array.length)]; + } + + public static List toList(T[] array) + { + return Lists.newArrayList(array); + } + + public static boolean equal(T1[] array1, T2[] array2) + { + return Arrays.equals(array1, array2); + } + + public static void ForEach(List list, Consumer consumer) + { + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) + { + consumer.accept(iterator.next()); + } + } + + @SafeVarargs + public static List newList(X... elements) + { + return toList(elements); + } + + public static String combine(X[] data, String delimiter) + { + StringBuilder total = new StringBuilder(); + + int loops = 0; + + for (X x : data) + { + if (delimiter != null && loops != 0) + { + total.append(delimiter); + } + + total.append(x.toString()); + + loops++; + } + + return total.toString(); + } + +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilColor.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilColor.java index 32244ece9..6be674535 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilColor.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilColor.java @@ -10,6 +10,8 @@ public class UtilColor public static final RGBData RgbRed = hexToRgb(0xee0100); public static final RGBData RgbGold = hexToRgb(0xffd014); public static final RGBData RgbLightBlue = hexToRgb(0x61fff7); + public static final RGBData RgbLightRed = hexToRgb(0xeb1c1c); + public static final RGBData RgbPurple = hexToRgb(0x9c17a3); public static byte chatColorToClayData(ChatColor chatColor) { @@ -84,4 +86,9 @@ public class UtilColor { return (red << 16 | green << 8 | blue); } + + public static RGBData rgb(int r, int g, int b) + { + return new RGBData(r, g, b); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEnt.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEnt.java index f4f73003a..4b479fb52 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEnt.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEnt.java @@ -5,24 +5,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import net.minecraft.server.v1_8_R3.AxisAlignedBB; -import net.minecraft.server.v1_8_R3.EntityBat; -import net.minecraft.server.v1_8_R3.EntityCreature; -import net.minecraft.server.v1_8_R3.EntityEnderDragon; -import net.minecraft.server.v1_8_R3.EntityHuman; -import net.minecraft.server.v1_8_R3.EntityInsentient; -import net.minecraft.server.v1_8_R3.EntityLiving; -import net.minecraft.server.v1_8_R3.EntityTrackerEntry; -import net.minecraft.server.v1_8_R3.NavigationAbstract; -import net.minecraft.server.v1_8_R3.PacketPlayOutEntity; -import net.minecraft.server.v1_8_R3.PacketPlayOutEntityHeadRotation; -import net.minecraft.server.v1_8_R3.PathfinderGoal; -import net.minecraft.server.v1_8_R3.PathfinderGoalLookAtPlayer; -import net.minecraft.server.v1_8_R3.PathfinderGoalMoveTowardsRestriction; -import net.minecraft.server.v1_8_R3.PathfinderGoalRandomLookaround; -import net.minecraft.server.v1_8_R3.PathfinderGoalSelector; -import net.minecraft.server.v1_8_R3.WorldServer; - import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -40,8 +22,29 @@ import org.bukkit.entity.EntityType; import org.bukkit.entity.Giant; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.Vector; +import net.minecraft.server.v1_8_R3.AxisAlignedBB; +import net.minecraft.server.v1_8_R3.EntityBat; +import net.minecraft.server.v1_8_R3.EntityCreature; +import net.minecraft.server.v1_8_R3.EntityEnderDragon; +import net.minecraft.server.v1_8_R3.EntityHuman; +import net.minecraft.server.v1_8_R3.EntityInsentient; +import net.minecraft.server.v1_8_R3.EntityLiving; +import net.minecraft.server.v1_8_R3.EntityTrackerEntry; +import net.minecraft.server.v1_8_R3.NavigationAbstract; +import net.minecraft.server.v1_8_R3.PacketPlayOutEntity; +import net.minecraft.server.v1_8_R3.PacketPlayOutEntityHeadRotation; +import net.minecraft.server.v1_8_R3.PathfinderGoal; +import net.minecraft.server.v1_8_R3.PathfinderGoalLookAtPlayer; +import net.minecraft.server.v1_8_R3.PathfinderGoalMoveTowardsRestriction; +import net.minecraft.server.v1_8_R3.PathfinderGoalRandomLookaround; +import net.minecraft.server.v1_8_R3.PathfinderGoalSelector; +import net.minecraft.server.v1_8_R3.WorldServer; + public class UtilEnt { @@ -163,7 +166,7 @@ public class UtilEnt if (entity instanceof CraftCreature) { - EntityCreature creature = ((CraftCreature)entity).getHandle(); + EntityCreature creature = ((CraftCreature) entity).getHandle(); if (_bsRestrictionGoal == null) { @@ -176,26 +179,26 @@ public class UtilEnt if (((CraftEntity)entity).getHandle() instanceof EntityInsentient) { - EntityInsentient creature = (EntityInsentient)((CraftEntity)entity).getHandle(); + EntityInsentient creature = (EntityInsentient) ((CraftEntity) entity).getHandle(); creature.setVegetated(true); creature.setSilent(mute); - ((List) _pathfinderBList.get(((PathfinderGoalSelector)_goalSelector.get(creature)))).clear(); - ((List)_pathfinderCList.get(((PathfinderGoalSelector)_goalSelector.get(creature)))).clear(); + ((List) _pathfinderBList.get(((PathfinderGoalSelector) _goalSelector.get(creature)))).clear(); + ((List) _pathfinderCList.get(((PathfinderGoalSelector) _goalSelector.get(creature)))).clear(); - ((List)_pathfinderBList.get(((PathfinderGoalSelector)_targetSelector.get(creature)))).clear(); - ((List)_pathfinderCList.get(((PathfinderGoalSelector)_targetSelector.get(creature)))).clear(); + ((List) _pathfinderBList.get(((PathfinderGoalSelector) _targetSelector.get(creature)))).clear(); + ((List) _pathfinderCList.get(((PathfinderGoalSelector) _targetSelector.get(creature)))).clear(); } if (((CraftEntity)entity).getHandle() instanceof EntityBat) { - ((EntityBat)((CraftEntity)entity).getHandle()).setVegetated(true); + ((EntityBat) ((CraftEntity) entity).getHandle()).setVegetated(true); } - if (((CraftEntity)entity).getHandle() instanceof EntityEnderDragon) + if (((CraftEntity) entity).getHandle() instanceof EntityEnderDragon) { - EntityEnderDragon creature = (EntityEnderDragon)((CraftEntity)entity).getHandle(); + EntityEnderDragon creature = (EntityEnderDragon) ((CraftEntity) entity).getHandle(); creature.setVegetated(true); } @@ -255,6 +258,34 @@ public class UtilEnt } } + public static void Rotate(LivingEntity entity, float yaw, float pitch) + { + EntityLiving handle = ((CraftLivingEntity) entity).getHandle(); + + while (yaw < -180.0F) yaw += 360.0F; + while (yaw >= 180.0F) yaw -= 360.0F; + + handle.yaw = yaw; + handle.aK = yaw; + handle.aI = yaw; + handle.aL = yaw; + handle.pitch = pitch; + } + + public static void LookAt(LivingEntity entity, Location location) + { + if (!(entity.getWorld().equals(location.getWorld()))) + return; + + Vector dir = entity.getEyeLocation().toVector().subtract(location.toVector()).normalize(); + Location loc = entity.getEyeLocation().clone(); + + loc.setYaw(180 - (float) Math.toDegrees(Math.atan2(dir.getX(), dir.getZ()))); + loc.setPitch(90 - (float) Math.toDegrees(Math.acos(dir.getY()))); + + Rotate(entity, loc.getYaw(), loc.getPitch()); + } + public static void populate() { if (creatureMap.isEmpty()) @@ -442,7 +473,7 @@ public class UtilEnt if (offset < dR) { - ents.put(ent, 1 - (offset/dR)); + ents.put(ent, Double.valueOf(1 - (offset/dR))); continue; } @@ -451,7 +482,7 @@ public class UtilEnt if (offset < dR) { - ents.put(ent, 1 - (offset/dR)); + ents.put(ent, Double.valueOf(1 - (offset/dR))); continue; } } @@ -473,7 +504,7 @@ public class UtilEnt if (offset < dR) { - ents.put(cur, 1 - (offset/dR)); + ents.put(cur, Double.valueOf(1 - (offset/dR))); continue; } } @@ -775,7 +806,7 @@ public class UtilEnt field.setAccessible(true); int entityId = field.getInt(null); if (modifynumber) { - field.set(null, entityId+1); + field.set(null, Integer.valueOf(entityId + 1)); } return entityId; } @@ -815,9 +846,37 @@ public class UtilEnt ((EntityInsentient)e.getHandle()).k(!ai); } } - + + public static double getBlockSizeOfSlime(int size) + { + return .51 * ((double) size); + } + public static boolean inWater(LivingEntity ent) { return ent.getLocation().getBlock().getTypeId() == 8 || ent.getLocation().getBlock().getTypeId() == 9; } + + public static void SetMetadata(Entity entity, String key, Object value) + { + entity.setMetadata(key, new FixedMetadataValue(UtilServer.getPlugin(), value)); + } + + // Nicer than doing entity.getMetadata(key).get(0); + public static Object GetMetadata(Entity entity, String key) + { + if (!entity.hasMetadata(key)) + { + return null; + } + + return entity.getMetadata(key).get(0); + } + + public static void SetItemInHand(LivingEntity entity, ItemStack item) + { + EntityEquipment equipment = entity.getEquipment(); + equipment.setItemInHand(item); + } + } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEvent.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEvent.java index bd5346696..c4bb681a8 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEvent.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilEvent.java @@ -1,5 +1,6 @@ package mineplex.core.common.util; +import org.bukkit.entity.Arrow; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Projectile; import org.bukkit.event.block.Action; @@ -46,6 +47,15 @@ public class UtilEvent return false; } + public static boolean isBowDamage(EntityDamageEvent event) + { + if (!(event instanceof EntityDamageByEntityEvent)) + return false; + + EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event; + return e.getDamager() instanceof Arrow; + } + public static LivingEntity GetDamagerEntity(EntityDamageEvent event, boolean ranged) { if (!(event instanceof EntityDamageByEntityEvent)) diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFile.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFile.java index 5429f0107..038824e40 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFile.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFile.java @@ -1,310 +1,53 @@ package mineplex.core.common.util; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Paths; public class UtilFile { - public static void writePlainFile(File file, String text) throws FileNotFoundException - { - PrintWriter writer = new PrintWriter(file); - writer.print(text); - writer.close(); - } - - /** - * Will read the specified file, and return the contents, or a null value, - * if an exception is thrown. Will handle all exceptions, and simply ignore - * them and return null. No stack trace printed or anything. - */ - public static String readIgnoreErrors(File file) + public static String read(File file) { try { - return readToStr(file); + return new String(readBytes(file)); } - catch (IOException exception) + catch (IOException e) { return null; } } - public static String readToStr(File file) throws IOException - { - return new String(readAllBytes(file)); - } - - public static byte[] readAllBytes(File file) throws IOException - { - return Files.readAllBytes(Paths.get(file.toURI())); - } - - public static void writePlainFile(String file, String text) throws FileNotFoundException - { - writePlainFile(new File(file), text); - } - /** - * Will read the specified file, and return the contents, or a null value, - * if an exception is thrown. Will handle all exceptions, and simply ignore - * them and return null. No stack trace printed or anything. + * @param file + * @return + * @throws IOException */ - public static String readIgnoreErrors(String file) + public static byte[] readBytes(File file) throws IOException { - return readIgnoreErrors(new File(file)); - } - - public static String readToStr(String file) throws IOException - { - return readToStr(new File(file)); - } - - public static byte[] readAllBytes(String file) throws IOException - { - return readAllBytes(new File(file)); - } - - public static void writeDataFile(File file, DataFileChunk... chunks) throws IOException - { - DataOutputStream stream = new DataOutputStream(new FileOutputStream(file)); - for (DataFileChunk chunk : chunks) + FileInputStream stream = new FileInputStream(file); + + byte[] bytes = new byte[stream.available() /* estimated bytes available */]; + + int pointer = 0; + while (true) { - chunk.writeTo(stream); + int read = stream.read(); + + if (read == -1) + { + break; + } + + bytes = UtilCollections.ensureSize(bytes, bytes.length + 1); + + bytes[pointer] = (byte) read; + + ++pointer; } + stream.close(); + + return bytes; } - - public static DataFileReader beginReading(String file) throws FileNotFoundException - { - return beginReading(new File(file)); - } - - public static DataFileReader beginReading(File file) throws FileNotFoundException - { - return new DataFileReader(file); - } - - public static void writeDataFile(String file, DataFileChunk... chunks) throws IOException - { - writeDataFile(new File(file), chunks); - } - - public static class DataFileChunk - { - private ChunkType _type; - private Object _value; - - public DataFileChunk(ChunkType type, Object value) - { - if (type == null) - { - throw new RuntimeException("ChunkType can NOT be null."); - } - - _type = type; - - if (!_type.isValid(value)) - { - throw new RuntimeException("Invalid value provided for the specified ChunkType."); - } - - _value = value; - } - - public void writeTo(DataOutputStream stream) throws IOException - { - _type.writeTo(stream, _value); - } - } - - public static enum ChunkType - { - STRING(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - String str = (String) value; - - INTEGER.writeTo(stream, str.length()); - for (char b : str.toCharArray()) - { - CHAR.writeTo(stream, b); - } - } - - public boolean isValid(Object value) - { - return value.getClass().equals(String.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - int length = (int) INTEGER.readFrom(stream); - - StringBuilder string = new StringBuilder(); - - for (int i = 0; i < length; i++) - { - string.append(CHAR.readFrom(stream)); - } - - return string.toString(); - } - }), - DOUBLE(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - double number = (double) value; - - stream.writeDouble(number); - } - - public boolean isValid(Object value) - { - return value.getClass().equals(Double.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return stream.readDouble(); - } - }), - INTEGER(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - int number = (int) value; - - stream.writeInt(number); - } - - public boolean isValid(Object value) - { - return value.getClass().equals(Integer.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return stream.readInt(); - } - }), - BYTE(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - byte number = (byte) value; - - stream.writeByte(number); - } - - public boolean isValid(Object value) - { - return value.getClass().equals(Byte.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return stream.readByte(); - } - }), - CHAR(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - char number = (char) value; - - stream.writeChar(number); - } - - public boolean isValid(Object value) - { - return value.getClass().equals(Character.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return stream.readChar(); - } - }), - LONG(new ChunkImpl() - { - public void writeTo(DataOutputStream stream, Object value) throws IOException - { - long number = (long) value; - - stream.writeLong(number); - } - - public boolean isValid(Object value) - { - return value.getClass().equals(Long.class); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return stream.readLong(); - } - }); - - private ChunkImpl _impl; - - ChunkType(ChunkImpl impl) - { - _impl = impl; - } - - protected void writeTo(DataOutputStream stream, Object value) throws IOException - { - _impl.writeTo(stream, value); - } - - protected boolean isValid(Object value) - { - return value != null && _impl.isValid(value); - } - - public Object readFrom(DataInputStream stream) throws IOException - { - return _impl.readFrom(stream); - } - } - - public static class DataFileReader - { - private DataInputStream _stream; - - public DataFileReader(File file) throws FileNotFoundException - { - _stream = new DataInputStream(new FileInputStream(file)); - } - - public Object readChunk(ChunkType type) throws IOException - { - return type.readFrom(_stream); - } - - public void close() throws IOException - { - _stream.close(); - } - } - - protected interface ChunkImpl - { - void writeTo(DataOutputStream stream, Object value) throws IOException; - - Object readFrom(DataInputStream stream) throws IOException; - - boolean isValid(Object value); - } - } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFirework.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFirework.java index c017bab66..ba7e00bb9 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFirework.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilFirework.java @@ -74,10 +74,10 @@ public class UtilFirework public static void packetPlayFirework(Player player, Location loc, Type type, Color color, boolean flicker, boolean trail) { - Firework firework = (Firework) loc.getWorld().spawn(loc, Firework.class); + Firework firework = loc.getWorld().spawn(loc, Firework.class); FireworkEffect effect = FireworkEffect.builder().flicker(flicker).withColor(color).with(type).trail(trail).build(); - FireworkMeta data = (FireworkMeta) firework.getFireworkMeta(); + FireworkMeta data = firework.getFireworkMeta(); data.clearEffects(); data.setPower(1); data.addEffect(effect); @@ -98,4 +98,14 @@ public class UtilFirework UtilPlayer.sendPacket(viewing, packet); } } + + public static void spawnRandomFirework(Location location) + { + playFirework(location, + Type.values()[UtilMath.r(Type.values().length)], + Color.fromRGB(UtilMath.r(256), UtilMath.r(256), UtilMath.r(256)), + UtilMath.random.nextBoolean(), + UtilMath.random.nextBoolean() + ); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilInv.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilInv.java index 1b1b5b775..ac42f9ad4 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilInv.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilInv.java @@ -396,4 +396,61 @@ public class UtilInv return amount; } + + public static ItemStack decrement(ItemStack item) + { + ItemStack newItem; + + if (item.getAmount() == 1) + { + newItem = null; + } + else + { + newItem = item; + newItem.setAmount(newItem.getAmount() - 1); + } + + return newItem; + } + + public static boolean HasSpace(Player player, Material material, int amount) + { + int slotsFree = 0; + + for (int slot = 0; slot < player.getInventory().getSize(); slot++) + { + if (player.getInventory().getItem(slot) == null) + { + slotsFree++; + + if (slotsFree >= amount / 64) + { + return true; + } + } + else if (player.getInventory().getItem(slot).getType().equals(material) && amount <= (64 - player.getInventory().getItem(slot).getAmount())) + { + return true; + } + } + + return false; + } + + public static void give(Player player, Material material) + { + give(player, material, 1); + } + + public static void give(Player player, Material material, int amount) + { + give(player, material, amount, (byte) 0); + } + + public static void give(Player shooter, Material material, int amount, byte data) + { + shooter.getInventory().addItem(new ItemStack(material, amount, data)); + } + } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilItem.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilItem.java index 07a5bcf51..11c709372 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilItem.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilItem.java @@ -306,10 +306,10 @@ public class UtilItem _materials.put(Material.DIAMOND_CHESTPLATE, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_CHESTPLATE, ItemCategory.ARMOR)); _materials.put(Material.DIAMOND_LEGGINGS, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_LEGGINGS, ItemCategory.ARMOR)); _materials.put(Material.DIAMOND_BOOTS, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_BOOTS, ItemCategory.ARMOR)); - _materials.put(Material.GOLD_HELMET, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_HELMET, ItemCategory.ARMOR)); - _materials.put(Material.GOLD_CHESTPLATE, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_CHESTPLATE, ItemCategory.ARMOR)); - _materials.put(Material.GOLD_LEGGINGS, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_LEGGINGS, ItemCategory.ARMOR)); - _materials.put(Material.GOLD_BOOTS, EnumSet.of(ItemCategory.ITEM, ItemCategory.DIAMOND, ItemCategory.ARMOR_BOOTS, ItemCategory.ARMOR)); + _materials.put(Material.GOLD_HELMET, EnumSet.of(ItemCategory.ITEM, ItemCategory.GOLD, ItemCategory.ARMOR_HELMET, ItemCategory.ARMOR)); + _materials.put(Material.GOLD_CHESTPLATE, EnumSet.of(ItemCategory.ITEM, ItemCategory.GOLD, ItemCategory.ARMOR_CHESTPLATE, ItemCategory.ARMOR)); + _materials.put(Material.GOLD_LEGGINGS, EnumSet.of(ItemCategory.ITEM, ItemCategory.GOLD, ItemCategory.ARMOR_LEGGINGS, ItemCategory.ARMOR)); + _materials.put(Material.GOLD_BOOTS, EnumSet.of(ItemCategory.ITEM, ItemCategory.GOLD, ItemCategory.ARMOR_BOOTS, ItemCategory.ARMOR)); _materials.put(Material.FLINT, EnumSet.of(ItemCategory.ITEM)); _materials.put(Material.PORK, EnumSet.of(ItemCategory.ITEM, ItemCategory.EDIBLE, ItemCategory.RAW_FOOD)); _materials.put(Material.GRILLED_PORK, EnumSet.of(ItemCategory.ITEM, ItemCategory.EDIBLE)); @@ -550,7 +550,7 @@ public class UtilItem public static boolean isSword(ItemStack stack) { - return isEdible(stack == null ? null : stack.getType()); + return isSword(stack == null ? null : stack.getType()); } public static boolean isSword(Material material) @@ -878,6 +878,16 @@ public class UtilItem return isLeaf(stack == null ? null : stack.getType()); } + public static boolean isDoor(Material type) + { + return type == null ? false : (contains(type, ItemCategory.DOOR)); + } + + public static boolean isDoor(ItemStack stack) + { + return isDoor(stack == null ? null : stack.getType()); + } + public static boolean isTool(Material material) { return material == null ? false : (contains(material, ItemCategory.TOOL)); @@ -1137,4 +1147,56 @@ public class UtilItem i.setItemMeta(im); return i; } + + public static double getAttackDamage(Material type) + { + return ItemDamage.get(type); + } + + enum ItemDamage + { + IRON_SHOVEL(Material.IRON_SPADE, 3), + IRON_PICKAXE(Material.IRON_PICKAXE, 4), + IRON_AXE(Material.IRON_AXE, 5), + WOODEN_SHOVEL(Material.WOOD_SPADE, 1), + WOODEN_PICKAXE(Material.WOOD_PICKAXE, 2), + WOODEN_AXE(Material.WOOD_AXE, 3), + STONE_SHOVEL(Material.STONE_SPADE, 2), + STONE_PICKAXE(Material.STONE_PICKAXE, 3), + STONE_AXE(Material.STONE_AXE, 4), + DIAMOND_SHOVEL(Material.DIAMOND_SPADE, 4), + DIAMOND_PICKAXE(Material.DIAMOND_PICKAXE, 5), + DIAMOND_AXE(Material.DIAMOND_AXE, 6), + GOLD_SHOVEL(Material.GOLD_SPADE, 1), + GOLD_PICKAXE(Material.GOLD_PICKAXE, 2), + GOLD_AXE(Material.GOLD_AXE, 3), + IRON_SWORD(Material.IRON_SWORD, 6), + WOODEN_SWORD(Material.WOOD_SWORD, 4), + STONE_SWORD(Material.STONE_SWORD, 5), + DIAMOND_SWORD(Material.DIAMOND_SWORD, 7), + GOLDEN_SWORD(Material.GOLD_SWORD, 4); + + private double _damage; + private Material _type; + + ItemDamage(Material type, double damage) + { + _type = type; + _damage = damage; + } + + public static double get(Material type) + { + for (ItemDamage item : values()) + { + if (item._type.equals(type)) + { + return item._damage; + } + } + + return 1; + } + + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilMath.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilMath.java index 2c950b705..bd9e1600c 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilMath.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilMath.java @@ -108,6 +108,11 @@ public class UtilMath return num < min ? min : (num > max ? max : num); } + public static float clamp(float num, float min, float max) + { + return num < min ? min : (num > max ? max : num); + } + public static long clamp(long num, long min, long max) { return num < min ? min : (num > max ? max : num); @@ -137,4 +142,145 @@ public class UtilMath return ((double) rand) / 100.d; } + + public static T getLast(List list) + { + return list.isEmpty() ? null : list.get(list.size() - 1); + } + + public static T getFirst(List list) + { + return list.isEmpty() ? null : list.get(0); + } + + public static T getLast(NautArrayList list) + { + return list.isEmpty() ? null : list.get(list.size() - 1); + } + + public static T getFirst(NautArrayList list) + { + return list.isEmpty() ? null : list.get(0); + } + + public static N closest(List values, N value) + { + int closestIndex = -1; + + int index = 0; + for (N number : values) + { + if (closestIndex == -1 || (Math.abs(number.doubleValue() - value.doubleValue()) < Math.abs(values.get(closestIndex).doubleValue() - value.doubleValue()))) + { + closestIndex = index; + } + + index++; + } + + return values.get(closestIndex); + } + + public static boolean isOdd(int size) + { + return !isEven(size); + } + + public static boolean isEven(int size) + { + return size % 2 == 0; + } + + public static byte[] getBits(int value) + { + byte[] bits = new byte[32]; + + String bit = Long.toBinaryString(value); + + while (bit.length() < 32) + { + bit = "0" + bit; + } + + int index = 0; + for (char c : bit.toCharArray()) + { + bits[index] = (byte) (c == '1' ? '1' : '0'); + + index++; + } + + return bits; + } + + public static byte[] getBits(long value) + { + byte[] bits = new byte[64]; + + String bit = Long.toBinaryString(value); + + while (bit.length() < 64) + { + bit = "0" + bit; + } + + int index = 0; + for (char c : bit.toCharArray()) + { + bits[index] = (byte) (c == '1' ? '1' : '0'); + + index++; + } + + return bits; + } + + public static byte[] getBits(byte value) + { + byte[] bits = new byte[8]; + + String bit = Long.toBinaryString(value); + + while (bit.length() < 8) + { + bit = "0" + bit; + } + + int index = 0; + for (char c : bit.toCharArray()) + { + bits[index] = (byte) (c == '1' ? '1' : '0'); + + index++; + } + + return bits; + } + + public static byte[] getBits(short value) + { + byte[] bits = new byte[16]; + + String bit = Long.toBinaryString(value); + + while (bit.length() < 16) + { + bit = "0" + bit; + } + + int index = 0; + for (char c : bit.toCharArray()) + { + bits[index] = (byte) (c == '1' ? '1' : '0'); + + index++; + } + + return bits; + } + + public static double getDecimalPoints(double n) + { + return n - ((int) ((int) n)); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilOfflinePlayer.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilOfflinePlayer.java new file mode 100644 index 000000000..cbc537082 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilOfflinePlayer.java @@ -0,0 +1,29 @@ +package mineplex.core.common.util; + +import java.io.File; +import java.io.FileInputStream; + +import org.bukkit.inventory.ItemStack; + +import com.java.sk89q.jnbt.NBTInputStream; +import com.java.sk89q.jnbt.NamedTag; + +public class UtilOfflinePlayer +{ + public static ItemStack loadOfflineInventory(File file) + { + try (NBTInputStream stream = new NBTInputStream(new FileInputStream(file))) + { + NamedTag tag = stream.readNamedTag(); + + System.out.println(tag); + + } + catch (Exception e) + { + e.printStackTrace(); + } + + return null; + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilPlayer.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilPlayer.java index e013329cf..316ffedd8 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilPlayer.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilPlayer.java @@ -27,6 +27,7 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.util.BlockIterator; import org.bukkit.util.Vector; +import mineplex.core.common.MinecraftVersion; import net.minecraft.server.v1_8_R3.EntityPlayer; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PlayerConnection; @@ -67,6 +68,11 @@ public class UtilPlayer return true; } + public static boolean is1_9(Player player) + { + return ((CraftPlayer) player).getHandle().playerConnection.networkManager.getVersion() > 47; + } + private static class Vector3D { @@ -336,7 +342,7 @@ public class UtilPlayer { if (cur.getName().equalsIgnoreCase(player)) return cur; - + if (cur.getName().toLowerCase().contains(player.toLowerCase())) matchList.add(cur); } @@ -784,4 +790,37 @@ public class UtilPlayer return null; } + + public static boolean isGliding(Player player) + { + return ((CraftPlayer) player).getHandle().isGliding(); + } + + public static void setGliding(Player player, boolean gliding) + { + ((CraftPlayer) player).getHandle().setGliding(gliding); + } + + public static void setAutoDeploy(Player player, boolean autoDeploy) + { + ((CraftPlayer) player).getHandle().setAutoWingsDeploy(autoDeploy); + } + + public static void setGlidableWithoutWings(Player player, boolean glidableWithoutWings) + { + ((CraftPlayer) player).getHandle().setGlidableWithoutWings(glidableWithoutWings); + } + + public static void setAutoDeployDistance(Player player, float distance) + { + ((CraftPlayer) player).getHandle().setWingsDeployAt(distance); + } + + public static MinecraftVersion getVersion(Player player) + { + if (is1_9(player)) + return MinecraftVersion.Version1_9; + + return MinecraftVersion.Version1_8; + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilServer.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilServer.java index 79f248c3d..2b574345e 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilServer.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilServer.java @@ -1,20 +1,38 @@ package mineplex.core.common.util; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; -import java.util.stream.Stream; import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.Sound; import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.scheduler.BukkitRunnable; + +import com.google.common.collect.Lists; + +import mineplex.core.common.events.PlayerRecieveBroadcastEvent; public class UtilServer { + // Quite hacky. would be nice if we could have a "MineplexPlugin" interface + // which would define a getServerName() method and then implement it in + // whatever way needed. + // MineplexPlugin plugin = (MineplexPlugin) plugin.getClass().getDeclaredMethod("getMineplexPlugin").invoke(plugin); + // plugin.getServerName(); + private static String _serverName; + public static Player[] getPlayers() { return getServer().getOnlinePlayers().toArray(new Player[0]); @@ -52,7 +70,10 @@ public class UtilServer public static void broadcast(String message) { for (Player cur : getPlayers()) - UtilPlayer.message(cur, message); + { + if (!UtilServer.CallEvent(new PlayerRecieveBroadcastEvent(cur, message)).isCancelled()) + UtilPlayer.message(cur, message); + } } public static void broadcast(LinkedList messages) @@ -86,4 +107,116 @@ public class UtilServer { return (double)getPlayers().length / (double)UtilServer.getServer().getMaxPlayers(); } + + public static void RegisterEvents(Listener listener) + { + getPluginManager().registerEvents(listener, getPlugin()); + } + + public static void Unregister(Listener listener) + { + HandlerList.unregisterAll(listener); + } + + public static Plugin getPlugin() + { + return getPluginManager().getPlugins()[0]; + } + + public static PluginManager getPluginManager() + { + return getServer().getPluginManager(); + } + + public static T CallEvent(T event) + { + getPluginManager().callEvent(event); + return event; + } + + public static void repeat(BukkitRunnable runnable, long time) + { + runnable.runTaskTimer(getPlugin(), time, time); + } + + public static boolean IsOnline(String name) + { + return !UtilStreams.IsEmpty(getPlayersCollection().stream().filter(player -> player.getName().equals(name))); + } + + public static Player GetPlayer(String name) + { + return UtilStreams.GetFirst(getPlayersCollection().stream().filter(player -> player.getName().equals(name))); + } + + public static OfflinePlayer GetOffline(String player) + { + return getServer().getOfflinePlayer(player); + } + + public static String getServerName() + { + if (_serverName == null) + { + try + { + Class Portal = Class.forName("mineplex.core.portal.Portal"); + + Object instance = null; + + List stringFields = Lists.newArrayList(); + + for (Field field : Portal.getDeclaredFields()) + { + if (field.getType().equals(Portal)) + { + field.setAccessible(true); + instance = field.get(null); + } + + if (field.getType().equals(String.class)) + { + stringFields.add(field); + } + } + + for (Field field : stringFields) + { + field.setAccessible(true); + String value = (String) field.get(instance); + + if (stringFields.size() > 1) + { + if (value.contains("-")) + { + _serverName = new String(value); + } + } + else + { + _serverName = new String(value); + } + } + + if (_serverName == null) + { + _serverName = "UNKOWN"; + System.out.println("ERROR: Could not get server name from Portal. Cause is most likely ambiguous fields in the class. Please revise UtilServer's method of getting the current server name."); + } + } + catch (Exception exception) + { + System.out.println("FATAL ERROR WHILE TRYING TO GET SERVER NAME"); + exception.printStackTrace(); + + } + } + + return _serverName; + } + + public static Collection GetPlayers() + { + return Lists.newArrayList(getPlayers()); + } } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilShapes.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilShapes.java index dfff5bd5c..a0bda3026 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilShapes.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilShapes.java @@ -11,38 +11,40 @@ public class UtilShapes { private final static BlockFace[] radial = { - BlockFace.SOUTH, BlockFace.SOUTH_WEST, BlockFace.WEST, BlockFace.NORTH_WEST, BlockFace.NORTH, - BlockFace.NORTH_EAST, BlockFace.EAST, BlockFace.SOUTH_EAST + BlockFace.SOUTH, + BlockFace.SOUTH_WEST, + BlockFace.WEST, + BlockFace.NORTH_WEST, + BlockFace.NORTH, + BlockFace.NORTH_EAST, + BlockFace.EAST, + BlockFace.SOUTH_EAST }; public static ArrayList getCircle(Location loc, boolean hollow, double radius) { - return getCircleBlocks(loc, radius, 0, hollow, false); + return getSphereBlocks(loc, radius, 0, hollow); } - public static ArrayList getSphereBlocks(Location loc, double radius, double height, boolean hollow) - { - return getCircleBlocks(loc, radius, height, hollow, true); - } - - private static ArrayList getCircleBlocks(Location loc, double radius, double height, boolean hollow, boolean sphere) + public static ArrayList getSphereBlocks(Location loc, double width, double height, boolean hollow) { ArrayList circleblocks = new ArrayList(); double cx = loc.getBlockX(); double cy = loc.getBlockY(); double cz = loc.getBlockZ(); - for (double y = (sphere ? cy - radius : cy); y < (sphere ? cy + radius : cy + height + 1); y++) + for (double y = height; y < height + 1; y++) { - for (double x = cx - radius; x <= cx + radius; x++) + for (double x = -width; x <= width; x++) { - for (double z = cz - radius; z <= cz + radius; z++) + for (double z = -width; z <= width; z++) { - double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0); + double dist = (x * x) + (z * z) + (y * y); - if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1))) + if (dist < width * width + && !(hollow && Math.abs(x) - width < 1 && Math.abs(z) - width < 1 && Math.abs(y) - height < 1)) { - Location l = new Location(loc.getWorld(), x, y, z); + Location l = new Location(loc.getWorld(), x + cx, y + cy, z + cz); circleblocks.add(l); } } @@ -51,7 +53,7 @@ public class UtilShapes return circleblocks; } - + /** * Gets the block at the exact corners, will return a diagonal. * @@ -75,7 +77,8 @@ public class UtilShapes right = radial[high]; return new BlockFace[] { - left, right + left, + right }; } } @@ -87,13 +90,19 @@ public class UtilShapes BlockFace[] faces = getSideBlockFaces(facing); return new Block[] { - b.getRelative(faces[0]), b.getRelative(faces[1]) + b.getRelative(faces[0]), + b.getRelative(faces[1]) }; } public static BlockFace getFacing(float yaw) { - return radial[Math.round(yaw / 45f) & 0x7]; + return radial[Math.round(yaw / 45f) % 8]; + } + + public static float getFacing(BlockFace face) + { + return UtilAlg.GetYaw(new Vector(face.getModX(), face.getModY(), face.getModZ()).normalize()); } public static ArrayList getLinesDistancedPoints(Location startingPoint, Location endingPoint, @@ -133,6 +142,24 @@ public class UtilShapes return locs; } + /** + * Rotates the blocks around 0,0,0 + */ + public static ArrayList rotate(ArrayList locs, double degree) + { + ArrayList rotated = new ArrayList(); + + for (Location loc : locs) + { + double xRot = Math.cos(degree) * (loc.getX()) - Math.sin(degree) * (loc.getZ()); + double zRot = loc.getZ() + Math.sin(degree) * (loc.getX()) + Math.cos(degree) * (loc.getZ()); + + rotated.add(new Location(loc.getWorld(), xRot, loc.getY(), zRot)); + } + + return rotated; + } + public static ArrayList getDistancedCircle(Location center, double pointsDistance, double circleRadius) { return getPointsInCircle(center, (int) ((circleRadius * Math.PI * 2) / pointsDistance), circleRadius); @@ -157,12 +184,14 @@ public class UtilShapes new int[] { - allowDiagonal ? facing.getModX() : facing.getModZ(), allowDiagonal ? 0 : -facing.getModX() + allowDiagonal ? facing.getModX() : facing.getModZ(), + allowDiagonal ? 0 : -facing.getModX() }, new int[] { - allowDiagonal ? 0 : -facing.getModZ(), allowDiagonal ? facing.getModZ() : facing.getModX() + allowDiagonal ? 0 : -facing.getModZ(), + allowDiagonal ? facing.getModZ() : facing.getModX() } }; @@ -189,7 +218,8 @@ public class UtilShapes { faces = new BlockFace[] { - faces[1], faces[0] + faces[1], + faces[0] }; } @@ -228,7 +258,8 @@ public class UtilShapes return new Block[] { - b.getRelative(faces[0]), b.getRelative(faces[1]) + b.getRelative(faces[0]), + b.getRelative(faces[1]) }; } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilStreams.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilStreams.java new file mode 100644 index 000000000..4fea3c6de --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilStreams.java @@ -0,0 +1,58 @@ +package mineplex.core.common.util; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.stream.Stream; + +import org.apache.commons.lang.Validate; + +public class UtilStreams +{ + public static boolean IsEmpty(Stream stream) + { + return Sum(stream) != 0; + } + + public static int Sum(Stream stream) + { + return stream.mapToInt(v -> 1).sum(); + } + + public static Object[] ToArray(Stream stream) + { + return stream.toArray(); + } + + public static T Get(int index, Stream stream) + { + if (Sum(stream) < index + 1) + { + return null; + } + + return (T) ToArray(stream)[index]; + } + + public static T GetFirst(Stream stream) + { + return Get(0, stream); + } + + public static T GetLast(Stream stream) + { + return Get(Sum(stream) + 1, stream); + } + + public static byte[] ReadBytes(DataInputStream dos, int bytes) throws IOException + { + Validate.isTrue(bytes > 0, "Amount of bytes to read must be > 0"); + + byte[] read = new byte[bytes]; + + for (int i = 0; i < bytes; i++) + read[i] = dos.readByte(); + + return read; + } + +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilText.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilText.java index fe42fdf3c..61aa6b007 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilText.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilText.java @@ -6,14 +6,14 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.UUID; import javax.imageio.ImageIO; -import mineplex.core.common.CurrencyType; - import org.apache.commons.lang.WordUtils; import org.bukkit.ChatColor; -import org.bukkit.entity.Player; + +import mineplex.core.common.CurrencyType; public class UtilText { @@ -614,6 +614,11 @@ public class UtilText public static String repeat(String txt, int times) { + if (times <= 0) + { + return new String(); + } + return new String(new byte[times]).replace("\0", txt); } @@ -653,12 +658,16 @@ public class UtilText } public static String getProgress(String prefix, double amount, String suffix, boolean progressDirectionSwap) + { + return getProgress(prefix, amount, suffix, progressDirectionSwap, 24); + } + + public static String getProgress(String prefix, double amount, String suffix, boolean progressDirectionSwap, int bars) { if (progressDirectionSwap) amount = 1 - amount; //Generate Bar - int bars = 24; String progressBar = C.cGreen + ""; boolean colorChange = false; for (int i=0 ; i _lastUpdated = new HashMap(); + + // Display public static void displayTextBar(final Player player, double healthPercent, String text) { - deleteOld(player); - - healthPercent = Math.min(1, healthPercent); - - //Display Dragon + if (_lastUpdated.containsKey(player.getName())) { - Location loc = player.getLocation().subtract(0, 200, 0); - - UtilPlayer.sendPacket(player, getDragonPacket(text, healthPercent, loc)); + _lastUpdated.get(player.getName()).cancel(); } - - - //Display Wither (as well as Dragon) - Location loc = player.getEyeLocation().add(player.getLocation().getDirection().multiply(24)); - UtilPlayer.sendPacket(player, getWitherPacket(text, healthPercent, loc)); - - //Remove - Bukkit.getServer().getScheduler().runTaskLater(Bukkit.getPluginManager().getPlugins()[0], new Runnable() + healthPercent = Math.max(0, Math.min(1, healthPercent)); + + // Remove + final BukkitRunnable runnable = new BukkitRunnable() { public void run() { + if (_lastUpdated.containsKey(player.getName()) && _lastUpdated.get(player.getName()) != this) + return; + deleteOld(player); + + _lastUpdated.remove(player.getName()); } - }, 20); + }; + + runnable.runTaskLater(Bukkit.getPluginManager().getPlugins()[0], 20); + + if (UtilPlayer.is1_9(player)) + { + sendBossBar(player, healthPercent, text); + + _lastUpdated.put(player.getName(), runnable); + return; + } + + _lastUpdated.put(player.getName(), runnable); + + deleteOld(player); + + // Display Dragon + { + Location loc = player.getLocation().subtract(0, 200, 0); + + UtilPlayer.sendPacket(player, getDragonPacket(text, healthPercent, loc)); + } + + // Display Wither (as well as Dragon) + Location loc = player.getEyeLocation().add(player.getLocation().getDirection().multiply(24)); + + UtilPlayer.sendPacket(player, getWitherPacket(text, healthPercent, loc)); + + } + + private static void sendBossBar(Player player, double health, String text) + { + if (_lastUpdated.containsKey(player.getName())) + { + PacketPlayOutBossBar bossBar1 = new PacketPlayOutBossBar(); + + bossBar1.uuid = BossUUID; + bossBar1.action = 2; + bossBar1.health = (float) health; + + PacketPlayOutBossBar bossBar2 = new PacketPlayOutBossBar(); + + bossBar2.uuid = BossUUID; + bossBar2.action = 3; + bossBar2.title = text; + + UtilPlayer.sendPacket(player, bossBar1, bossBar2); + } + else + { + PacketPlayOutBossBar bossBar = new PacketPlayOutBossBar(); + + bossBar.uuid = BossUUID; + bossBar.title = text; + bossBar.health = (float) health; + bossBar.color = 2; + + UtilPlayer.sendPacket(player, bossBar); + } } private static void deleteOld(Player player) { + if (UtilPlayer.is1_9(player)) + { + PacketPlayOutBossBar bossBar = new PacketPlayOutBossBar(); + + bossBar.uuid = BossUUID; + bossBar.action = 1; + + UtilPlayer.sendPacket(player, bossBar); + return; + } // Delete Dragon (All Clients) PacketPlayOutEntityDestroy destroyDragonPacket = new PacketPlayOutEntityDestroy(new int[] { - EntityDragonId + EntityDragonId }); UtilPlayer.sendPacket(player, destroyDragonPacket); // Delete Wither (1.8+ Only) PacketPlayOutEntityDestroy destroyWitherPacket = new PacketPlayOutEntityDestroy(new int[] { - EntityWitherId + EntityWitherId }); UtilPlayer.sendPacket(player, destroyWitherPacket); } - + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) + { + if (UtilPlayer.is1_9(event.getPlayer())) + { + deleteOld(event.getPlayer()); + } + } + public static PacketPlayOutSpawnEntityLiving getDragonPacket(String text, double healthPercent, Location loc) { PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving(); - mobPacket.a = (int) EntityDragonId; //Entity ID - mobPacket.b = (byte) EntityType.ENDER_DRAGON.getTypeId(); //Mob type - mobPacket.c = (int) Math.floor(loc.getBlockX() * 32.0D); //X position - mobPacket.d = (int) MathHelper.floor(loc.getBlockY() * 32.0D); //Y position - mobPacket.e = (int) Math.floor(loc.getBlockZ() * 32.0D); //Z position - mobPacket.f = (byte) 0; //Pitch - mobPacket.g = (byte) 0; //Head Pitch - mobPacket.h = (byte) 0; //Yaw - mobPacket.i = (short) 0; //X velocity - mobPacket.j = (short) 0; //Y velocity - mobPacket.k = (short) 0; //Z velocity - - //Health + mobPacket.a = (int) EntityDragonId; // Entity ID + mobPacket.b = (byte) EntityType.ENDER_DRAGON.getTypeId(); // Mob type + mobPacket.c = (int) Math.floor(loc.getBlockX() * 32.0D); // X position + mobPacket.d = (int) MathHelper.floor(loc.getBlockY() * 32.0D); // Y position + mobPacket.e = (int) Math.floor(loc.getBlockZ() * 32.0D); // Z position + mobPacket.f = (byte) 0; // Pitch + mobPacket.g = (byte) 0; // Head Pitch + mobPacket.h = (byte) 0; // Yaw + mobPacket.i = (short) 0; // X velocity + mobPacket.j = (short) 0; // Y velocity + mobPacket.k = (short) 0; // Z velocity + mobPacket.uuid = UUID.randomUUID(); + + // Health double health = healthPercent * 199.9 + 0.1; - //if (halfHealth) - // health = healthPercent * 99 + 101; - - //Watcher + // if (halfHealth) + // health = healthPercent * 99 + 101; + + // Watcher DataWatcher watcher = getWatcher(text, health, loc.getWorld()); mobPacket.l = watcher; return mobPacket; } - + public static PacketPlayOutSpawnEntityLiving getWitherPacket(String text, double healthPercent, Location loc) { PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving(); - mobPacket.a = (int) EntityWitherId; //Entity ID - mobPacket.b = (byte) EntityType.WITHER.getTypeId(); //Mob type - mobPacket.c = (int) Math.floor(loc.getBlockX() * 32.0D); //X position - mobPacket.d = (int) MathHelper.floor(loc.getBlockY() * 32.0D); //Y position - mobPacket.e = (int) Math.floor(loc.getBlockZ() * 32.0D); //Z position - mobPacket.f = (byte) 0; //Pitch - mobPacket.g = (byte) 0; //Head Pitch - mobPacket.h = (byte) 0; //Yaw - mobPacket.i = (short) 0; //X velocity - mobPacket.j = (short) 0; //Y velocity - mobPacket.k = (short) 0; //Z velocity - - //Health + mobPacket.a = (int) EntityWitherId; // Entity ID + mobPacket.b = (byte) EntityType.WITHER.getTypeId(); // Mob type + mobPacket.c = (int) Math.floor(loc.getBlockX() * 32.0D); // X position + mobPacket.d = (int) MathHelper.floor(loc.getBlockY() * 32.0D); // Y position + mobPacket.e = (int) Math.floor(loc.getBlockZ() * 32.0D); // Z position + mobPacket.f = (byte) 0; // Pitch + mobPacket.g = (byte) 0; // Head Pitch + mobPacket.h = (byte) 0; // Yaw + mobPacket.i = (short) 0; // X velocity + mobPacket.j = (short) 0; // Y velocity + mobPacket.k = (short) 0; // Z velocity + mobPacket.uuid = UUID.randomUUID(); + + // Health double health = healthPercent * 299.9 + 0.1; - //if (halfHealth) - // health = healthPercent * 149 + 151; - - //Watcher + // if (halfHealth) + // health = healthPercent * 149 + 151; + + // Watcher DataWatcher watcher = getWatcher(text, health, loc.getWorld()); mobPacket.l = watcher; return mobPacket; } - + public static DataWatcher getWatcher(String text, double health, World world) { - DataWatcher watcher = new DataWatcher(new DummyEntity(((CraftWorld)world).getHandle())); + DataWatcher watcher = new DataWatcher(new DummyEntity(((CraftWorld) world).getHandle())); - watcher.a(0, (Byte) (byte) 0); //Flags, 0x20 = invisible - watcher.a(6, (Float) (float) health); - watcher.a(2, (String) text); //Entity name - watcher.a(3, (Byte) (byte) 0); //Show name, 1 = show, 0 = don't show - watcher.a(16, (Integer) (int) health); //Health - watcher.a(20, (Integer) (int) 881); //Inv - - int i1 = watcher.getByte(0); - watcher.watch(0, Byte.valueOf((byte)(i1 | 1 << 5))); + watcher.a(0, (Byte) (byte) (0 | 1 << 5), Entity.META_ENTITYDATA, (byte) (0 | 1 << 5)); // Flags, 0x20 = invisible + watcher.a(6, (Float) (float) health, EntityLiving.META_HEALTH, (float) health); + watcher.a(2, (String) text, Entity.META_CUSTOMNAME, text); // Entity name + watcher.a(3, (Byte) (byte) 0, Entity.META_CUSTOMNAME_VISIBLE, false); // Show name, 1 = show, 0 = don't show + // watcher.a(16, (Integer) (int) health, EntityWither.META); //Health + watcher.a(20, (Integer) (int) 881, EntityWither.META_INVUL_TIME, 881); // Inv return watcher; } diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilTrig.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilTrig.java new file mode 100644 index 000000000..5eb5311f5 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilTrig.java @@ -0,0 +1,80 @@ +package mineplex.core.common.util; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.util.Vector; + +public class UtilTrig +{ + public static List GetCirclePoints(Vector origin, int points, double radius) + { + List list = new LinkedList<>(); + + double slice = 2 * Math.PI / points; + + for (int point = 0; point < points; point++) + { + double angle = slice * point; + list.add(new Vector(origin.getX() + radius * Math.cos(angle), 0, origin.getZ() + radius * Math.sin(angle))); + } + + return list; + } + + public static ArrayList GetSpherePoints(Location loc, double radius, double height, boolean hollow, double addition) + { + ArrayList circleblocks = new ArrayList(); + double cx = loc.getBlockX(); + double cy = loc.getBlockY(); + double cz = loc.getBlockZ(); + + for (double y = cy - radius; y < cy + radius; y += addition) + { + for (double x = cx - radius; x <= cx + radius; x += addition) + { + for (double z = cz - radius; z <= cz + radius; z += addition) + { + double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (cy - y) * (cy - y); + + if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1))) + { + Location l = new Location(loc.getWorld(), x, y, z); + circleblocks.add(l); + } + } + } + } + + return circleblocks; + } + + public static List GetSpherePoints(Vector vector, double radius, double height, boolean hollow, double addition) + { + List circleblocks = new ArrayList<>(); + double cx = vector.getX(); + double cy = vector.getY(); + double cz = vector.getZ(); + + for (double y = cy - radius; y < cy + radius; y += addition) + { + for (double x = cx - radius; x <= cx + radius; x += addition) + { + for (double z = cz - radius; z <= cz + radius; z += addition) + { + double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (cy - y) * (cy - y); + + if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1))) + { + Vector l = new Vector(x, y, z); + circleblocks.add(l); + } + } + } + } + + return circleblocks; + } +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWeb.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWeb.java new file mode 100644 index 000000000..5b45d1913 --- /dev/null +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWeb.java @@ -0,0 +1,58 @@ +package mineplex.core.common.util; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Map; + +public class UtilWeb +{ + public static String doPOST(String url, Map params) + { + try + { + StringBuilder postData = new StringBuilder(); + for (Map.Entry param : params.entrySet()) + { + if (postData.length() != 0) + { + postData.append('&'); + } + + postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); + postData.append('='); + postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); + } + + byte[] postDataBytes = postData.toString().getBytes("UTF-8"); + + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); + conn.setDoOutput(true); + conn.getOutputStream().write(postDataBytes); + + Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); + + StringBuilder back = new StringBuilder(); + + for (int $char; ($char = in.read()) >= 0;) + { + back.append((char) $char); + } + + return back.toString(); + } + catch (Exception exception) + { + exception.printStackTrace(); + + return null; + } + } + +} diff --git a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWorld.java b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWorld.java index 321ba7ee9..cef329774 100644 --- a/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWorld.java +++ b/Plugins/Mineplex.Core.Common/src/mineplex/core/common/util/UtilWorld.java @@ -2,18 +2,20 @@ package mineplex.core.common.util; import java.util.Collection; import java.util.List; -import java.util.function.Predicate; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; +import org.bukkit.WorldBorder; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.util.Vector; import com.google.common.collect.Lists; +import net.minecraft.server.v1_8_R3.AxisAlignedBB; + public class UtilWorld { public static World getWorld(String world) @@ -209,4 +211,82 @@ public class UtilWorld origin.getBlock().getRelative(BlockFace.SOUTH), origin.getBlock().getRelative(BlockFace.WEST)); } + + /** + * This method will use the World provided by the given Location.

+ * @return true if the specified location is within the bounds of the + * world's set border, or false if {@link World#getWorldBorder()} returns null. + */ + public static boolean inWorldBorder(Location location) + { + WorldBorder border = location.getWorld().getWorldBorder(); + + if (border == null) + { + return false; + } + + double size = border.getSize() / 2; + + double maxX = size; + double maxZ = size; + double minX = -size; + double minZ = -size; + + return location.getX() >= minX && location.getX() <= maxX && location.getZ() >= minZ && location.getZ() <= maxZ; + } + + /** + * This method will use the World specified by the second argument, and the + * x, y, and z provided by the given Location.

+ * @return true if the specified location is within the bounds of the + * world's set border, or false if {@link World#getWorldBorder()} returns null. + */ + public static boolean inWorldBorder(World world, Location location) + { + WorldBorder border = world.getWorldBorder(); + + if (border == null) + { + return false; + } + + double size = border.getSize() / 2; + + double maxX = size; + double maxZ = size; + double minX = -size; + double minZ = -size; + + return location.getX() >= minX && location.getX() <= maxX && location.getZ() >= minZ && location.getZ() <= maxZ; + } + + /** + * @return true if the specified bounding box is within the bounds of the + * world's set border, or false if {@link World#getWorldBorder()} returns null. + */ + public static boolean isBoxInWorldBorder(World world, Location min, Location max) + { + WorldBorder border = world.getWorldBorder(); + + if (border == null) + { + return false; + } + + double size = border.getSize() / 2; + + double maxX = size; + double maxZ = size; + double minX = -size; + double minZ = -size; + + double startX = Math.min(min.getX(), max.getX()); + double startZ = Math.min(min.getZ(), max.getZ()); + double endX = Math.max(min.getX(), max.getX()); + double endZ = Math.max(min.getZ(), max.getZ()); + + return startX >= minX && startZ <= maxX && endX >= minZ && endZ <= maxZ; + } + } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java b/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java index 6dd6d2c29..215d47c08 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/CustomTagFix.java @@ -19,6 +19,8 @@ import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import net.minecraft.server.v1_8_R3.DataWatcher; import net.minecraft.server.v1_8_R3.DataWatcher.WatchableObject; +import net.minecraft.server.v1_8_R3.Entity; +import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity; import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity.EnumEntityUseAction; @@ -26,6 +28,7 @@ import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata; import net.minecraft.server.v1_8_R3.PacketPlayOutNamedEntitySpawn; +import net.minecraft.server.v1_8_R3.PacketPlayOutNewAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; @@ -65,12 +68,12 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook { super("Custom Tag Fix", plugin); - packetHandler.addPacketHandler(this, true, PacketPlayOutAttachEntity.class, PacketPlayOutEntityDestroy.class, - PacketPlayOutEntityMetadata.class, PacketPlayOutSpawnEntity.class, PacketPlayOutSpawnEntityLiving.class, - PacketPlayOutNamedEntitySpawn.class, PacketPlayInUseEntity.class, PacketPlayOutAttachEntity.class); + packetHandler.addPacketHandler(this, true, PacketPlayOutEntityDestroy.class, PacketPlayOutEntityMetadata.class, + PacketPlayOutSpawnEntity.class, PacketPlayOutSpawnEntityLiving.class, PacketPlayOutNamedEntitySpawn.class, + PacketPlayInUseEntity.class, PacketPlayOutAttachEntity.class, PacketPlayOutNewAttachEntity.class); -// NCPHookManager.addHook(CheckType.MOVING_SURVIVALFLY, this); -// NCPHookManager.addHook(CheckType.MOVING_PASSABLE, this); + // NCPHookManager.addHook(CheckType.MOVING_SURVIVALFLY, this); + // NCPHookManager.addHook(CheckType.MOVING_PASSABLE, this); NCPHookManager.addHook(CheckType.ALL, this); } @@ -119,7 +122,8 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook @EventHandler public void ncpExemptVelocity(final PlayerVelocityEvent event) { - long ignoreTime = System.currentTimeMillis() + (long) (event.getVelocity().length() * 2000); + long ignoreTime = System.currentTimeMillis() + (long) (event.getVelocity().length() * 1500); + if (_exemptTimeMap.containsKey(event.getPlayer().getUniqueId())) { _exemptTimeMap.put(event.getPlayer().getUniqueId(), @@ -254,15 +258,16 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook return; } - int newId = UtilEnt.getNewEntityId(); + Integer[] ids = new Integer[] + { + UtilEnt.getNewEntityId(), + UtilEnt.getNewEntityId() + }; _entityNameMap.get(owner.getName()).put(spawnPacket.a, entityName); - _entityMap.get(owner.getName()).put(spawnPacket.a, new Integer[] - { - newId - }); + _entityMap.get(owner.getName()).put(spawnPacket.a, ids); - sendProtocolPackets(owner, spawnPacket.a, newId, entityName, verifier, true, -1); + sendProtocolPackets(owner, spawnPacket.a, entityName, verifier, true, ids); break; } } @@ -299,17 +304,16 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook return; } - int newId = UtilEnt.getNewEntityId(); - int newId2 = UtilEnt.getNewEntityId(); + Integer[] ids = new Integer[] + { + UtilEnt.getNewEntityId(), + UtilEnt.getNewEntityId() + }; _entityNameMap.get(owner.getName()).put(spawnPacket.a, entityName); - _entityMap.get(owner.getName()).put(spawnPacket.a, new Integer[] - { - newId, - newId2 - }); + _entityMap.get(owner.getName()).put(spawnPacket.a, ids); - sendProtocolPackets(owner, spawnPacket.a, newId2, entityName, verifier, true, newId); + sendProtocolPackets(owner, spawnPacket.a, entityName, verifier, true, ids); break; } } @@ -329,13 +333,13 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook } String newName = currentName; - boolean newDisplay = isDisplaying; + boolean displayName = isDisplaying; for (WatchableObject watchable : (List) metaPacket.b) { if (watchable.a() == 3 && watchable.b() instanceof Byte) { - newDisplay = ((Byte) watchable.b()) == 1; + displayName = ((Byte) watchable.b()) == 1; } if (watchable.a() == 2 && watchable.b() instanceof String) @@ -345,10 +349,10 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook } // If the name has changed and the name should be showing, or the name display status has changed. - if ((!newName.equals(currentName) && newDisplay) || newDisplay != isDisplaying) + if ((!newName.equals(currentName) && displayName) || displayName != isDisplaying) { // If name is still being displayed - if (newDisplay) + if (displayName) { Integer[] newId; @@ -361,6 +365,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook { newId = new Integer[] { + UtilEnt.getNewEntityId(), UtilEnt.getNewEntityId() }; @@ -368,7 +373,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook } _entityNameMap.get(owner.getName()).put(metaPacket.a, newName); - sendProtocolPackets(owner, metaPacket.a, newId[0], newName, verifier, !isDisplaying, -1); + sendProtocolPackets(owner, metaPacket.a, newName, verifier, !isDisplaying, newId); } else { // Lets delete it @@ -449,9 +454,25 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook } } } - else if (packet instanceof PacketPlayOutAttachEntity) + else if (packet instanceof PacketPlayOutAttachEntity || packet instanceof PacketPlayOutNewAttachEntity) { - PacketPlayOutAttachEntity attachPacket = (PacketPlayOutAttachEntity) packet; + int vech = -1; + int rider = -1; + + if (packet instanceof PacketPlayOutAttachEntity) + { + PacketPlayOutAttachEntity attachPacket = (PacketPlayOutAttachEntity) packet; + vech = attachPacket.b; + rider = attachPacket.c; + } + else if (packet instanceof PacketPlayOutNewAttachEntity) + { + PacketPlayOutNewAttachEntity attachPacket = (PacketPlayOutNewAttachEntity) packet; + vech = attachPacket.a; + + if (attachPacket.b.length > 0) + rider = attachPacket.b[0]; + } // c = rider, b = ridden // When detaching, c is sent, b is -1 @@ -470,27 +491,27 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook int vehicleId = -1; - if (_entityRiding.get(owner.getName()).containsKey(attachPacket.b)) + if (_entityRiding.get(owner.getName()).containsKey(vech)) { - vehicleId = _entityRiding.get(owner.getName()).get(attachPacket.b); + vehicleId = _entityRiding.get(owner.getName()).get(vech); } - if (attachPacket.c == -1 && _entityMap.get(owner.getName()).containsKey(vehicleId)) + if (rider == -1 && _entityMap.get(owner.getName()).containsKey(vehicleId)) { Integer[] ids = _entityMap.get(owner.getName()).get(vehicleId); - _entityRiding.get(owner.getName()).remove(attachPacket.b); + _entityRiding.get(owner.getName()).remove(vech); - sendProtocolPackets(owner, vehicleId, ids[ids.length - 1], _entityNameMap.get(owner.getName()).get(vehicleId), - verifier, true, ids.length > 1 ? ids[0] : -1); + sendProtocolPackets(owner, vehicleId, _entityNameMap.get(owner.getName()).get(vehicleId), verifier, true, + ids); } else { - Integer[] ids = _entityMap.get(owner.getName()).get(attachPacket.c); + Integer[] ids = _entityMap.get(owner.getName()).get(rider); - if (ids != null && ids[0] != attachPacket.b) + if (ids != null && ids[1] != vech) { - _entityRiding.get(owner.getName()).put(attachPacket.b, attachPacket.c); + _entityRiding.get(owner.getName()).put(vech, rider); int[] newIds = new int[ids.length]; @@ -506,8 +527,8 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook } } - private void sendProtocolPackets(final Player owner, final int entityId, final int newEntityId, String entityName, - final PacketVerifier packetList, final boolean newPacket, final int squidId) + private void sendProtocolPackets(final Player owner, final int entityId, String entityName, final PacketVerifier packetList, + final boolean newPacket, final Integer[] entityIds) { CustomTagEvent event = new CustomTagEvent(owner, entityId, entityName); _plugin.getServer().getPluginManager().callEvent(event); @@ -519,63 +540,81 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook { DataWatcher watcher = new DataWatcher(new DummyEntity(((CraftWorld) owner.getWorld()).getHandle())); - watcher.a(0, (byte) (0 | 1 << 5)); // Invisible - watcher.a(1, Short.valueOf((short) 300)); - watcher.a(2, finalEntityName); - watcher.a(3, (byte) 1); - watcher.a(4, Byte.valueOf((byte) 0)); - watcher.a(7, Integer.valueOf(0)); - watcher.a(8, Byte.valueOf((byte) 0)); - watcher.a(9, Byte.valueOf((byte) 0)); - watcher.a(6, Float.valueOf(1.0F)); - watcher.a(10, (byte) (0 | 0x1)); // Small + watcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 32); // Invisible + watcher.a(1, Short.valueOf((short) 300), Entity.META_AIR, 0); + watcher.a(2, finalEntityName, Entity.META_CUSTOMNAME, finalEntityName); + watcher.a(3, (byte) 1, Entity.META_CUSTOMNAME_VISIBLE, true); + watcher.a(10, (byte) 16, EntityArmorStand.META_ARMOR_OPTION, (byte) 16); // Small if (newPacket) { - if (squidId >= 0) { - watcher.watch(10, (byte) 16); - DataWatcher squidWatcher = new DataWatcher(new DummyEntity(((CraftWorld) owner.getWorld()).getHandle())); - squidWatcher.a(0, (byte) (0 | 1 << 5)); + squidWatcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 32); PacketPlayOutSpawnEntityLiving spawnPacket = new PacketPlayOutSpawnEntityLiving(); - spawnPacket.a = squidId; + spawnPacket.a = entityIds[1]; spawnPacket.b = (byte) EntityType.SQUID.getTypeId(); - spawnPacket.c = 1000000; + spawnPacket.c = owner.getLocation().getBlockX() * 32; + spawnPacket.d = -150; + spawnPacket.e = owner.getLocation().getBlockZ() * 32; spawnPacket.l = squidWatcher; + spawnPacket.uuid = UUID.randomUUID(); UtilPlayer.sendPacket(owner, spawnPacket); - PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity(); - vehiclePacket.a = 0; - vehiclePacket.b = spawnPacket.a; - vehiclePacket.c = entityId; + if (UtilPlayer.is1_9(owner)) + { + UtilPlayer.sendPacket(owner, new PacketPlayOutNewAttachEntity(entityId, new int[] + { + entityIds[1] + })); + } + else + { + PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity(); + vehiclePacket.a = 0; + vehiclePacket.b = spawnPacket.a; + vehiclePacket.c = entityId; - UtilPlayer.sendPacket(owner, vehiclePacket); + UtilPlayer.sendPacket(owner, vehiclePacket); + } } PacketPlayOutSpawnEntityLiving spawnPacket = new PacketPlayOutSpawnEntityLiving(); - spawnPacket.a = newEntityId; + spawnPacket.a = entityIds[0]; spawnPacket.b = (byte) 30; - spawnPacket.c = 1000000; + spawnPacket.c = owner.getLocation().getBlockX() * 32; + spawnPacket.d = -150; + spawnPacket.e = owner.getLocation().getBlockZ() * 32; spawnPacket.l = watcher; + spawnPacket.uuid = UUID.randomUUID(); UtilPlayer.sendPacket(owner, spawnPacket); - PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity(); - vehiclePacket.a = 0; - vehiclePacket.b = spawnPacket.a; - vehiclePacket.c = squidId >= 0 ? squidId : entityId; + if (UtilPlayer.is1_9(owner)) + { + UtilPlayer.sendPacket(owner, new PacketPlayOutNewAttachEntity(entityIds[1], new int[] + { + entityIds[0] + })); + } + else + { + PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity(); + vehiclePacket.a = 0; + vehiclePacket.b = entityIds[0]; + vehiclePacket.c = entityIds[1]; - UtilPlayer.sendPacket(owner, vehiclePacket); + UtilPlayer.sendPacket(owner, vehiclePacket); + } } else { PacketPlayOutEntityMetadata entityMetadata = new PacketPlayOutEntityMetadata(); - entityMetadata.a = newEntityId; + entityMetadata.a = entityIds[0]; entityMetadata.b = watcher.c(); packetList.bypassProcess(entityMetadata); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/MiniClientPlugin.java b/Plugins/Mineplex.Core/src/mineplex/core/MiniClientPlugin.java index 397e6d0c5..391e86a54 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/MiniClientPlugin.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/MiniClientPlugin.java @@ -15,7 +15,6 @@ public abstract class MiniClientPlugin extends MiniPlug private NautHashMap _clientData = new NautHashMap(); - public MiniClientPlugin(String moduleName, JavaPlugin plugin) { super(moduleName, plugin); @@ -41,7 +40,7 @@ public abstract class MiniClientPlugin extends MiniPlug return _clientData.get(name); } } - + public void saveData(String name, int accountId) {} public DataType Get(Player player) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/MiniPlugin.java b/Plugins/Mineplex.Core/src/mineplex/core/MiniPlugin.java index 732c13816..5bb0abae4 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/MiniPlugin.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/MiniPlugin.java @@ -1,5 +1,9 @@ package mineplex.core; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginManager; @@ -12,6 +16,7 @@ import mineplex.core.common.util.F; import mineplex.core.common.util.NautHashMap; import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilTime.TimeUnit; +import mineplex.core.thread.ThreadPool; public abstract class MiniPlugin implements Listener { @@ -19,11 +24,15 @@ public abstract class MiniPlugin implements Listener protected JavaPlugin _plugin; protected NautHashMap _commands; - public MiniPlugin(String moduleName, JavaPlugin plugin) + protected long _initializedTime; + + public MiniPlugin(String moduleName, JavaPlugin plugin) { _moduleName = moduleName; _plugin = plugin; + _initializedTime = System.currentTimeMillis(); + _commands = new NautHashMap(); onEnable(); @@ -100,12 +109,13 @@ public abstract class MiniPlugin implements Listener public void log(String message) { - System.out.println(F.main(_moduleName, message)); + Bukkit.getConsoleSender().sendMessage(F.main(_moduleName, message)); } public void runAsync(Runnable runnable) { - _plugin.getServer().getScheduler().runTaskAsynchronously(_plugin, runnable); + // Instead of using + ThreadPool.ASYNC.execute(runnable); } public void runAsync(Runnable runnable, long time) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java b/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java index 1f2dc672d..69a745818 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/CoreClientManager.java @@ -1,8 +1,9 @@ package mineplex.core.account; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.UUID; @@ -49,9 +50,8 @@ public class CoreClientManager extends MiniPlugin private NautHashMap _clientList; private HashSet _duplicateLoginGlitchPreventionList; - private NautHashMap _loginProcessors = new NautHashMap(); - private LinkedList _querylessLoginProcessors = new LinkedList(); - + private List _loginProcessors = new ArrayList<>(); + private Object _clientLock = new Object(); private static AtomicInteger _clientsConnecting = new AtomicInteger(0); @@ -185,7 +185,7 @@ public class CoreClientManager extends MiniPlugin if (!LoadClient(Add(event.getName()), event.getUniqueId(), event.getAddress().getHostAddress())) event.disallow(Result.KICK_OTHER, "There was a problem logging you in."); } - catch(Exception exception) + catch (Exception exception) { event.disallow(Result.KICK_OTHER, "Error retrieving information from web, please retry in a minute."); exception.printStackTrace(); @@ -260,7 +260,7 @@ public class CoreClientManager extends MiniPlugin CoreClient client = Add(playerName); client.SetRank(Rank.valueOf(token.Rank), false); - client.setAccountId(_repository.login(_loginProcessors, _querylessLoginProcessors, uuid.toString(), client.GetPlayerName())); + client.setAccountId(_repository.login(_loginProcessors, uuid, client.GetPlayerName())); // JSON sql response Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid)); @@ -332,7 +332,7 @@ public class CoreClientManager extends MiniPlugin CoreClient client = Add(playerName); client.SetRank(Rank.valueOf(token.Rank), false); - client.setAccountId(_repository.login(_loginProcessors, _querylessLoginProcessors, uuid.toString(), client.GetPlayerName())); + client.setAccountId(_repository.login(_loginProcessors, uuid, client.GetPlayerName())); // JSON sql response Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid)); @@ -373,12 +373,18 @@ public class CoreClientManager extends MiniPlugin _clientLoginLock.put(client.GetPlayerName(), new Object()); ClientToken token = null; Gson gson = new Gson(); - + runAsync(new Runnable() { + @Override public void run() { - client.setAccountId(_repository.login(_loginProcessors, _querylessLoginProcessors, uuid.toString(), client.GetPlayerName())); + try { + client.setAccountId(_repository.login(_loginProcessors, uuid, client.GetPlayerName())); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } _clientLoginLock.remove(client.GetPlayerName()); } }); @@ -386,7 +392,8 @@ public class CoreClientManager extends MiniPlugin TimingManager.start(client.GetPlayerName() + " GetClient."); String response = _repository.GetClient(client.GetPlayerName(), uuid, ipAddress); TimingManager.stop(client.GetPlayerName() + " GetClient."); - + + TimingManager.start(client.GetPlayerName() + " Event."); token = gson.fromJson(response, ClientToken.class); client.SetRank(Rank.valueOf(token.Rank), false); @@ -395,7 +402,9 @@ public class CoreClientManager extends MiniPlugin // JSON sql response Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid)); - + TimingManager.stop(client.GetPlayerName() + " Event."); + + TimingManager.start(client.GetPlayerName() + " While Loop."); while (_clientLoginLock.containsKey(client.GetPlayerName()) && System.currentTimeMillis() - timeStart < 15000) { try @@ -407,6 +416,7 @@ public class CoreClientManager extends MiniPlugin e.printStackTrace(); } } + TimingManager.stop(client.GetPlayerName() + " While Loop."); if (_clientLoginLock.containsKey(client.GetPlayerName())) { @@ -646,14 +656,9 @@ public class CoreClientManager extends MiniPlugin public void addStoredProcedureLoginProcessor(ILoginProcessor processor) { - _loginProcessors.put(processor.getName(), processor); + _loginProcessors.add(processor); } - public void addStoredProcedureLoginProcessor(IQuerylessLoginProcessor processor) - { - _querylessLoginProcessors.add(processor); - } - public boolean hasRank(Player player, Rank rank) { CoreClient client = Get(player); @@ -662,10 +667,4 @@ public class CoreClientManager extends MiniPlugin return client.GetRank().has(rank); } - - public int getCachedClientAccountId(UUID uuid) - { - PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid); - return playerInfo == null ? -1 : playerInfo.getAccountId(); - } } \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java index 746b3cf6b..e00cd1b21 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/account/repository/AccountRepository.java @@ -6,30 +6,28 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; -import mineplex.core.database.MinecraftRepository; import org.bukkit.Bukkit; import com.google.gson.reflect.TypeToken; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.cache.player.PlayerCache; import mineplex.core.account.ILoginProcessor; -import mineplex.core.account.IQuerylessLoginProcessor; import mineplex.core.account.repository.token.LoginToken; import mineplex.core.account.repository.token.RankUpdateToken; import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; -import mineplex.core.common.util.NautHashMap; +import mineplex.core.database.MinecraftRepository; +import mineplex.core.server.remotecall.JsonWebCall; import mineplex.serverdata.database.DBPool; import mineplex.serverdata.database.DatabaseRunnable; -import mineplex.serverdata.database.RepositoryBase; import mineplex.serverdata.database.ResultSetCallable; import mineplex.serverdata.database.column.ColumnBoolean; import mineplex.serverdata.database.column.ColumnTimestamp; import mineplex.serverdata.database.column.ColumnVarChar; -import mineplex.core.server.remotecall.JsonWebCall; public class AccountRepository extends MinecraftRepository { @@ -59,107 +57,68 @@ public class AccountRepository extends MinecraftRepository //executeUpdate(CREATE_ACCOUNT_TABLE); } - public int login(NautHashMap loginProcessors, LinkedList querylessLoginProcessors, String uuid, String name) + public int login(final List loginProcessors, final UUID uuid, final String name) throws SQLException { - int accountId = -1; - try ( - Connection connection = getConnection(); - Statement statement = connection.createStatement() - ) + // First we try to grab the account id from cache - this saves an extra trip to database + int accountId = PlayerCache.getInstance().getAccountId(uuid); + + try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { - statement.execute("SELECT id FROM accounts WHERE accounts.uuid = '" + uuid + "' LIMIT 1;"); - ResultSet resultSet = statement.getResultSet(); - - while (resultSet.next()) + if (accountId <= 0) { - accountId = resultSet.getInt(1); - } - - if (accountId == -1) - { - final List tempList = new ArrayList(1); - - executeInsert(ACCOUNT_LOGIN_NEW, new ResultSetCallable() - { - @Override - public void processResultSet(ResultSet resultSet) throws SQLException - { - while (resultSet.next()) - { - tempList.add(resultSet.getInt(1)); - } - } - },new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("name", 100, name)); - - accountId = tempList.get(0); - } - - /* - boolean statementStatus = statement.execute( - "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE accounts.uuid = '" + uuid + "';" - + "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests FROM accountPreferences WHERE accountPreferences.uuid = '" + uuid + "' LIMIT 1;" - + "SELECT items.name, ic.name as category, count FROM accountInventory AS ai INNER JOIN items ON items.id = ai.itemId INNER JOIN itemCategories AS ic ON ic.id = items.categoryId INNER JOIN accounts ON accounts.id = ai.accountId WHERE accounts.uuid = '" + uuid + "';" - + "SELECT benefit FROM rankBenefits WHERE rankBenefits.uuid = '" + uuid + "';" - + "SELECT stats.name, value FROM accountStats INNER JOIN stats ON stats.id = accountStats.statId INNER JOIN accounts ON accountStats.accountId = accounts.id WHERE accounts.uuid = '" + uuid + "';" - + "SELECT tA.Name, status, serverName, tA.lastLogin, now() FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget LEFT JOIN playerMap ON tA.name = playerName WHERE uuidSource = '" + uuid + "';" - + "SELECT gameType, elo FROM eloRating WHERE uuid = '" + uuid + "';" - ); -*/ + // Player was not found in cache, we need to grab the account id from database + statement.execute("SELECT id FROM accounts WHERE accounts.uuid = '" + uuid + "' LIMIT 1;"); + ResultSet resultSet = statement.getResultSet(); - String loginString = "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE id = '" + accountId + "';"; - - for (ILoginProcessor loginProcessor : loginProcessors.values()) - { - loginString += loginProcessor.getQuery(accountId, uuid, name); - } - - statement.execute(loginString); - - /* - while (true) - { - if (statementStatus) + if (resultSet.next()) { - System.out.println("ResultSet : " + statement.getResultSet().getMetaData().getColumnCount() + " columns:"); - - for (int i = 0; i < statement.getResultSet().getMetaData().getColumnCount(); i++) - { - System.out.println(statement.getResultSet().getMetaData().getColumnName(i + 1)); - } + accountId = resultSet.getInt(1); } else { - if (statement.getUpdateCount() == -1) - break; + // Player doesn't exist in our database, add them to the accounts table + final List tempList = new ArrayList(1); - System.out.println("Update statement : " + statement.getUpdateCount() + " rows affected."); + executeInsert(ACCOUNT_LOGIN_NEW, new ResultSetCallable() + { + @Override + public void processResultSet(ResultSet resultSet) throws SQLException + { + while (resultSet.next()) + { + tempList.add(resultSet.getInt(1)); + } + } + }, new ColumnVarChar("uuid", 100, uuid.toString()), new ColumnVarChar("name", 100, name)); + + accountId = tempList.get(0); } - - statementStatus = statement.getMoreResults(); } - - System.out.println("Done"); - */ + else + { + System.out.println(name + " Loaded Account ID From Cache [" + name + " - " + accountId + "]"); + } + + final int finalId = accountId; + final String uuidString = uuid.toString(); + + String loginString = "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE id = '" + accountId + "';"; + // We can use a parallel stream because they will be in the correct order when we collect + loginString += loginProcessors.parallelStream().map(processor -> processor.getQuery(finalId, uuidString, name)).collect(Collectors.joining()); + + statement.execute(loginString); statement.getUpdateCount(); statement.getMoreResults(); - - for (ILoginProcessor loginProcessor : loginProcessors.values()) + + for (ILoginProcessor loginProcessor : loginProcessors) { - loginProcessor.processLoginResultSet(name, accountId, statement.getResultSet()); + loginProcessor.processLoginResultSet(name, finalId, statement.getResultSet()); statement.getMoreResults(); } - - for (IQuerylessLoginProcessor loginProcessor : querylessLoginProcessors) - { - loginProcessor.processLogin(name, accountId); - } - } - catch (Exception exception) - { - exception.printStackTrace(); } + return accountId; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/achievement/Achievement.java b/Plugins/Mineplex.Core/src/mineplex/core/achievement/Achievement.java index 2a9b7ccbf..c74d23965 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/achievement/Achievement.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/achievement/Achievement.java @@ -164,6 +164,43 @@ public enum Achievement new int[]{10}, AchievementCategory.UHC), + //MC League + MC_LEAGUE_STRIKE("First Strike", 600, + new String[] {"MC League.FirstStrike"}, + new String[] {"Earn 30 First Bloods"}, + new int[] {30}, + AchievementCategory.MC_LEAGUE), + + MC_LEAGUE_HEAD("Head Hunter", 600, + new String[] {"MC League.HeadHunter"}, + new String[] {"Grab 25 Wither Skulls"}, + new int[] {25}, + AchievementCategory.MC_LEAGUE), + + MC_LEAGUE_ALTAR("Altar Builder", 600, + new String[] {"MC League.AltarBuilder"}, + new String[] {"Place 50 Wither Skulls", "on your Altar"}, + new int[] {50}, + AchievementCategory.MC_LEAGUE), + + MC_LEAGUE_WINS("Mineplex Champion", 900, + new String[] {"MC League.Wins"}, + new String[] {"Win 25 Games"}, + new int[] {25}, + AchievementCategory.MC_LEAGUE), + + MC_LEAGUE_TOWER("Tower Defender", 800, + new String[] {"MC League.TowerDefender"}, + new String[] {"Get a double kill", "inside your Active Tower"}, + new int[] {1}, + AchievementCategory.MC_LEAGUE), + + MC_LEAGUE_SAVING("Saving Up", 900, + new String[] {"MC League.SavingUp"}, + new String[] {"Craft a Diamond Chestplate"}, + new int[] {1}, + AchievementCategory.MC_LEAGUE), + //UHC WIZARDS_WINS("Supreme Wizard", 600, new String[]{"Wizards.Wins"}, @@ -880,7 +917,7 @@ public enum Achievement new int[]{15}, AchievementCategory.GLADIATORS), - TYPE_WARS_SPEED_DEMON("Speed Demon", 1000, + /*TYPE_WARS_SPEED_DEMON("Speed Demon", 1000, new String[]{"Type Wars.Demon"}, new String[]{"Kill 5 Mobs in 8 seconds", "by typing"}, new int[]{1}, @@ -914,7 +951,7 @@ public enum Achievement new String[]{"Type Wars.Wins"}, new String[]{"Win 30 Games"}, new int[]{30}, - AchievementCategory.TYPE_WARS), + AchievementCategory.TYPE_WARS),*/ SPEED_BUILDERS_SPEED_MASTER("Speed Master", 800, new String[]{"Speed Builders.Wins"}, diff --git a/Plugins/Mineplex.Core/src/mineplex/core/achievement/AchievementCategory.java b/Plugins/Mineplex.Core/src/mineplex/core/achievement/AchievementCategory.java index 62a53af26..c4da40e41 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/achievement/AchievementCategory.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/achievement/AchievementCategory.java @@ -6,6 +6,7 @@ import mineplex.core.account.CoreClientManager; import mineplex.core.common.Rank; import mineplex.core.common.util.C; import mineplex.core.common.util.UtilTime; +import mineplex.core.game.GameCategory; import mineplex.core.game.GameDisplay; import mineplex.core.stats.PlayerStats; import mineplex.core.stats.StatsManager; @@ -48,6 +49,10 @@ public enum AchievementCategory UHC("Ultra Hardcore", null, new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED }, Material.GOLDEN_APPLE, 0, GameCategory.SURVIVAL, "None"), + + MC_LEAGUE("MC League", null, + new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED }, + Material.IRON_CHESTPLATE, 0, GameCategory.SURVIVAL, "None"), WIZARDS("Wizards", null, new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED }, @@ -159,9 +164,9 @@ public enum AchievementCategory new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED }, Material.IRON_SWORD, 0, GameCategory.ARCADE, null), - TYPE_WARS("Type Wars", null, + /*TYPE_WARS("Type Wars", null, new StatDisplay[] {StatDisplay.WINS, StatDisplay.GAMES_PLAYED, new StatDisplay("Minions killed", "MinionKills"), new StatDisplay("Words Per Minute", false, true, "MinionKills", "TimeInGame"), StatDisplay.GEMS_EARNED}, - Material.NAME_TAG, 0, GameCategory.CLASSICS, null), + Material.NAME_TAG, 0, GameCategory.CLASSICS, null),*/ SPEED_BUILDERS("Speed Builders", null, new StatDisplay[] {StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.GEMS_EARNED, null, new StatDisplay("Perfect Builds", "PerfectBuild")}, diff --git a/Plugins/Mineplex.Core/src/mineplex/core/antihack/AntiHack.java b/Plugins/Mineplex.Core/src/mineplex/core/antihack/AntiHack.java index 17c4200be..2bd3903b3 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/antihack/AntiHack.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/antihack/AntiHack.java @@ -11,6 +11,7 @@ import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.Sound; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; @@ -30,6 +31,7 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilInv; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; @@ -202,7 +204,12 @@ public class AntiHack extends MiniPlugin return true; } - if (player.isFlying() || player.isInsideVehicle() || player.getGameMode() != GameMode.SURVIVAL || UtilPlayer.isSpectator(player)) + if (player.isFlying() || ((CraftPlayer) player).getHandle().isGliding() || player.isInsideVehicle() || player.getGameMode() != GameMode.SURVIVAL || UtilPlayer.isSpectator(player)) + { + return true; + } + + if (UtilInv.IsItem(player.getInventory().getArmorContents()[2], Material.ELYTRA, (byte) 0)) { return true; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusManager.java b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusManager.java index 1dd545c93..d2a4b9b52 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusManager.java @@ -33,6 +33,7 @@ import mineplex.core.donation.GiveDonorData; import mineplex.core.facebook.FacebookManager; import mineplex.core.hologram.Hologram; import mineplex.core.hologram.HologramManager; +import mineplex.core.inventory.ClientItem; import mineplex.core.inventory.InventoryManager; import mineplex.core.npc.Npc; import mineplex.core.npc.NpcManager; @@ -72,6 +73,7 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.EntityCreeper; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata; public class BonusManager extends MiniClientPlugin implements ILoginProcessor @@ -408,7 +410,7 @@ public class BonusManager extends MiniClientPlugin implements I if (!_enabled) return; - ((CraftEntity)_carlNpc.getEntity()).getHandle().getDataWatcher().watch(16, (byte) -1); + ((CraftEntity)_carlNpc.getEntity()).getHandle().getDataWatcher().watch(16, (byte) -1, EntityCreeper.META_FUSE_STATE, -1); } public void IncreaseSize(Entity player) @@ -416,7 +418,7 @@ public class BonusManager extends MiniClientPlugin implements I if (!_enabled) return; - ((CraftEntity)_carlNpc.getEntity()).getHandle().getDataWatcher().watch(16, (byte) 1); + ((CraftEntity)_carlNpc.getEntity()).getHandle().getDataWatcher().watch(16, (byte) 1, EntityCreeper.META_FUSE_STATE, 1); } // DAILY BONUS @@ -473,6 +475,7 @@ public class BonusManager extends MiniClientPlugin implements I { if (timeTillRankBonus(player) > 0) result.run(false); + getRepository().attemptRankBonus(player, new Callback() { @Override @@ -733,20 +736,23 @@ public class BonusManager extends MiniClientPlugin implements I if (oldChests > 0) { - _inventoryManager.addItemToInventory(player, TreasureType.OLD.getItemName(), oldChests); + //_inventoryManager.addItemToInventory(player, TreasureType.OLD.getItemName(), oldChests); UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(oldChests + " Old Chests"))); + _inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.OLD.getItemName()), oldChests)); } if (ancientChests > 0) { UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(ancientChests + " Ancient Chests"))); - _inventoryManager.addItemToInventory(player, TreasureType.ANCIENT.getItemName(), ancientChests); + //_inventoryManager.addItemToInventory(player, TreasureType.ANCIENT.getItemName(), ancientChests); + _inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.ANCIENT.getItemName()), ancientChests)); } if (mythicalChests > 0) { UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(mythicalChests + " Mythical Chests"))); - _inventoryManager.addItemToInventory(player, TreasureType.MYTHICAL.getItemName(), mythicalChests); + //_inventoryManager.addItemToInventory(player, TreasureType.MYTHICAL.getItemName(), mythicalChests); + _inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.MYTHICAL.getItemName()), mythicalChests)); } if (gems > 0) @@ -758,6 +764,7 @@ public class BonusManager extends MiniClientPlugin implements I if (gold > 0) { UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold"))); + /* _donationManager.rewardGold(new Callback() { @Override @@ -772,6 +779,7 @@ public class BonusManager extends MiniClientPlugin implements I } } }, "Earned", player.getName(), coreClient.getAccountId(), gold, true); + */ } if (coins > 0) @@ -916,7 +924,7 @@ public class BonusManager extends MiniClientPlugin implements I if (client.getHologram() == null) { - double yAdd = 2.18; + double yAdd = 2.3; hologram = new Hologram(_hologramManager, _carlNpc.getLocation().clone().add(0, yAdd, 0), ""); hologram.setHologramTarget(Hologram.HologramTarget.WHITELIST); hologram.addPlayer(player); @@ -939,9 +947,9 @@ public class BonusManager extends MiniClientPlugin implements I { // Charged DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 0); - watcher.a(1, (short) 300); - watcher.a(17, (byte) 1); + watcher.a(0, (byte) 0, EntityCreeper.META_ENTITYDATA, (byte) 0); + watcher.a(1, (short) 300, EntityCreeper.META_AIR, 0); + watcher.a(17, (byte) 1, EntityCreeper.META_POWERED, true); PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(); packet.a = _carlNpc.getEntity().getEntityId(); packet.b = watcher.c(); @@ -958,7 +966,7 @@ public class BonusManager extends MiniClientPlugin implements I { // Charged DataWatcher watcher = new DataWatcher(null); - watcher.a(17, (byte) 0); + watcher.a(17, (byte) 0, EntityCreeper.META_POWERED, false); PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(); packet.a = _carlNpc.getEntity().getEntityId(); packet.b = watcher.c(); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusRepository.java index a00e6373e..594dff4e8 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/BonusRepository.java @@ -259,42 +259,48 @@ public class BonusRepository extends MinecraftRepository public void attemptRankBonus(final Player player, final Callback result) { - if (!Recharge.Instance.usable(player, "AttemptRankBonus")) { + if (!Recharge.Instance.usable(player, "AttemptRankBonus")) + { result.run(false); return; } + final int accountId = _manager.getClientManager().Get(player).getAccountId(); final int coins = _manager.getRankBonusAmount(player).getCoins(); + final int gems = _manager.getRankBonusAmount(player).getGems(); + final int mythicalChestChange = _manager.getRankBonusAmount(player).getMythicalChests(); - if (!_manager.getRankBonusAmount(player).isGreaterThanZero()) { + if (!_manager.getRankBonusAmount(player).isGreaterThanZero()) + { result.run(false); return; } final JavaPlugin plug = _manager.getPlugin(); - Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable() { - + Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable() + { @Override public void run() { - try (Connection connection = getConnection(); - CallableStatement callableStatement = connection.prepareCall("{call check_rank(?, ?, ?, ?, ?)}")) { + CallableStatement callableStatement = connection.prepareCall("{call rankBonus(?, ?, ?, ?, ?, ?)}")) + { callableStatement.setInt(1, accountId); callableStatement.setInt(2, coins); - callableStatement.setInt(3, 0); - callableStatement.registerOutParameter(4, java.sql.Types.BOOLEAN); - callableStatement.registerOutParameter(5, java.sql.Types.DATE); + callableStatement.setInt(3, gems); + callableStatement.setInt(4, mythicalChestChange); + callableStatement.registerOutParameter(5, java.sql.Types.BOOLEAN); + callableStatement.registerOutParameter(6, java.sql.Types.DATE); callableStatement.executeUpdate(); - final boolean pass = callableStatement.getBoolean(4); + final boolean pass = callableStatement.getBoolean(5); - final Date date = callableStatement.getDate(5); - - Bukkit.getScheduler().runTask(plug, new Runnable() { + final Date date = callableStatement.getDate(6); + Bukkit.getScheduler().runTask(plug, new Runnable() + { @Override public void run() { @@ -311,9 +317,12 @@ public class BonusRepository extends MinecraftRepository } } }); - } catch (Exception e) { + } + catch (Exception e) + { Recharge.Instance.use(player, "AttemptRankBonus", 1000 * 30, false, false); e.printStackTrace(); + System.out.println("Error : " + e.getMessage()); result.run(false); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/gui/buttons/RankBonusButton.java b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/gui/buttons/RankBonusButton.java index 5fe0fc0f0..1f525f36b 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/bonuses/gui/buttons/RankBonusButton.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/bonuses/gui/buttons/RankBonusButton.java @@ -153,9 +153,10 @@ public class RankBonusButton implements GuiItem, Listener { lore.add(" "); lore.add(ChatColor.WHITE + "Players with a Rank get a Monthly Bonus!"); lore.add(ChatColor.WHITE + ""); - lore.add(ChatColor.AQUA + "Ultra receives 7500 Coins Monthly"); - lore.add(ChatColor.LIGHT_PURPLE + "Hero receives 15000 Coins Monthly"); - lore.add(ChatColor.GREEN + "Legend receives 30000 Coins Monthly"); + lore.add(ChatColor.AQUA + "Ultra receives 1 Mythical Chest Monthly"); + lore.add(ChatColor.LIGHT_PURPLE + "Hero receives 2 Mythical Chests Monthly"); + lore.add(ChatColor.GREEN + "Legend receives 3 Mythical Chests Monthly"); + lore.add(ChatColor.RED + "Titan receives 5 Mythical Chests Monthly"); lore.add(ChatColor.WHITE + ""); lore.add(ChatColor.WHITE + "Purchase a Rank at;"); lore.add(ChatColor.WHITE + "www.mineplex.com/shop"); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/chat/Chat.java b/Plugins/Mineplex.Core/src/mineplex/core/chat/Chat.java index a0166d63b..fcdb2aafa 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/chat/Chat.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/chat/Chat.java @@ -7,9 +7,12 @@ import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.UUID; +import java.util.function.Function; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; @@ -18,24 +21,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import mineplex.core.MiniPlugin; -import mineplex.core.chat.command.ChatSlowCommand; -import mineplex.core.preferences.PreferencesManager; -import mineplex.core.recharge.Recharge; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.core.updater.UpdateType; -import mineplex.core.account.CoreClientManager; -import mineplex.core.achievement.AchievementManager; -import mineplex.core.chat.command.BroadcastCommand; -import mineplex.core.chat.command.SilenceCommand; -import mineplex.core.common.Rank; -import mineplex.core.common.util.C; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilText; -import mineplex.core.common.util.UtilTime; - +import org.apache.commons.lang3.Validate; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -48,11 +34,31 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; +import mineplex.core.MiniPlugin; +import mineplex.core.account.CoreClientManager; +import mineplex.core.achievement.AchievementManager; +import mineplex.core.chat.command.BroadcastCommand; +import mineplex.core.chat.command.ChatSlowCommand; +import mineplex.core.chat.command.SilenceCommand; +import mineplex.core.common.Rank; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTime; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.preferences.PreferencesManager; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + public class Chat extends MiniPlugin { private CoreClientManager _clientManager; private PreferencesManager _preferences; private AchievementManager _achievements; + private IncognitoManager _incognitoManager; private String[] _hackusations = {"hack", "hax", "hacker", "hacking", "cheat", "cheater", "cheating", "forcefield", "flyhack", "flyhacking", "autoclick", "aimbot"}; private String _filterUrl = "https://chat.mineplex.com:8003/content/item/moderate"; @@ -63,13 +69,17 @@ public class Chat extends MiniPlugin private int _chatSlow = 0; private long _silenced = 0; private boolean _threeSecondDelay = true; - + + private List> _highPriorityFilters = new ArrayList<>(); + private List> _lowPriorityFilters = new ArrayList<>(); + private HashMap _playerLastMessage = new HashMap(); - public Chat(JavaPlugin plugin, CoreClientManager clientManager, PreferencesManager preferences, AchievementManager achievements, String serverName) + public Chat(JavaPlugin plugin, IncognitoManager incognitoManager, CoreClientManager clientManager, PreferencesManager preferences, AchievementManager achievements, String serverName) { super("Chat", plugin); - + + _incognitoManager = incognitoManager; _clientManager = clientManager; _serverName = serverName; _preferences = preferences; @@ -299,7 +309,23 @@ public class Chat extends MiniPlugin return; Player sender = event.getPlayer(); - + + if (_incognitoManager != null && _incognitoManager.Get(sender).Status) + { + UtilPlayer.message(sender, C.cYellow + "You can not chat while incognito."); + event.setCancelled(true); + return; + } + + for (Function filter : _highPriorityFilters) + { + if (filter.apply(event).booleanValue()) + { + event.setCancelled(true); + return; + } + } + if (SilenceCheck(sender)) { event.setCancelled(true); @@ -346,12 +372,21 @@ public class Chat extends MiniPlugin event.setCancelled(true); } } - + if (!event.isCancelled()) _playerLastMessage.put(sender.getUniqueId(), new MessageData(event.getMessage())); + + for (Function filter : _lowPriorityFilters) + { + if (filter.apply(event).booleanValue()) + { + event.setCancelled(true); + return; + } + } } - private boolean msgContainsHack(String msg) + private boolean msgContainsHack(String msg) { msg = " " + msg.toLowerCase().replaceAll("[^a-z ]", "") + " "; for (String s : _hackusations) { @@ -596,4 +631,22 @@ public class Chat extends MiniPlugin { _threeSecondDelay = b; } + + /** + * If the function returns Boolean.TRUE then the message will be CANCELLED. + */ + public void AddFilter(Function restriction, FilterPriority priority) + { + Validate.isTrue(priority != null, "Priority must not be null."); + + switch (priority) + { + case HIGH: + _highPriorityFilters.add(restriction); + break; + case LOW: + _lowPriorityFilters.add(restriction); + } + } + } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/chat/FilterPriority.java b/Plugins/Mineplex.Core/src/mineplex/core/chat/FilterPriority.java new file mode 100644 index 000000000..71aae5059 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/chat/FilterPriority.java @@ -0,0 +1,7 @@ +package mineplex.core.chat; + +public enum FilterPriority +{ + HIGH, + LOW; +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/PetTagPage.java b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/PetTagPage.java index 05b1c2d6c..9e222aeae 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/PetTagPage.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/cosmetic/ui/page/PetTagPage.java @@ -82,6 +82,15 @@ public class PetTagPage extends ShopPageBase getShop().openPageForPlayer(getPlayer(), new PetPage(getPlugin(), getShop(), getClientManager(), getDonationManager(), "Pets", getPlayer())); return; } + + if (_tagName.equalsIgnoreCase("ULTRA")) + { + UtilPlayer.message(getPlayer(), F.main(getPlugin().getName(), ChatColor.RED + _tagName + " is a restricted name.")); + playDenySound(getPlayer()); + + getShop().openPageForPlayer(getPlayer(), new PetPage(getPlugin(), getShop(), getClientManager(), getDonationManager(), "Pets", getPlayer())); + return; + } PetExtra tag = new PetExtra("Rename " + _pet.GetName() + " to " + _tagName, Material.NAME_TAG, 100); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/delayedtask/DelayedTask.java b/Plugins/Mineplex.Core/src/mineplex/core/delayedtask/DelayedTask.java index bd02855fe..da5c6c7c0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/delayedtask/DelayedTask.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/delayedtask/DelayedTask.java @@ -62,4 +62,14 @@ public class DelayedTask extends MiniClientPlugin { return new DelayedTaskClient(Bukkit.getPlayer(player)); } + + public boolean HasTask(Player player, String task) + { + return Get(player).getStartTime(task) != -1; + } + + public boolean HasTask(String player, String task) + { + return HasTask(Bukkit.getPlayer(player), task); + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/DisguiseManager.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/DisguiseManager.java index ee25da25d..faed31632 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/DisguiseManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/DisguiseManager.java @@ -401,17 +401,17 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler disguise(disguise, true, players); } - public Packet[] getBedChunkLoadPackets(Player player, Location newLoc) + public PacketPlayOutMapChunk[] getBedChunkLoadPackets(Player player, Location newLoc) { prepareChunk(newLoc); - Packet[] packets = new Packet[2]; + PacketPlayOutMapChunk[] packets = new PacketPlayOutMapChunk[2]; // Make unload packets[0] = new PacketPlayOutMapChunk(_bedChunk, true, 0); // Make load - packets[1] = new PacketPlayOutMapChunkBulk(Arrays.asList(_bedChunk)); + packets[1] = new PacketPlayOutMapChunk(_bedChunk, true, '\uffff'); return packets; } @@ -823,7 +823,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler PacketPlayOutNamedEntitySpawn namePacket = pDisguise.spawnBeforePlayer(player.getLocation()); - namePacket.i.watch(0, (byte) 32); + namePacket.i.watch(0, (byte) 32, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 32); handlePacket(namePacket, packetVerifier); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseAgeable.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseAgeable.java index 0d52b1c38..f51230ef4 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseAgeable.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseAgeable.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityAgeable; + import org.bukkit.entity.*; public abstract class DisguiseAgeable extends DisguiseCreature @@ -8,14 +10,7 @@ public abstract class DisguiseAgeable extends DisguiseCreature { super(disguiseType, entity); - DataWatcher.a(12, new Byte((byte)0)); - } - - public void UpdateDataWatcher() - { - super.UpdateDataWatcher(); - - DataWatcher.watch(12, DataWatcher.getByte(12)); + DataWatcher.a(12, new Byte((byte)0), EntityAgeable.META_BABY, false); } public boolean isBaby() @@ -25,6 +20,6 @@ public abstract class DisguiseAgeable extends DisguiseCreature public void setBaby() { - DataWatcher.watch(12, new Byte((byte) ( -1 ))); + DataWatcher.watch(12, new Byte((byte) ( -1 )), EntityAgeable.META_BABY, true); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseArmorStand.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseArmorStand.java index 9d198e02b..520ef6ff2 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseArmorStand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseArmorStand.java @@ -2,6 +2,7 @@ package mineplex.core.disguise.disguises; import org.bukkit.util.Vector; +import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; @@ -13,12 +14,14 @@ public class DisguiseArmorStand extends DisguiseInsentient { super(entity); - DataWatcher.a(10, (byte) 0); + DataWatcher.a(10, (byte) 0, EntityArmorStand.META_ARMOR_OPTION, (byte) 0); - for (int i = 11; i < 17; i++) - { - DataWatcher.a(i, new Vector3f(0, 0, 0)); - } + DataWatcher.a(11, new Vector3f(0, 0, 0), EntityArmorStand.META_HEAD_POSE, new Vector3f(0, 0, 0)); + DataWatcher.a(12, new Vector3f(0, 0, 0), EntityArmorStand.META_BODY_POSE, new Vector3f(0, 0, 0)); + DataWatcher.a(13, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_ARM_POSE, new Vector3f(0, 0, 0)); + DataWatcher.a(14, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_ARM_POSE, new Vector3f(0, 0, 0)); + DataWatcher.a(15, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_LEG_POSE, new Vector3f(0, 0, 0)); + DataWatcher.a(16, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_LEG_POSE, new Vector3f(0, 0, 0)); // Rotations are from -360 to 360 } @@ -55,6 +58,7 @@ public class DisguiseArmorStand extends DisguiseInsentient packet.i = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); packet.j = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); packet.k = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.uuid = Entity.getUniqueID(); double var2 = 3.9D; double var4 = 0; @@ -103,51 +107,55 @@ public class DisguiseArmorStand extends DisguiseInsentient public void setBodyPosition(Vector vector) { - DataWatcher.watch(12, convert(vector)); + DataWatcher.watch(12, convert(vector), EntityArmorStand.META_BODY_POSE, convert(vector)); } public void setHasArms() { - DataWatcher.watch(10, (byte) DataWatcher.getByte(10) | 4); + DataWatcher.watch(10, (byte) (DataWatcher.getByte(10) | 4), EntityArmorStand.META_ARMOR_OPTION, + (byte) (DataWatcher.getByte(10) | 4)); } public void setHeadPosition(Vector vector) { - DataWatcher.watch(11, convert(vector)); + DataWatcher.watch(11, convert(vector), EntityArmorStand.META_HEAD_POSE, convert(vector)); } public void setLeftArmPosition(Vector vector) { - DataWatcher.watch(13, convert(vector)); + DataWatcher.watch(13, convert(vector), EntityArmorStand.META_LEFT_ARM_POSE, convert(vector)); } public void setLeftLegPosition(Vector vector) { - DataWatcher.watch(15, convert(vector)); + DataWatcher.watch(15, convert(vector), EntityArmorStand.META_LEFT_LEG_POSE, convert(vector)); } public void setRemoveBase() { - DataWatcher.watch(10, (byte) DataWatcher.getByte(10) | 8); + DataWatcher.watch(10, (byte) (DataWatcher.getByte(10) | 8), EntityArmorStand.META_ARMOR_OPTION, + (byte) (DataWatcher.getByte(10) | 8)); } public void setRightArmPosition(Vector vector) { - DataWatcher.watch(14, convert(vector)); + DataWatcher.watch(14, convert(vector), EntityArmorStand.META_RIGHT_ARM_POSE, convert(vector)); } public void setRightLegPosition(Vector vector) { - DataWatcher.watch(16, convert(vector)); + DataWatcher.watch(16, convert(vector), EntityArmorStand.META_RIGHT_LEG_POSE, convert(vector)); } public void setSmall() { - DataWatcher.watch(10, (byte) DataWatcher.getByte(10) | 1); + DataWatcher.watch(10, (byte) (DataWatcher.getByte(10) | 1), EntityArmorStand.META_ARMOR_OPTION, + (byte) (DataWatcher.getByte(10) | 1)); } public void setGravityEffected() { - DataWatcher.watch(10, (byte) DataWatcher.getByte(10) | 2); + DataWatcher.watch(10, (byte) (DataWatcher.getByte(10) | 2), EntityArmorStand.META_ARMOR_OPTION, + (byte) (DataWatcher.getByte(10) | 2)); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBase.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBase.java index 27e6fbd54..b16edaa20 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBase.java @@ -31,10 +31,10 @@ public abstract class DisguiseBase } DataWatcher = new DataWatcher(new DummyEntity(null)); - - DataWatcher.a(0, Byte.valueOf((byte)0)); - DataWatcher.a(1, Short.valueOf((short)300)); - + + DataWatcher.a(0, Byte.valueOf((byte) 0), Entity.META_ENTITYDATA, (byte) 0); + DataWatcher.a(1, Short.valueOf((short) 300), Entity.META_AIR, 300); + _soundDisguise = this; } @@ -45,8 +45,8 @@ public abstract class DisguiseBase public void UpdateDataWatcher() { - DataWatcher.watch(0, Entity.getDataWatcher().getByte(0)); - DataWatcher.watch(1, Entity.getDataWatcher().getShort(1)); + DataWatcher.watch(0, Entity.getDataWatcher().getByte(0), Entity.META_ENTITYDATA, Entity.getDataWatcher().getByte(0)); + DataWatcher.watch(1, Entity.getDataWatcher().getShort(1), Entity.META_AIR, (int) Entity.getDataWatcher().getShort(1)); } public abstract Packet GetSpawnPacket(); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBat.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBat.java index 05e41c469..b5100c880 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBat.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBat.java @@ -1,30 +1,32 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityBat; + import org.bukkit.entity.*; -public class DisguiseBat extends DisguiseAnimal +public class DisguiseBat extends DisguiseCreature { public DisguiseBat(org.bukkit.entity.Entity entity) { super(EntityType.BAT, entity); - - DataWatcher.a(16, new Byte((byte)0)); + + DataWatcher.a(16, new Byte((byte) 0), EntityBat.META_UPSIDEDOWN, (byte) 0); } - public boolean isSitting() + public boolean isSitting() { return (DataWatcher.getByte(16) & 0x1) != 0; } - public void setSitting(boolean paramBoolean) + public void setSitting(boolean paramBoolean) { int i = DataWatcher.getByte(16); if (paramBoolean) - DataWatcher.watch(16, Byte.valueOf((byte)(i | 0x1))); + DataWatcher.watch(16, Byte.valueOf((byte) (i | 0x1)), EntityBat.META_UPSIDEDOWN, (byte) (i | 0x1)); else - DataWatcher.watch(16, Byte.valueOf((byte)(i & 0xFFFFFFFE))); + DataWatcher.watch(16, Byte.valueOf((byte) (i & 0xFFFFFFFE)), EntityBat.META_UPSIDEDOWN, (byte) (i & 0xFFFFFFFE)); } - + public String getHurtSound() { return "mob.bat.hurt"; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlaze.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlaze.java index 19e57b290..c0d782982 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlaze.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlaze.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityBlaze; + import org.bukkit.entity.*; public class DisguiseBlaze extends DisguiseMonster @@ -7,27 +9,27 @@ public class DisguiseBlaze extends DisguiseMonster public DisguiseBlaze(org.bukkit.entity.Entity entity) { super(EntityType.BLAZE, entity); - - DataWatcher.a(16, new Byte((byte)0)); + + DataWatcher.a(16, new Byte((byte) 0), EntityBlaze.META_FIRE, (byte) 0); } - + public boolean bT() { return (DataWatcher.getByte(16) & 0x01) != 0; } - + public void a(boolean flag) { byte b0 = DataWatcher.getByte(16); - + if (flag) - b0 = (byte)(b0 | 0x1); + b0 = (byte) (b0 | 0x1); else - b0 = (byte)(b0 | 0xFFFFFFFE); - - DataWatcher.watch(16, Byte.valueOf(b0)); + b0 = (byte) (b0 | 0xFFFFFFFE); + + DataWatcher.watch(16, Byte.valueOf(b0), EntityBlaze.META_FIRE, b0); } - + public String getHurtSound() { return "mob.blaze.hit"; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlock.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlock.java index 9e90deaf4..f0406a88e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlock.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseBlock.java @@ -9,26 +9,26 @@ import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntity; public class DisguiseBlock extends DisguiseBase { private static Random _random = new Random(); - + private int _blockId; private int _blockData; - + public DisguiseBlock(org.bukkit.entity.Entity entity, int blockId, int blockData) { super(entity); - + _blockId = blockId; _blockData = blockData; } - + public int GetBlockId() { return _blockId; } - + public byte GetBlockData() { - return (byte)_blockData; + return (byte) _blockData; } @Override @@ -43,38 +43,45 @@ public class DisguiseBlock extends DisguiseBase packet.i = MathHelper.d(Entity.yaw * 256.0F / 360.0F); packet.j = 70; packet.k = _blockId | _blockData << 12; + packet.uuid = Entity.getUniqueID(); double d1 = Entity.motX; double d2 = Entity.motY; double d3 = Entity.motZ; double d4 = 3.9D; - - if (d1 < -d4) d1 = -d4; - if (d2 < -d4) d2 = -d4; - if (d3 < -d4) d3 = -d4; - if (d1 > d4) d1 = d4; - if (d2 > d4) d2 = d4; - if (d3 > d4) d3 = d4; - - packet.e = ((int)(d1 * 8000.0D)); - packet.f = ((int)(d2 * 8000.0D)); - packet.g = ((int)(d3 * 8000.0D)); + + if (d1 < -d4) + d1 = -d4; + if (d2 < -d4) + d2 = -d4; + if (d3 < -d4) + d3 = -d4; + if (d1 > d4) + d1 = d4; + if (d2 > d4) + d2 = d4; + if (d3 > d4) + d3 = d4; + + packet.e = ((int) (d1 * 8000.0D)); + packet.f = ((int) (d2 * 8000.0D)); + packet.g = ((int) (d3 * 8000.0D)); return packet; } - protected String getHurtSound() - { - return "damage.hit"; - } - - protected float getVolume() - { - return 1.0F; - } + protected String getHurtSound() + { + return "damage.hit"; + } - protected float getPitch() - { - return (_random.nextFloat() - _random.nextFloat()) * 0.2F + 1.0F; - } + protected float getVolume() + { + return 1.0F; + } + + protected float getPitch() + { + return (_random.nextFloat() - _random.nextFloat()) * 0.2F + 1.0F; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCat.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCat.java index e21a4ffc8..621d77259 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCat.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCat.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityOcelot; + import org.bukkit.entity.*; public class DisguiseCat extends DisguiseTameableAnimal @@ -8,21 +10,21 @@ public class DisguiseCat extends DisguiseTameableAnimal { super(EntityType.OCELOT, entity); - DataWatcher.a(18, Byte.valueOf((byte)0)); + DataWatcher.a(18, Byte.valueOf((byte) 0), EntityOcelot.META_TYPE, 0); } - + public int getCatType() { return DataWatcher.getByte(18); } - public void setCatType(int i) + public void setCatType(int i) { - DataWatcher.watch(18, Byte.valueOf((byte)i)); + DataWatcher.watch(18, Byte.valueOf((byte) i), EntityOcelot.META_TYPE, i); + } + + protected String getHurtSound() + { + return "mob.cat.hitt"; } - - protected String getHurtSound() - { - return "mob.cat.hitt"; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCaveSpider.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCaveSpider.java index abda09d1c..530f69a5c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCaveSpider.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCaveSpider.java @@ -2,6 +2,8 @@ package mineplex.core.disguise.disguises; import org.bukkit.entity.EntityType; +import net.minecraft.server.v1_8_R3.EntitySpider; + public class DisguiseCaveSpider extends DisguiseMonster { @@ -9,7 +11,7 @@ public class DisguiseCaveSpider extends DisguiseMonster { super(EntityType.CAVE_SPIDER, entity); - DataWatcher.a(16, new Byte((byte) 0)); + DataWatcher.a(16, new Byte((byte) 0), EntitySpider.META_CLIMBING, (byte) 0); } public boolean bT() @@ -26,7 +28,7 @@ public class DisguiseCaveSpider extends DisguiseMonster else b0 = (byte) (b0 & 0xFFFFFFFE); - DataWatcher.watch(16, Byte.valueOf(b0)); + DataWatcher.watch(16, Byte.valueOf(b0), EntitySpider.META_CLIMBING, b0); } protected String getHurtSound() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreature.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreature.java index 93a693ec0..a1db97615 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreature.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreature.java @@ -33,6 +33,7 @@ public abstract class DisguiseCreature extends DisguiseInsentient packet.i = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); packet.j = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); packet.k = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.uuid = Entity.getUniqueID(); double var2 = 3.9D; double var4 = 0; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreeper.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreeper.java index 2eaf7b2ef..6d1eeb73b 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreeper.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseCreeper.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityCreeper; + import org.bukkit.entity.*; public class DisguiseCreeper extends DisguiseMonster @@ -7,33 +9,33 @@ public class DisguiseCreeper extends DisguiseMonster public DisguiseCreeper(org.bukkit.entity.Entity entity) { super(EntityType.CREEPER, entity); - - DataWatcher.a(16, Byte.valueOf((byte)-1)); - DataWatcher.a(17, Byte.valueOf((byte)0)); + + DataWatcher.a(16, Byte.valueOf((byte) -1), EntityCreeper.META_FUSE_STATE, -1); + DataWatcher.a(17, Byte.valueOf((byte) 0), EntityCreeper.META_POWERED, false); } - + public boolean IsPowered() { return DataWatcher.getByte(17) == 1; } - + public void SetPowered(boolean powered) { - DataWatcher.watch(17, Byte.valueOf((byte)(powered ? 1 : 0))); + DataWatcher.watch(17, Byte.valueOf((byte) (powered ? 1 : 0)), EntityCreeper.META_POWERED, powered); } - + public int bV() { return DataWatcher.getByte(16); } - + public void a(int i) { - DataWatcher.watch(16, Byte.valueOf((byte)i)); + DataWatcher.watch(16, Byte.valueOf((byte) i), EntityCreeper.META_FUSE_STATE, i); + } + + protected String getHurtSound() + { + return "mob.creeper.say"; } - - protected String getHurtSound() - { - return "mob.creeper.say"; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseEnderman.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseEnderman.java index d752c1698..55964abc2 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseEnderman.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseEnderman.java @@ -2,50 +2,71 @@ package mineplex.core.disguise.disguises; import java.util.Arrays; +import net.minecraft.server.v1_8_R3.Block; +import net.minecraft.server.v1_8_R3.Blocks; +import net.minecraft.server.v1_8_R3.EntityEnderman; +import net.minecraft.server.v1_8_R3.EntityLiving; +import net.minecraft.server.v1_8_R3.IBlockData; import net.minecraft.server.v1_8_R3.MobEffect; import net.minecraft.server.v1_8_R3.MobEffectList; import net.minecraft.server.v1_8_R3.PotionBrewer; import org.bukkit.entity.*; +import com.google.common.base.Optional; + public class DisguiseEnderman extends DisguiseMonster { public DisguiseEnderman(org.bukkit.entity.Entity entity) { super(EntityType.ENDERMAN, entity); - - DataWatcher.a(16, new Short( (short) 0)); - DataWatcher.a(17, new Byte( (byte) 0)); - DataWatcher.a(18, new Byte( (byte) 0)); - - int i = PotionBrewer.a(Arrays.asList(new MobEffect(MobEffectList.FIRE_RESISTANCE.id, 777))); - DataWatcher.watch(8, Byte.valueOf((byte)(PotionBrewer.b(Arrays.asList(new MobEffect(MobEffectList.FIRE_RESISTANCE.id, 777))) ? 1 : 0))); - DataWatcher.watch(7, Integer.valueOf(i)); + + DataWatcher.a(16, new Short((short) 0), EntityEnderman.META_BLOCK, Optional. absent()); + DataWatcher.a(17, new Byte((byte) 0), EntityEnderman.META_BLOCK, Optional. absent()); + DataWatcher.a(18, new Byte((byte) 0), EntityEnderman.META_ANGRY, false); + + int i = PotionBrewer.a(Arrays.asList(new MobEffect(MobEffectList.FIRE_RESISTANCE.id, 777))); + DataWatcher.watch(8, Byte.valueOf((byte) (PotionBrewer.b(Arrays.asList(new MobEffect(MobEffectList.FIRE_RESISTANCE.id, + 777))) ? 1 : 0)), EntityLiving.META_AMBIENT_POTION, PotionBrewer.b(Arrays.asList(new MobEffect( + MobEffectList.FIRE_RESISTANCE.id, 777)))); + DataWatcher.watch(7, Integer.valueOf(i), EntityLiving.META_POTION_COLOR, i); } public void UpdateDataWatcher() { super.UpdateDataWatcher(); - DataWatcher.watch(0, Byte.valueOf((byte)(DataWatcher.getByte(0) & ~(1 << 0)))); - DataWatcher.watch(16, DataWatcher.getShort(16)); + DataWatcher.watch(0, Byte.valueOf((byte) (DataWatcher.getByte(0) & ~(1 << 0))), Entity.META_ENTITYDATA, + (byte) (DataWatcher.getByte(0) & ~(1 << 0))); + DataWatcher.watch(16, DataWatcher.getShort(16), EntityEnderman.META_BLOCK, getBlock(DataWatcher.getShort(16))); } - + + private Optional getBlock(int i) + { + Block b = Block.getById(i); + if (b != null && b != Blocks.AIR) + { + return Optional.fromNullable(b.getBlockData()); + } + + return Optional.fromNullable(null); + } + public void SetCarriedId(int i) { - DataWatcher.watch(16, new Short( (short)(i & 0xFF)) ); + DataWatcher.watch(16, new Short((short) (i & 0xFF)), EntityEnderman.META_BLOCK, getBlock(i)); } - + public int GetCarriedId() { return DataWatcher.getByte(16); } - + public void SetCarriedData(int i) { - DataWatcher.watch(17, Byte.valueOf((byte)(i & 0xFF))); + DataWatcher.watch(17, Byte.valueOf((byte) (i & 0xFF)), EntityEnderman.META_BLOCK, getBlock(0)); } - + public int GetCarriedData() { return DataWatcher.getByte(17); @@ -55,14 +76,14 @@ public class DisguiseEnderman extends DisguiseMonster { return DataWatcher.getByte(18) > 0; } - + public void a(boolean flag) { - DataWatcher.watch(18, Byte.valueOf((byte)(flag ? 1 : 0))); + DataWatcher.watch(18, Byte.valueOf((byte) (flag ? 1 : 0)), EntityEnderman.META_ANGRY, flag); + } + + protected String getHurtSound() + { + return "mob.endermen.hit"; } - - protected String getHurtSound() - { - return "mob.endermen.hit"; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseGuardian.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseGuardian.java index bd2ced0fd..af05e67bb 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseGuardian.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseGuardian.java @@ -2,23 +2,25 @@ package mineplex.core.disguise.disguises; import org.bukkit.entity.*; +import net.minecraft.server.v1_8_R3.EntityGuardian; + public class DisguiseGuardian extends DisguiseCreature { public DisguiseGuardian(org.bukkit.entity.Entity entity) { super(EntityType.GUARDIAN, entity); - DataWatcher.a(16, 0); - DataWatcher.a(17, 0); + DataWatcher.a(16, 0, EntityGuardian.META_ELDER, (byte) 0); + DataWatcher.a(17, 0, EntityGuardian.META_TARGET, 0); } public void setTarget(int target) { - DataWatcher.watch(17, target); + DataWatcher.watch(17, target, EntityGuardian.META_TARGET, target); } public void setElder(boolean elder) { - DataWatcher.watch(16, Integer.valueOf(DataWatcher.getInt(16) | 4)); + DataWatcher.watch(16, Integer.valueOf(DataWatcher.getInt(16) | 4), EntityGuardian.META_ELDER, (byte) (DataWatcher.getInt(16) | 4)); } public boolean isElder() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHorse.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHorse.java index a5526300d..cbd7ee097 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHorse.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHorse.java @@ -1,23 +1,29 @@ package mineplex.core.disguise.disguises; +import java.util.UUID; + +import net.minecraft.server.v1_8_R3.EntityHorse; + import org.bukkit.entity.*; +import com.google.common.base.Optional; + public class DisguiseHorse extends DisguiseAnimal { public DisguiseHorse(org.bukkit.entity.Entity entity) { super(EntityType.HORSE, entity); - DataWatcher.a(16, Integer.valueOf(0)); - DataWatcher.a(19, Byte.valueOf((byte) 0)); - DataWatcher.a(20, Integer.valueOf(0)); - DataWatcher.a(21, String.valueOf("")); - DataWatcher.a(22, Integer.valueOf(0)); + DataWatcher.a(16, Integer.valueOf(0), EntityHorse.META_HORSE_STATE, (byte) 0); + DataWatcher.a(19, Byte.valueOf((byte) 0), EntityHorse.META_TYPE, 0); + DataWatcher.a(20, Integer.valueOf(0), EntityHorse.META_VARIANT, 0); + DataWatcher.a(21, String.valueOf(""), EntityHorse.META_OWNER, Optional. absent()); + DataWatcher.a(22, Integer.valueOf(0), EntityHorse.META_ARMOR, 0); } public void setType(Horse.Variant horseType) { - DataWatcher.watch(19, Byte.valueOf((byte) horseType.ordinal())); + DataWatcher.watch(19, Byte.valueOf((byte) horseType.ordinal()), EntityHorse.META_TYPE, horseType.ordinal()); } public Horse.Variant getType() @@ -27,7 +33,7 @@ public class DisguiseHorse extends DisguiseAnimal public void setVariant(Horse.Color color) { - DataWatcher.watch(20, Integer.valueOf(color.ordinal())); + DataWatcher.watch(20, Integer.valueOf(color.ordinal()), EntityHorse.META_VARIANT, color.ordinal()); } public Horse.Color getVariant() @@ -35,49 +41,35 @@ public class DisguiseHorse extends DisguiseAnimal return Horse.Color.values()[DataWatcher.getInt(20)]; } - private boolean w(int i) - { - return (DataWatcher.getInt(16) & i) != 0; - } - public void kick() { - b(32, false); - b(64, true); + b(32, false); + b(64, true); } - + public void stopKick() { - b(64, false); + b(64, false); } - + private void b(int i, boolean flag) { int j = DataWatcher.getInt(16); if (flag) - DataWatcher.watch(16, Integer.valueOf(j | i)); + DataWatcher.watch(16, Integer.valueOf(j | i), EntityHorse.META_HORSE_STATE, (byte) (j | i)); else - DataWatcher.watch(16, Integer.valueOf(j & (i ^ 0xFFFFFFFF))); + DataWatcher.watch(16, Integer.valueOf(j & (i ^ 0xFFFFFFFF)), EntityHorse.META_HORSE_STATE, + (byte) (j & (i ^ 0xFFFFFFFF))); } - public String getOwnerName() - { - return DataWatcher.getString(21); - } - - public void setOwnerName(String s) - { - DataWatcher.watch(21, s); - } - - public int cf() + public int getArmor() { return DataWatcher.getInt(22); } - public void r(int i) + public void setArmor(int i) { - DataWatcher.watch(22, Integer.valueOf(i)); + DataWatcher.watch(22, Integer.valueOf(i), EntityHorse.META_ARMOR, i); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHuman.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHuman.java index e2faae19d..6ef6f1cf1 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHuman.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseHuman.java @@ -1,14 +1,16 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityHuman; + public abstract class DisguiseHuman extends DisguiseLiving { public DisguiseHuman(org.bukkit.entity.Entity entity) { super(entity); - - DataWatcher.a(10, (byte) 0); // todo - DataWatcher.a(16, (byte) 0); - DataWatcher.a(17, Float.valueOf(0.0F)); - DataWatcher.a(18, Integer.valueOf(0)); + + DataWatcher.a(10, (byte) 0, EntityHuman.META_SKIN, (byte) 0); // todo + DataWatcher.a(16, (byte) 1, EntityHuman.META_CAPE, (byte) 1); + DataWatcher.a(17, Float.valueOf(0.0F), EntityHuman.META_SCALED_HEALTH, 0f); + DataWatcher.a(18, Integer.valueOf(0), EntityHuman.META_SCORE, 0); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseInsentient.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseInsentient.java index 3e068439a..349073a17 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseInsentient.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseInsentient.java @@ -1,25 +1,27 @@ package mineplex.core.disguise.disguises; import mineplex.core.common.*; +import net.minecraft.server.v1_8_R3.EntityInsentient; + import org.bukkit.*; public abstract class DisguiseInsentient extends DisguiseLiving { - private boolean _showArmor; - + private boolean _showArmor; + public DisguiseInsentient(org.bukkit.entity.Entity entity) { super(entity); - DataWatcher.a(3, Byte.valueOf((byte) 0)); - DataWatcher.a(2, ""); + DataWatcher.a(3, Byte.valueOf((byte) 0), EntityInsentient.META_CUSTOMNAME_VISIBLE, false); + DataWatcher.a(2, "", EntityInsentient.META_CUSTOMNAME, ""); } - + public void setName(String name) { setName(name, null); } - + public void setName(String name, Rank rank) { if (rank != null) @@ -30,35 +32,34 @@ public abstract class DisguiseInsentient extends DisguiseLiving } } - DataWatcher.watch(2, name); + DataWatcher.watch(2, name, EntityInsentient.META_CUSTOMNAME, name); } - public boolean hasCustomName() { return DataWatcher.getString(2).length() > 0; } - + public void setCustomNameVisible(boolean visible) { - DataWatcher.watch(3, Byte.valueOf((byte)(visible ? 1 : 0))); + DataWatcher.watch(3, Byte.valueOf((byte) (visible ? 1 : 0)), EntityInsentient.META_CUSTOMNAME_VISIBLE, visible); } - + public boolean getCustomNameVisible() { return DataWatcher.getByte(11) == 1; } - + public boolean armorVisible() { return _showArmor; } - + public void showArmor() { _showArmor = true; } - + public void hideArmor() { _showArmor = false; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseIronGolem.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseIronGolem.java index e063ef70b..0e487c7e7 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseIronGolem.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseIronGolem.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityIronGolem; + import org.bukkit.entity.*; public class DisguiseIronGolem extends DisguiseGolem @@ -8,26 +10,27 @@ public class DisguiseIronGolem extends DisguiseGolem { super(EntityType.IRON_GOLEM, entity); - DataWatcher.a(16, Byte.valueOf((byte)0)); - } - - public boolean bW() - { - return (DataWatcher.getByte(16) & 0x1) != 0; + DataWatcher.a(16, Byte.valueOf((byte) 0), EntityIronGolem.META_PLAYER_CREATED, (byte) 0); } - public void setPlayerCreated(boolean flag) + public boolean bW() + { + return (DataWatcher.getByte(16) & 0x1) != 0; + } + + public void setPlayerCreated(boolean flag) { byte b0 = DataWatcher.getByte(16); - + if (flag) - DataWatcher.watch(16, Byte.valueOf((byte)(b0 | 0x1))); + DataWatcher.watch(16, Byte.valueOf((byte) (b0 | 0x1)), EntityIronGolem.META_PLAYER_CREATED, (byte) (b0 | 0x1)); else - DataWatcher.watch(16, Byte.valueOf((byte)(b0 & 0xFFFFFFFE))); + DataWatcher.watch(16, Byte.valueOf((byte) (b0 & 0xFFFFFFFE)), EntityIronGolem.META_PLAYER_CREATED, + (byte) (b0 & 0xFFFFFFFE)); + } + + protected String getHurtSound() + { + return "mob.irongolem.hit"; } - - protected String getHurtSound() - { - return "mob.irongolem.hit"; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseLiving.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseLiving.java index 8c1136eac..0f426bf2d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseLiving.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseLiving.java @@ -21,10 +21,10 @@ public abstract class DisguiseLiving extends DisguiseBase { super(entity); - DataWatcher.a(6, Float.valueOf(1.0F)); - DataWatcher.a(7, Integer.valueOf(0)); - DataWatcher.a(8, Byte.valueOf((byte) 0)); - DataWatcher.a(9, Byte.valueOf((byte) 0)); + DataWatcher.a(6, Float.valueOf(1.0F), EntityLiving.META_HEALTH, 1F); + DataWatcher.a(7, Integer.valueOf(0), EntityLiving.META_POTION_COLOR, 0); + DataWatcher.a(8, Byte.valueOf((byte) 0), EntityLiving.META_AMBIENT_POTION, false); + DataWatcher.a(9, Byte.valueOf((byte) 0), EntityLiving.META_ARROWS, 0); } public ItemStack[] getEquipment() @@ -106,16 +106,20 @@ public abstract class DisguiseLiving extends DisguiseBase byte b0 = DataWatcher.getByte(0); if (_invisible) - DataWatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << 5))); + DataWatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << 5)), EntityLiving.META_ENTITYDATA, (byte) (b0 | 1 << 5)); else - DataWatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << 5)))); + DataWatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << 5))), EntityLiving.META_ENTITYDATA, (byte) (b0 & ~(1 << 5))); if (Entity instanceof EntityLiving) { - DataWatcher.watch(6, Entity.getDataWatcher().getFloat(6)); - DataWatcher.watch(7, Entity.getDataWatcher().getInt(7)); - DataWatcher.watch(8, Entity.getDataWatcher().getByte(8)); - DataWatcher.watch(9, Entity.getDataWatcher().getByte(9)); + DataWatcher.watch(6, Entity.getDataWatcher().getFloat(6), EntityLiving.META_HEALTH, + Entity.getDataWatcher().getFloat(6)); + DataWatcher.watch(7, Entity.getDataWatcher().getInt(7), EntityLiving.META_POTION_COLOR, Entity.getDataWatcher() + .getInt(7)); + DataWatcher.watch(8, Entity.getDataWatcher().getByte(8), EntityLiving.META_AMBIENT_POTION, Entity.getDataWatcher() + .getByte(8) == 1); + DataWatcher.watch(9, Entity.getDataWatcher().getByte(9), EntityLiving.META_ARROWS, (int) Entity.getDataWatcher() + .getByte(9)); } } @@ -146,7 +150,7 @@ public abstract class DisguiseLiving extends DisguiseBase public void setHealth(float health) { - DataWatcher.watch(6, Float.valueOf(health)); + DataWatcher.watch(6, Float.valueOf(health), EntityLiving.META_HEALTH, health); } public float getHealth() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseMagmaCube.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseMagmaCube.java index c5a50d924..3bbd587b7 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseMagmaCube.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseMagmaCube.java @@ -1,5 +1,6 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntitySlime; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; @@ -10,14 +11,14 @@ public class DisguiseMagmaCube extends DisguiseInsentient { super(entity); - DataWatcher.a(16, new Byte((byte)1)); + DataWatcher.a(16, new Byte((byte) 1), EntitySlime.META_SIZE, 1); } - + public void SetSize(int i) { - DataWatcher.watch(16, new Byte((byte)i)); + DataWatcher.watch(16, new Byte((byte) i), EntitySlime.META_SIZE, i); } - + public int GetSize() { return DataWatcher.getByte(16); @@ -28,65 +29,66 @@ public class DisguiseMagmaCube extends DisguiseInsentient PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(); packet.a = Entity.getId(); packet.b = (byte) 62; - packet.c = (int)MathHelper.floor(Entity.locX * 32D); - packet.d = (int)MathHelper.floor(Entity.locY * 32.0D); - packet.e = (int)MathHelper.floor(Entity.locZ * 32D); + packet.c = (int) MathHelper.floor(Entity.locX * 32D); + packet.d = (int) MathHelper.floor(Entity.locY * 32.0D); + packet.e = (int) MathHelper.floor(Entity.locZ * 32D); packet.i = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); packet.j = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); packet.k = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.uuid = Entity.getUniqueID(); - double var2 = 3.9D; - double var4 = 0; - double var6 = 0; - double var8 = 0; + double var2 = 3.9D; + double var4 = 0; + double var6 = 0; + double var8 = 0; - if (var4 < -var2) - { - var4 = -var2; - } + if (var4 < -var2) + { + var4 = -var2; + } - if (var6 < -var2) - { - var6 = -var2; - } + if (var6 < -var2) + { + var6 = -var2; + } - if (var8 < -var2) - { - var8 = -var2; - } + if (var8 < -var2) + { + var8 = -var2; + } - if (var4 > var2) - { - var4 = var2; - } + if (var4 > var2) + { + var4 = var2; + } - if (var6 > var2) - { - var6 = var2; - } + if (var6 > var2) + { + var6 = var2; + } - if (var8 > var2) - { - var8 = var2; - } + if (var8 > var2) + { + var8 = var2; + } + + packet.f = (int) (var4 * 8000.0D); + packet.g = (int) (var6 * 8000.0D); + packet.h = (int) (var8 * 8000.0D); + + packet.l = DataWatcher; + packet.m = DataWatcher.b(); - packet.f = (int)(var4 * 8000.0D); - packet.g = (int)(var6 * 8000.0D); - packet.h = (int)(var8 * 8000.0D); - - packet.l = DataWatcher; - packet.m = DataWatcher.b(); - return packet; } - - protected String getHurtSound() - { - return "mob.slime." + (GetSize() > 1 ? "big" : "small"); - } - - protected float getVolume() - { - return 0.4F * (float)GetSize(); - } + + protected String getHurtSound() + { + return "mob.slime." + (GetSize() > 1 ? "big" : "small"); + } + + protected float getVolume() + { + return 0.4F * (float) GetSize(); + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguisePlayer.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguisePlayer.java index d81a3086e..674c566d0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguisePlayer.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguisePlayer.java @@ -8,6 +8,7 @@ import org.bukkit.block.BlockFace; import com.mojang.authlib.GameProfile; import mineplex.core.common.skin.SkinData; +import net.minecraft.server.v1_8_R3.EntityHuman; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutNamedEntitySpawn; @@ -17,31 +18,31 @@ import net.minecraft.server.v1_8_R3.WorldSettings; public class DisguisePlayer extends DisguiseHuman { - private GameProfile _profile; - private boolean _sneaking; - private BlockFace _sleeping; + private GameProfile _profile; + private boolean _sneaking; + private BlockFace _sleeping; private boolean _sendSkinToSelf; - public DisguisePlayer(org.bukkit.entity.Entity entity) - { - super(entity); - } + public DisguisePlayer(org.bukkit.entity.Entity entity) + { + super(entity); + } - public DisguisePlayer(org.bukkit.entity.Entity entity, GameProfile profile) - { - this(entity); + public DisguisePlayer(org.bukkit.entity.Entity entity, GameProfile profile) + { + this(entity); - setProfile(profile); - } + setProfile(profile); + } - public void setProfile(GameProfile profile) - { - GameProfile newProfile = new GameProfile(UUID.randomUUID(), profile.getName()); + public void setProfile(GameProfile profile) + { + GameProfile newProfile = new GameProfile(UUID.randomUUID(), profile.getName()); - newProfile.getProperties().putAll(profile.getProperties()); + newProfile.getProperties().putAll(profile.getProperties()); - _profile = newProfile; - } + _profile = newProfile; + } public GameProfile getProfile() { @@ -66,28 +67,28 @@ public class DisguisePlayer extends DisguiseHuman return _sendSkinToSelf; } - public BlockFace getSleepingDirection() - { - return _sleeping; - } + public BlockFace getSleepingDirection() + { + return _sleeping; + } - /** - * Don't use this if the disguise is already on as it will not work the way - * you want it to. Contact libraryaddict if you need that added. - */ - public void setSleeping(BlockFace sleeping) - { - _sleeping = sleeping; - } + /** + * Don't use this if the disguise is already on as it will not work the way you want it to. Contact libraryaddict if you need + * that added. + */ + public void setSleeping(BlockFace sleeping) + { + _sleeping = sleeping; + } - public void setSneaking(boolean sneaking) - { - _sneaking = sneaking; - } - - public boolean getSneaking() - { - return _sneaking; + public void setSneaking(boolean sneaking) + { + _sneaking = sneaking; + } + + public boolean getSneaking() + { + return _sneaking; } public Packet getNewInfoPacket(boolean add) @@ -103,56 +104,55 @@ public class DisguisePlayer extends DisguiseHuman return newDisguiseInfo; } - @Override - public void UpdateDataWatcher() - { - super.UpdateDataWatcher(); + @Override + public void UpdateDataWatcher() + { + super.UpdateDataWatcher(); - byte b0 = DataWatcher.getByte(0); - DataWatcher.watch(10, (Object)(byte)0x40); - - if(_sneaking) - DataWatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << 1))); - else - DataWatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << 1)))); - } + byte b0 = DataWatcher.getByte(0); - public PacketPlayOutNamedEntitySpawn spawnBeforePlayer(Location spawnLocation) - { - Location loc = spawnLocation.add(spawnLocation.getDirection().normalize().multiply(30)); - loc.setY(Math.max(loc.getY(), 0)); + if (_sneaking) + DataWatcher.watch(0, Byte.valueOf((byte) (b0 | 1 << 1)), EntityHuman.META_ENTITYDATA, (byte) (b0 | 1 << 1)); + else + DataWatcher.watch(0, Byte.valueOf((byte) (b0 & ~(1 << 1))), EntityHuman.META_ENTITYDATA, (byte) (b0 & ~(1 << 1))); + } - PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn(); - packet.a = Entity.getId(); - packet.b = _profile.getId(); - packet.c = MathHelper.floor(loc.getX() * 32.0D); - packet.d = MathHelper.floor(loc.getY() * 32.0D); - packet.e = MathHelper.floor(loc.getZ() * 32.0D); - packet.f = (byte) ((int) (loc.getYaw() * 256.0F / 360.0F)); - packet.g = (byte) ((int) (loc.getPitch() * 256.0F / 360.0F)); - packet.i = DataWatcher; + public PacketPlayOutNamedEntitySpawn spawnBeforePlayer(Location spawnLocation) + { + Location loc = spawnLocation.add(spawnLocation.getDirection().normalize().multiply(30)); + loc.setY(Math.max(loc.getY(), 0)); - return packet; - } + PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn(); + packet.a = Entity.getId(); + packet.b = _profile.getId(); + packet.c = MathHelper.floor(loc.getX() * 32.0D); + packet.d = MathHelper.floor(loc.getY() * 32.0D); + packet.e = MathHelper.floor(loc.getZ() * 32.0D); + packet.f = (byte) ((int) (loc.getYaw() * 256.0F / 360.0F)); + packet.g = (byte) ((int) (loc.getPitch() * 256.0F / 360.0F)); + packet.i = DataWatcher; - @Override - public PacketPlayOutNamedEntitySpawn GetSpawnPacket() - { - PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn(); - packet.a = Entity.getId(); - packet.b = _profile.getId(); - packet.c = MathHelper.floor(Entity.locX * 32.0D); - packet.d = MathHelper.floor(Entity.locY * 32.0D); - packet.e = MathHelper.floor(Entity.locZ * 32.0D); - packet.f = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); - packet.g = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); - packet.i = DataWatcher; + return packet; + } - return packet; - } + @Override + public PacketPlayOutNamedEntitySpawn GetSpawnPacket() + { + PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn(); + packet.a = Entity.getId(); + packet.b = _profile.getId(); + packet.c = MathHelper.floor(Entity.locX * 32.0D); + packet.d = MathHelper.floor(Entity.locY * 32.0D); + packet.e = MathHelper.floor(Entity.locZ * 32.0D); + packet.f = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.g = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); + packet.i = DataWatcher; - public String getName() - { - return _profile.getName(); - } + return packet; + } + + public String getName() + { + return _profile.getName(); + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseRabbit.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseRabbit.java index 95b70ce50..426949661 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseRabbit.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseRabbit.java @@ -1,21 +1,20 @@ package mineplex.core.disguise.disguises; +import org.bukkit.entity.EntityType; + +import net.minecraft.server.v1_8_R3.EntityRabbit; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; -public class DisguiseRabbit extends DisguiseInsentient +public class DisguiseRabbit extends DisguiseAnimal { public DisguiseRabbit(org.bukkit.entity.Entity entity) { - super(entity); + super(EntityType.RABBIT, entity); - DataWatcher.a(4, Byte.valueOf((byte) 0)); - - DataWatcher.a(12, (byte) 0); - DataWatcher.a(15, Byte.valueOf((byte) 0)); - DataWatcher.a(18, Byte.valueOf((byte) 0)); + DataWatcher.a(18, Byte.valueOf((byte) 0), EntityRabbit.META_TYPE, 0); } @Override @@ -30,6 +29,7 @@ public class DisguiseRabbit extends DisguiseInsentient packet.i = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); packet.j = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); packet.k = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.uuid = Entity.getUniqueID(); double var2 = 3.9D; double var4 = 0; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSheep.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSheep.java index 21d6fffaa..83e32ad0a 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSheep.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSheep.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntitySheep; + import org.bukkit.DyeColor; import org.bukkit.entity.*; @@ -9,34 +11,35 @@ public class DisguiseSheep extends DisguiseAnimal { super(EntityType.SHEEP, entity); - DataWatcher.a(16, new Byte((byte)0)); + DataWatcher.a(16, new Byte((byte) 0), EntitySheep.META_WOOL_STATE, (byte) 0); } - + public boolean isSheared() { return (DataWatcher.getByte(16) & 16) != 0; } - + public void setSheared(boolean sheared) { - byte b0 = DataWatcher.getByte(16); + byte b0 = DataWatcher.getByte(16); - if (sheared) - DataWatcher.watch(16, Byte.valueOf((byte)(b0 | 16))); - else - DataWatcher.watch(16, Byte.valueOf((byte)(b0 & -17))); + if (sheared) + DataWatcher.watch(16, Byte.valueOf((byte) (b0 | 16)), EntitySheep.META_WOOL_STATE, (byte) (b0 | 16)); + else + DataWatcher.watch(16, Byte.valueOf((byte) (b0 & -17)), EntitySheep.META_WOOL_STATE, (byte) (b0 & -17)); } - - public int getColor() + + public int getColor() { - return DataWatcher.getByte(16) & 15; + return DataWatcher.getByte(16) & 15; } - + @SuppressWarnings("deprecation") - public void setColor(DyeColor color) + public void setColor(DyeColor color) { - byte b0 = DataWatcher.getByte(16); + byte b0 = DataWatcher.getByte(16); - DataWatcher.watch(16, Byte.valueOf((byte)(b0 & 240 | color.getWoolData() & 15))); + DataWatcher.watch(16, Byte.valueOf((byte) (b0 & 240 | color.getWoolData() & 15)), EntitySheep.META_WOOL_STATE, + (byte) (b0 & 240 | color.getWoolData() & 15)); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSkeleton.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSkeleton.java index ca059118d..122490073 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSkeleton.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSkeleton.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntitySkeleton; + import org.bukkit.entity.*; import org.bukkit.entity.Skeleton.SkeletonType; @@ -8,22 +10,22 @@ public class DisguiseSkeleton extends DisguiseMonster public DisguiseSkeleton(org.bukkit.entity.Entity entity) { super(EntityType.SKELETON, entity); - - DataWatcher.a(13, Byte.valueOf((byte)0)); + + DataWatcher.a(13, Byte.valueOf((byte) 0), EntitySkeleton.META_TYPE, 0); } - + public void SetSkeletonType(SkeletonType skeletonType) { - DataWatcher.watch(13, Byte.valueOf((byte)skeletonType.getId())); + DataWatcher.watch(13, Byte.valueOf((byte) skeletonType.getId()), EntitySkeleton.META_TYPE, skeletonType.getId()); } - + public int GetSkeletonType() { return DataWatcher.getByte(13); } - - protected String getHurtSound() - { - return "mob.skeleton.hurt"; - } + + protected String getHurtSound() + { + return "mob.skeleton.hurt"; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSlime.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSlime.java index ddb8bab5c..67e7547b0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSlime.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSlime.java @@ -1,5 +1,6 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntitySlime; import net.minecraft.server.v1_8_R3.MathHelper; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; @@ -10,14 +11,14 @@ public class DisguiseSlime extends DisguiseInsentient { super(entity); - DataWatcher.a(16, new Byte((byte)1)); + DataWatcher.a(16, new Byte((byte) 1), EntitySlime.META_SIZE, 1); } - + public void SetSize(int i) { - DataWatcher.watch(16, new Byte((byte)i)); + DataWatcher.watch(16, new Byte((byte) i), EntitySlime.META_SIZE, i); } - + public int GetSize() { return DataWatcher.getByte(16); @@ -29,63 +30,64 @@ public class DisguiseSlime extends DisguiseInsentient packet.a = Entity.getId(); packet.b = (byte) 55; packet.c = (int) MathHelper.floor(Entity.locX * 32D); - packet.d = (int)MathHelper.floor(Entity.locY * 32.0D); - packet.e = (int)MathHelper.floor(Entity.locZ * 32D); + packet.d = (int) MathHelper.floor(Entity.locY * 32.0D); + packet.e = (int) MathHelper.floor(Entity.locZ * 32D); packet.i = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); packet.j = (byte) ((int) (Entity.pitch * 256.0F / 360.0F)); packet.k = (byte) ((int) (Entity.yaw * 256.0F / 360.0F)); + packet.uuid = Entity.getUniqueID(); - double var2 = 3.9D; - double var4 = 0; - double var6 = 0; - double var8 = 0; + double var2 = 3.9D; + double var4 = 0; + double var6 = 0; + double var8 = 0; - if (var4 < -var2) - { - var4 = -var2; - } + if (var4 < -var2) + { + var4 = -var2; + } - if (var6 < -var2) - { - var6 = -var2; - } + if (var6 < -var2) + { + var6 = -var2; + } - if (var8 < -var2) - { - var8 = -var2; - } + if (var8 < -var2) + { + var8 = -var2; + } - if (var4 > var2) - { - var4 = var2; - } + if (var4 > var2) + { + var4 = var2; + } - if (var6 > var2) - { - var6 = var2; - } + if (var6 > var2) + { + var6 = var2; + } - if (var8 > var2) - { - var8 = var2; - } + if (var8 > var2) + { + var8 = var2; + } - packet.f = (int)(var4 * 8000.0D); - packet.g = (int)(var6 * 8000.0D); - packet.h = (int)(var8 * 8000.0D); + packet.f = (int) (var4 * 8000.0D); + packet.g = (int) (var6 * 8000.0D); + packet.h = (int) (var8 * 8000.0D); packet.l = DataWatcher; packet.m = DataWatcher.b(); - + return packet; } - - protected String getHurtSound() - { - return "mob.slime." + (GetSize() > 1 ? "big" : "small"); - } - - protected float getVolume() - { - return 0.4F * (float)GetSize(); - } + + protected String getHurtSound() + { + return "mob.slime." + (GetSize() > 1 ? "big" : "small"); + } + + protected float getVolume() + { + return 0.4F * (float) GetSize(); + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSpider.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSpider.java index 6b56f55e0..8851de909 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSpider.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSpider.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntitySpider; + import org.bukkit.entity.*; public class DisguiseSpider extends DisguiseMonster @@ -8,7 +10,7 @@ public class DisguiseSpider extends DisguiseMonster { super(EntityType.SPIDER, entity); - DataWatcher.a(16, new Byte((byte) 0)); + DataWatcher.a(16, new Byte((byte) 0), EntitySpider.META_CLIMBING, (byte) 0); } public boolean bT() @@ -20,12 +22,12 @@ public class DisguiseSpider extends DisguiseMonster { byte b0 = DataWatcher.getByte(16); - if(flag) + if (flag) b0 = (byte) (b0 | 0x1); else b0 = (byte) (b0 & 0xFFFFFFFE); - DataWatcher.watch(16, Byte.valueOf(b0)); + DataWatcher.watch(16, Byte.valueOf(b0), EntitySpider.META_CLIMBING, b0); } protected String getHurtSound() diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSquid.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSquid.java index 68f6d6dbb..040d5de5c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSquid.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseSquid.java @@ -7,34 +7,15 @@ public class DisguiseSquid extends DisguiseMonster public DisguiseSquid(org.bukkit.entity.Entity entity) { super(EntityType.SQUID, entity); - - DataWatcher.a(16, new Byte((byte)0)); - } - - public boolean bT() - { - return (DataWatcher.getByte(16) & 0x01) != 0; } - public void a(boolean flag) + protected String getHurtSound() { - byte b0 = DataWatcher.getByte(16); - - if (flag) - b0 = (byte)(b0 | 0x1); - else - b0 = (byte)(b0 & 0xFFFFFFFE); - - DataWatcher.watch(16, Byte.valueOf(b0)); + return "damage.hit"; + } + + protected float getVolume() + { + return 0.4F; } - - protected String getHurtSound() - { - return "damage.hit"; - } - - protected float getVolume() - { - return 0.4F; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseTameableAnimal.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseTameableAnimal.java index 015fc3b38..8309387c9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseTameableAnimal.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseTameableAnimal.java @@ -1,54 +1,53 @@ package mineplex.core.disguise.disguises; +import java.util.UUID; + +import net.minecraft.server.v1_8_R3.EntityTameableAnimal; + import org.bukkit.entity.*; +import com.google.common.base.Optional; + public abstract class DisguiseTameableAnimal extends DisguiseAnimal { public DisguiseTameableAnimal(EntityType disguiseType, org.bukkit.entity.Entity entity) { super(disguiseType, entity); - - DataWatcher.a(16, Byte.valueOf((byte)0)); - DataWatcher.a(17, ""); + + DataWatcher.a(16, Byte.valueOf((byte) 0), EntityTameableAnimal.META_SITTING_TAMED, (byte) 0); + DataWatcher.a(17, "", EntityTameableAnimal.META_OWNER, Optional. absent()); } - + public boolean isTamed() { return (DataWatcher.getByte(16) & 0x4) != 0; } - + public void setTamed(boolean tamed) { int i = DataWatcher.getByte(16); - + if (tamed) - DataWatcher.watch(16, Byte.valueOf((byte)(i | 0x4))); + DataWatcher.watch(16, Byte.valueOf((byte) (i | 0x4)), EntityTameableAnimal.META_SITTING_TAMED, (byte) (i | 0x4)); else - DataWatcher.watch(16, Byte.valueOf((byte)(i | 0xFFFFFFFB))); + DataWatcher.watch(16, Byte.valueOf((byte) (i | 0xFFFFFFFB)), EntityTameableAnimal.META_SITTING_TAMED, + (byte) (i | 0xFFFFFFFB)); } - + public boolean isSitting() { return (DataWatcher.getByte(16) & 0x1) != 0; } - + public void setSitting(boolean sitting) { int i = DataWatcher.getByte(16); - + if (sitting) - DataWatcher.watch(16, Byte.valueOf((byte)(i | 0x1))); + DataWatcher.watch(16, Byte.valueOf((byte) (i | 0x1)), EntityTameableAnimal.META_SITTING_TAMED, (byte) (i | 0x1)); else - DataWatcher.watch(16, Byte.valueOf((byte)(i | 0xFFFFFFFE))); - } - - public void setOwnerName(String name) - { - DataWatcher.watch(17, name); - } - - public String getOwnerName() - { - return DataWatcher.getString(17); + DataWatcher.watch(16, Byte.valueOf((byte) (i | 0xFFFFFFFE)), EntityTameableAnimal.META_SITTING_TAMED, + (byte) (i | 0xFFFFFFFE)); } + } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWitch.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWitch.java index 1de832596..83db8142c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWitch.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWitch.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityWitch; + import org.bukkit.entity.*; public class DisguiseWitch extends DisguiseMonster @@ -8,21 +10,21 @@ public class DisguiseWitch extends DisguiseMonster { super(EntityType.WITCH, entity); - DataWatcher.a(21, Byte.valueOf((byte)0)); - } - - public String getHurtSound() - { - return "mob.witch.hurt"; + DataWatcher.a(21, Byte.valueOf((byte) 0), EntityWitch.META_AGGRESSIVE, false); } - public void a(boolean flag) + public String getHurtSound() { - DataWatcher.watch(21, Byte.valueOf((byte)(flag ? 1 : 0))); + return "mob.witch.hurt"; } - - public boolean bT() + + public void a(boolean flag) { - return DataWatcher.getByte(21) == 1; + DataWatcher.watch(21, Byte.valueOf((byte) (flag ? 1 : 0)), EntityWitch.META_AGGRESSIVE, flag); + } + + public boolean bT() + { + return DataWatcher.getByte(21) == 1; } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWither.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWither.java index 45a6b13a7..333d283bd 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWither.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWither.java @@ -1,37 +1,37 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityWither; + import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; +import mineplex.core.common.util.UtilMath; + public class DisguiseWither extends DisguiseMonster { public DisguiseWither(org.bukkit.entity.Entity entity) { super(EntityType.WITHER, entity); - - DataWatcher.a(17, new Integer(0)); - DataWatcher.a(18, new Integer(0)); - DataWatcher.a(19, new Integer(0)); - DataWatcher.a(20, new Integer(0)); + + DataWatcher.a(17, new Integer(0), EntityWither.META_INVUL_TIME, 0); + DataWatcher.a(18, new Integer(0), EntityWither.META_TARGET_1, 0); + DataWatcher.a(19, new Integer(0), EntityWither.META_TARGET_2, 0); + DataWatcher.a(20, new Integer(0), EntityWither.META_TARGET_3, 0); } - public int getInvulTime() - { - return DataWatcher.getInt(20); - } - - public void setInvulTime(int i) - { - DataWatcher.watch(20, Integer.valueOf(i)); - } - - public int t(int i) - { - return DataWatcher.getInt(17 + i); - } + public int getInvulTime() + { + return DataWatcher.getInt(20); + } - public void b(int i, int j) - { - DataWatcher.watch(17 + i, Integer.valueOf(j)); - } + public void setInvulTime(int i) + { + DataWatcher.watch(17, Integer.valueOf(i), EntityWither.META_INVUL_TIME, i); + DataWatcher.watch(20, Integer.valueOf(i), EntityWither.META_INVUL_TIME, i); + } + + public int t(int i) + { + return DataWatcher.getInt(17 + i); + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWolf.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWolf.java index 90497a983..3b663f075 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWolf.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseWolf.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityWolf; + import org.bukkit.entity.*; public class DisguiseWolf extends DisguiseTameableAnimal @@ -8,51 +10,52 @@ public class DisguiseWolf extends DisguiseTameableAnimal { super(EntityType.WOLF, entity); - DataWatcher.a(18, new Float(20F)); - DataWatcher.a(19, new Byte((byte)0)); - DataWatcher.a(20, new Byte((byte)14)); + DataWatcher.a(18, new Float(20F), EntityWolf.META_WOLF_HEALTH, 20F); + DataWatcher.a(19, new Byte((byte) 0), EntityWolf.META_BEGGING, false); + DataWatcher.a(20, new Byte((byte) 14), EntityWolf.META_COLLAR, 14); } - - public boolean isAngry() + + public boolean isAngry() { return (DataWatcher.getByte(16) & 0x2) != 0; } - + public void setAngry(boolean angry) { - byte b0 = DataWatcher.getByte(16); + byte b0 = DataWatcher.getByte(16); - if (angry) - DataWatcher.watch(16, Byte.valueOf((byte)(b0 | 0x2))); - else - DataWatcher.watch(16, Byte.valueOf((byte)(b0 & 0xFFFFFFFD))); + if (angry) + DataWatcher.watch(16, Byte.valueOf((byte) (b0 | 0x2)), EntityWolf.META_SITTING_TAMED, (byte) (b0 | 0x2)); + else + DataWatcher + .watch(16, Byte.valueOf((byte) (b0 & 0xFFFFFFFD)), EntityWolf.META_SITTING_TAMED, (byte) (b0 & 0xFFFFFFFD)); } - public int getCollarColor() + public int getCollarColor() { - return DataWatcher.getByte(20) & 0xF; + return DataWatcher.getByte(20) & 0xF; } - public void setCollarColor(int i) + public void setCollarColor(int i) { - DataWatcher.watch(20, Byte.valueOf((byte)(i & 0xF))); + DataWatcher.watch(20, Byte.valueOf((byte) (i & 0xF)), EntityWolf.META_COLLAR, (i & 0xF)); } - + public void m(boolean flag) { - if (flag) - DataWatcher.watch(19, Byte.valueOf((byte)1)); - else - DataWatcher.watch(19, Byte.valueOf((byte)0)); + if (flag) + DataWatcher.watch(19, Byte.valueOf((byte) 1), EntityWolf.META_BEGGING, flag); + else + DataWatcher.watch(19, Byte.valueOf((byte) 0), EntityWolf.META_BEGGING, flag); } - + public boolean ce() { return DataWatcher.getByte(19) == 1; } - - protected String getHurtSound() - { - return "mob.wolf.hurt"; - } + + protected String getHurtSound() + { + return "mob.wolf.hurt"; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseZombie.java b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseZombie.java index ca8f9355e..c5f45f804 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseZombie.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/disguise/disguises/DisguiseZombie.java @@ -1,5 +1,7 @@ package mineplex.core.disguise.disguises; +import net.minecraft.server.v1_8_R3.EntityZombie; + import org.bukkit.entity.*; public class DisguiseZombie extends DisguiseMonster @@ -12,34 +14,34 @@ public class DisguiseZombie extends DisguiseMonster public DisguiseZombie(EntityType disguiseType, Entity entity) { super(disguiseType, entity); - - DataWatcher.a(12, Byte.valueOf((byte)0)); - DataWatcher.a(13, Byte.valueOf((byte)0)); - DataWatcher.a(14, Byte.valueOf((byte)0)); + + DataWatcher.a(12, Byte.valueOf((byte) 0), EntityZombie.META_CHILD, false); + DataWatcher.a(13, Byte.valueOf((byte) 0), EntityZombie.META_VILLAGER, false); + DataWatcher.a(14, Byte.valueOf((byte) 0), EntityZombie.META_CONVERTING, false); } - + public boolean IsBaby() { return DataWatcher.getByte(12) == 1; } - + public void SetBaby(boolean baby) { - DataWatcher.watch(12, Byte.valueOf((byte)(baby ? 1 : 0))); + DataWatcher.watch(12, Byte.valueOf((byte) (baby ? 1 : 0)), EntityZombie.META_CHILD, baby); } - + public boolean IsVillager() { return DataWatcher.getByte(13) == 1; } - + public void SetVillager(boolean villager) { - DataWatcher.watch(13, Byte.valueOf((byte)(villager ? 1 : 0))); + DataWatcher.watch(13, Byte.valueOf((byte) (villager ? 1 : 0)), EntityZombie.META_VILLAGER, villager); + } + + protected String getHurtSound() + { + return "mob.zombie.hurt"; } - - protected String getHurtSound() - { - return "mob.zombie.hurt"; - } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/command/GemCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/command/GemCommand.java index 8690987bc..a19144834 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/command/GemCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/command/GemCommand.java @@ -10,6 +10,7 @@ import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; import mineplex.core.common.util.UUIDFetcher; import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; import mineplex.core.donation.DonationManager; public class GemCommand extends CommandBase @@ -32,7 +33,11 @@ public class GemCommand extends CommandBase String gemsString = args[1]; Player target = UtilPlayer.searchExact(targetName); - if (target == null) + if (targetName.equalsIgnoreCase("@a")) + { + rewardAllGems(caller, gemsString); + } + else if (target == null) { UUID uuid = UUIDFetcher.getUUIDOf(targetName); if (uuid != null) @@ -50,6 +55,42 @@ public class GemCommand extends CommandBase } } + private void rewardAllGems(Player caller, String gemsString) + { + try + { + int gems = Integer.parseInt(gemsString); + + if (gems > 1000) + { + UtilPlayer.message(caller, F.main("Gem", "You can only give everybody 1000 gems at a time.")); + return; + } + + rewardAllGems(caller, gems); + } + catch (Exception e) + { + UtilPlayer.message(caller, F.main("Gem", "Invalid gems Amount")); + } + } + + private void rewardAllGems(Player caller, int gems) + { + for (Player player : UtilServer.getPlayers()) + { + Plugin.RewardGems(new Callback() + { + public void run(Boolean completed) + { + + } + }, caller.getName(), player.getName(), player.getUniqueId(), gems); + } + + UtilPlayer.message(caller, F.main("Gem", "Gave everyone " + F.elem(gems + " gems"))); + } + private void rewardGems(final Player caller, final Player target, final String targetName, final UUID uuid, String gemsString) { try diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/command/ShardCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/command/ShardCommand.java index c65df1a4a..cbe9dc269 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/command/ShardCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/command/ShardCommand.java @@ -6,8 +6,8 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; import mineplex.core.donation.DonationManager; - import org.bukkit.entity.Player; public class ShardCommand extends CommandBase @@ -30,7 +30,11 @@ public class ShardCommand extends CommandBase final String coinsString = args[1]; Player target = UtilPlayer.searchExact(targetName); - if (target == null) + if (targetName.equalsIgnoreCase("@a")) + { + rewardAllShards(caller, coinsString); + } + else if (target == null) { Plugin.getClientManager().loadClientByName(targetName, new Runnable() { @@ -53,6 +57,44 @@ public class ShardCommand extends CommandBase } } + private void rewardAllShards(Player caller, String shardsString) + { + try + { + int shards = Integer.parseInt(shardsString); + + if (shards > 1000) + { + UtilPlayer.message(caller, F.main("Shards", "You can only give everybody 1000 shards at a time.")); + return; + } + + rewardAllShards(caller, shards); + } + catch (Exception e) + { + UtilPlayer.message(caller, F.main("Shards", "Invalid Shards Amount")); + } + } + + private void rewardAllShards(Player caller, int shards) + { + for (Player player : UtilServer.getPlayers()) + { + CoreClient client = Plugin.getClientManager().Get(player); + + Plugin.RewardCoins(new Callback() + { + public void run(Boolean completed) + { + + } + }, caller.getName(), player.getName(), client.getAccountId(), shards); + } + + UtilPlayer.message(caller, F.main("Shards", "Gave everyone " + F.elem(shards + " Treasure Shards"))); + } + private void rewardCoins(final Player caller, final Player target, final String targetName, final int accountId, String coinsString) { try diff --git a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java index 5e696359e..8b842f424 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/donation/repository/DonationRepository.java @@ -27,20 +27,20 @@ public class DonationRepository extends MinecraftRepository private static String CREATE_GEM_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountGemTransactions (id INT NOT NULL AUTO_INCREMENT, accountId INT, reason VARCHAR(100), gems INT, PRIMARY KEY (id), FOREIGN KEY (accountId) REFERENCES accounts(id));"; private static String INSERT_COIN_TRANSACTION = "INSERT INTO accountCoinTransactions(accountId, reason, coins) VALUES(?, ?, ?);"; private static String UPDATE_ACCOUNT_COINS = "UPDATE accounts SET coins = coins + ? WHERE id = ?;"; - private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE id = ?;"; + private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE id = ? && gold >= ?;"; private static String SET_ACCOUNT_GOLD = "UPDATE accounts SET gold = ? WHERE id = ?;"; private static String UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_ = "UPDATE accounts SET gems = ?, coins = ? WHERE id = ? AND gems IS NULL AND coins IS NULL;"; private String _webAddress; - + public DonationRepository(JavaPlugin plugin, String webAddress) { super(plugin, DBPool.getAccount()); - + _webAddress = webAddress; } - - public void PurchaseKnownSalesPackage(final Callback callback, String name, final String uuid, final int cost, final int salesPackageId) + + public void PurchaseKnownSalesPackage(final Callback callback, String name, final String uuid, final int cost, final int salesPackageId) { final PurchaseToken token = new PurchaseToken(); token.AccountName = name; @@ -61,7 +61,7 @@ public class DonationRepository extends MinecraftRepository }); } }; - + handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() @@ -70,7 +70,7 @@ public class DonationRepository extends MinecraftRepository } }), "Error purchasing known sales package in DonationRepository : "); } - + public void PurchaseUnknownSalesPackage(final Callback callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost) { final UnknownPurchaseToken token = new UnknownPurchaseToken(); @@ -96,7 +96,7 @@ public class DonationRepository extends MinecraftRepository executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", -cost), new ColumnInt("id", accountId)); } } - + Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable() { @Override @@ -107,7 +107,7 @@ public class DonationRepository extends MinecraftRepository }); } }; - + handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() @@ -116,18 +116,18 @@ public class DonationRepository extends MinecraftRepository } }), "Error purchasing unknown sales package in DonationRepository : "); } - + public void gemReward(final Callback callback, final String giver, String name, final String uuid, final int greenGems) { final GemRewardToken token = new GemRewardToken(); token.Source = giver; token.Name = name; token.Amount = greenGems; - + final Callback extraCallback = new Callback() { public void run(final Boolean response) - { + { Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable() { @Override @@ -138,7 +138,7 @@ public class DonationRepository extends MinecraftRepository }); } }; - + handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() @@ -147,14 +147,14 @@ public class DonationRepository extends MinecraftRepository } }), "Error updating player gem amount in DonationRepository : "); } - + public void rewardCoins(final Callback callback, final String giver, String name, final int accountId, final int coins) { final GemRewardToken token = new GemRewardToken(); token.Source = giver; token.Name = name; token.Amount = coins; - + final Callback extraCallback = new Callback() { public void run(final Boolean response) @@ -164,7 +164,7 @@ public class DonationRepository extends MinecraftRepository //executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", coins), new ColumnInt("id", accountId)); //executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Rewarded by " + giver), new ColumnInt("coins", coins)); } - + Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable() { @Override @@ -175,7 +175,7 @@ public class DonationRepository extends MinecraftRepository }); } }; - + handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() @@ -184,21 +184,26 @@ public class DonationRepository extends MinecraftRepository } }), "Error updating player coin amount in DonationRepository : "); } - + public void rewardGold(final Callback callback, final String giver, final String name, final int accountId, final int gold) - { + { handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() { - boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) > 0; + ColumnInt min = new ColumnInt("gold", gold < 0 ? -gold : 0); + boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId), min) > 0; callback.run(success); } }), "Error updating player gold amount in DonationRepository : "); } - + public void setGold(final Callback callback, final String giver, final String name, final int accountId, final int gold) - { + { + if (gold < 0) + { + throw new IllegalArgumentException("gold cannot be negative"); + } handleDatabaseCall(new DatabaseRunnable(new Runnable() { public void run() @@ -208,7 +213,7 @@ public class DonationRepository extends MinecraftRepository } }), "Error updating player gold amount in DonationRepository : "); } - + @Override protected void initialize() { @@ -240,12 +245,12 @@ public class DonationRepository extends MinecraftRepository public Donor retrieveDonorInfo(ResultSet resultSet) throws SQLException { Donor donor = new Donor(); - + while (resultSet.next()) { donor.setGold(resultSet.getInt(1)); } - + return donor; } } \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloClientData.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloClientData.java index 2a4f86703..ffe6aa944 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloClientData.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloClientData.java @@ -4,5 +4,5 @@ import mineplex.core.common.util.NautHashMap; public class EloClientData { - public NautHashMap Elos = new NautHashMap(); + public NautHashMap Elos = new NautHashMap(); } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloDivision.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloDivision.java new file mode 100644 index 000000000..f60ae1d1f --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloDivision.java @@ -0,0 +1,72 @@ +package mineplex.core.elo; + +import java.util.UUID; + +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +public class EloDivision +{ + private byte _divisionPercentile; + private int _playerElo; + private UUID _uuid; + private String _divisionName; + + //If I understand MaterialData objects correctly, + private Material _divisionMaterial; + private byte _divisionMaterialValue; + private MaterialData _divisionMaterialData; + + public EloDivision(UUID userID, byte divPercent, int pElo) + { + _uuid = userID; + _divisionPercentile = divPercent; + _playerElo = pElo; + _divisionName = calculateDivision(divPercent, _playerElo); + + } + + public String calculateDivision(double divPercent, int _playerElo) + { + + if (divPercent > 99 && _playerElo > 3500) { return "Diamond"; } + if (_playerElo >= 3500) { return "Emerald 3"; } + if (_playerElo < 3500 && _playerElo >= 3300) { return "Emerald 2"; } + if (_playerElo < 3300 && _playerElo >= 3100) { return "Emerald 1"; } + if (_playerElo < 3100 && _playerElo >= 2900) { return "Lapis 3"; } + if (_playerElo < 2900 && _playerElo >= 2700) { return "Lapis 2"; } + if (_playerElo < 2700 && _playerElo >= 2500) { return "Lapis 1"; } + if (_playerElo < 2500 && _playerElo >= 2300) { return "Gold 3"; } + if (_playerElo < 2300 && _playerElo >= 2100) { return "Gold 2"; } + if (_playerElo < 2100 && _playerElo >= 1900) { return "Gold 1"; } + if (_playerElo < 1900 && _playerElo >= 1700) { return "Iron 3"; } + if (_playerElo < 1700 && _playerElo >= 1500) { return "Iron 2"; } + if (_playerElo < 1500 && _playerElo >= 1300) { return "Iron 1"; } + if (_playerElo < 1300 && _playerElo >= 800) { return "Coal 3"; } + if (_playerElo < 800 && _playerElo >= 600) { return "Coal 2"; } + if (_playerElo < 600) { return "Coal 1"; } + + //if none of the above are true, a player is in the bottom 20% + return "Coal 1"; + } + + @SuppressWarnings("deprecation") + //method to set icon's material(since it will change with player's ELO) + public void setDivisionIcon(Material divMat, byte divData) + { + _divisionMaterial = divMat; + _divisionMaterialValue = divData; + _divisionMaterialData = new MaterialData(_divisionMaterial, _divisionMaterialValue); + } + + public MaterialData getMaterialData() + { + return _divisionMaterialData; + } + + public String getDivisionName() + { + return _divisionName; + } + +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloManager.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloManager.java index d1c44b6d6..10bd385f9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloManager.java @@ -2,105 +2,147 @@ package mineplex.core.elo; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.UUID; +import java.util.HashSet; import mineplex.core.MiniDbClientPlugin; import mineplex.core.account.CoreClientManager; import mineplex.core.common.util.NautHashMap; -import org.bukkit.Bukkit; +import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class EloManager extends MiniDbClientPlugin { - private static Object _playerEloLock = new Object(); - private EloRepository _repository; private EloRatingSystem _ratingSystem; - private NautHashMap> _playerElos; + private NautHashMap _eloTeams = new NautHashMap<>(); public EloManager(JavaPlugin plugin, CoreClientManager clientManager) { super("Elo Rating", plugin, clientManager); _repository = new EloRepository(plugin); - _ratingSystem = new EloRatingSystem(new KFactor(0, 1200, 25), new KFactor(1201, 1600, 20), new KFactor(1601, 2000, 15), new KFactor(2001, 2500, 10)); - _playerElos = new NautHashMap>(); + _ratingSystem = new EloRatingSystem + ( + new KFactor(0, 1299, 50), + new KFactor(1300, 1899, 45), + new KFactor(1900, 2499, 40), + new KFactor(2500, 3099, 30), + new KFactor(3100, 3699, 20), + new KFactor(3700, 5000, 10) + ); } - - public int getElo(UUID uuid, String gameType) + + public int getElo(Player player, int gameType) { - int elo = 1000; + if (!Get(player).Elos.containsKey(gameType)) + return 1000; - synchronized (_playerEloLock) - { - if (_playerElos.containsKey(uuid.toString())) - { - if (_playerElos.get(uuid.toString()).containsKey(gameType)) - { - elo = _playerElos.get(uuid.toString()).get(gameType); - } - } - } - - return elo; + return Get(player).Elos.get(gameType); } public EloTeam getNewRatings(EloTeam teamA, EloTeam teamB, GameResult result) { EloTeam newTeam = new EloTeam(); - - System.out.println("Old " + result + " Team Rating:" + teamA.TotalElo); - + int newTotal = _ratingSystem.getNewRating(teamA.TotalElo / teamA.getPlayers().size(), teamB.TotalElo / teamB.getPlayers().size(), result) * teamA.getPlayers().size(); - - System.out.println("New " + result + " Team Rating:" + newTotal); + int kTotal = 0; for (EloPlayer player : teamA.getPlayers()) { - EloPlayer newPlayer = new EloPlayer(); - newPlayer.UniqueId = player.UniqueId; - newPlayer.Rating = (int)(player.Rating + ((double)player.Rating / (double)teamA.TotalElo) * (newTotal - teamA.TotalElo)); - - System.out.println("Old:"); - player.printInfo(); - - System.out.println("New:"); - newPlayer.printInfo(); - + kTotal += _ratingSystem.getKFactor(player.getRating()); + } + + for (EloPlayer player : teamA.getPlayers()) + { + int newRating = (int)(player.getRating() + ((double)_ratingSystem.getKFactor(player.getRating()) / (double)kTotal) * (newTotal - teamA.TotalElo)); + EloPlayer newPlayer = new EloPlayer(player.getPlayer(), player.getAccountId(), newRating); + newTeam.addPlayer(newPlayer); } return newTeam; } - public void saveElo(UUID uuid, String gameType, int elo) + public void saveElo(final Player player, final int accountId, final int gameType, final int oldElo, final int elo) { - saveElo(uuid.toString(), gameType, elo); - } - - public void saveElo(final String uuid, final String gameType, final int elo) - { - Bukkit.getServer().getScheduler().runTaskAsynchronously(getPlugin(), new Runnable() + runAsync(new Runnable() { public void run() { - _repository.saveElo(uuid, gameType, elo); + boolean success = false; - synchronized (_playerEloLock) + try { - if (_playerElos.containsKey(uuid)) + success = _repository.saveElo(accountId, gameType, oldElo, elo); + } + catch (SQLException e) + { + e.printStackTrace(); + } + finally + { + System.out.println("Saving " + accountId + "'s new elo rating of " + elo + " for gameType " + gameType + (success ? " SUCCEEDED." : " FAILED.")); + } + + final boolean finalSuccess = success; + + runSync(new Runnable() + { + public void run() { - if (_playerElos.get(uuid).containsKey(gameType)) + if (finalSuccess) { - _playerElos.get(uuid).put(gameType, elo); + if (player.isOnline()) + Get(player).Elos.put(gameType, elo); } } - } + }); } }); } - + + public String getPlayerDivision(Player player, int gameType) + { + int playerElo = getElo(player, gameType); + String divisionName = "Player's division"; + + if (playerElo >= 3700) + divisionName = "Diamond"; + else if (playerElo < 3700 && playerElo >= 3500) + divisionName = "Emerald 3"; + else if (playerElo < 3500 && playerElo >= 3300) + divisionName = "Emerald 2"; + else if (playerElo < 3300 && playerElo >= 3100) + divisionName = "Emerald 1"; + else if (playerElo < 3100 && playerElo >= 2900) + divisionName = "Lapis 3"; + else if (playerElo < 2900 && playerElo >= 2700) + divisionName = "Lapis 2"; + else if (playerElo < 2700 && playerElo >= 2500) + divisionName = "Lapis 1"; + else if (playerElo < 2500 && playerElo >= 2300) + divisionName = "Gold 3"; + else if (playerElo < 2300 && playerElo >= 2100) + divisionName = "Gold 2"; + else if (playerElo < 2100 && playerElo >= 1900) + divisionName = "Gold 1"; + else if (playerElo < 1900 && playerElo >= 1700) + divisionName = "Iron 3"; + else if (playerElo < 1700 && playerElo >= 1500) + divisionName = "Iron 2"; + else if (playerElo < 1500 && playerElo >= 1300) + divisionName = "Iron 1"; + else if (playerElo < 1300 && playerElo >= 1100) + divisionName = "Coal 3"; + else if (playerElo < 1100 && playerElo >= 900) + divisionName = "Coal 2"; + else if (playerElo < 900) + divisionName = "Coal 1"; + + return divisionName; + } + @Override protected EloClientData AddPlayer(String player) { @@ -116,6 +158,58 @@ public class EloManager extends MiniDbClientPlugin @Override public String getQuery(int accountId, String uuid, String name) { - return "SELECT gameType, elo FROM eloRating WHERE uuid = '" + uuid + "';"; + return "SELECT gameType, elo FROM eloRating WHERE accountId = '" + accountId + "';"; + } + + public void addTeam(String displayName, EloTeam eloTeam) + { + _eloTeams.put(displayName, eloTeam); + } + + public void setWinningTeam(String displayName) + { + _eloTeams.get(displayName).Winner = true; + } + + public void endMatch(int gameId) + { + EloTeam teamWinner = null; + EloTeam teamLoser = null; + + for (EloTeam team : _eloTeams.values()) + { + if (team.Winner) + teamWinner = team; + else + teamLoser = team; + } + + EloTeam teamWinnerNew = getNewRatings(teamWinner, teamLoser, GameResult.Win); + EloTeam teamLoserNew = getNewRatings(teamLoser, teamWinner, GameResult.Loss); + + // Use teams to calculate Elo + for (EloPlayer eloPlayer : teamWinnerNew.getPlayers()) + { + int oldElo = teamWinner.getPlayer(eloPlayer.getPlayer().getUniqueId().toString()).getRating(); + + // If this is the first time. + if (!Get(eloPlayer.getPlayer()).Elos.containsKey(gameId)) + oldElo = eloPlayer.getRating(); + + saveElo(eloPlayer.getPlayer(), eloPlayer.getAccountId(), gameId, oldElo, eloPlayer.getRating()); + } + + for (EloPlayer eloPlayer : teamLoserNew.getPlayers()) + { + int oldElo = teamLoser.getPlayer(eloPlayer.getPlayer().getUniqueId().toString()).getRating(); + + // If this is the first time. + if (!Get(eloPlayer.getPlayer()).Elos.containsKey(gameId)) + oldElo = eloPlayer.getRating(); + + saveElo(eloPlayer.getPlayer(), eloPlayer.getAccountId(), gameId, oldElo, eloPlayer.getRating()); + } + + _eloTeams.clear(); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloPlayer.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloPlayer.java index a2661fee3..58c56a888 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloPlayer.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloPlayer.java @@ -1,12 +1,37 @@ package mineplex.core.elo; +import org.bukkit.entity.Player; + public class EloPlayer { - public String UniqueId; - public int Rating; + private Player _player; + private int _accountId; + private int _rating; + + public EloPlayer(Player player, int accountId, int rating) + { + _player = player; + _accountId = accountId; + _rating = rating; + } + + public Player getPlayer() + { + return _player; + } + + public int getRating() + { + return _rating; + } + + public int getAccountId() + { + return _accountId; + } public void printInfo() { - System.out.println(UniqueId + "'s elo is " + Rating); + System.out.println(_player.getName() + "'s elo is " + _rating); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRatingSystem.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRatingSystem.java index d32433ed6..cb18341cc 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRatingSystem.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRatingSystem.java @@ -57,7 +57,7 @@ public class EloRatingSystem return oldRating + (int) (kFactor * (score - expectedScore)); } - private double getKFactor(int rating) + double getKFactor(int rating) { for (int i = 0; i < _kFactors.length; i++) { diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRepository.java index 8c0874208..1c5e749f8 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRepository.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloRepository.java @@ -4,17 +4,16 @@ import java.sql.ResultSet; import java.sql.SQLException; import mineplex.core.database.MinecraftRepository; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnInt; + import org.bukkit.plugin.java.JavaPlugin; -import mineplex.serverdata.database.DBPool; -import mineplex.serverdata.database.RepositoryBase; -import mineplex.serverdata.database.column.ColumnInt; -import mineplex.serverdata.database.column.ColumnVarChar; - public class EloRepository extends MinecraftRepository -{ - private static String CREATE_ELO_TABLE = "CREATE TABLE IF NOT EXISTS eloRating (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(256), gameType VARCHAR(256), elo INT, PRIMARY KEY (id), UNIQUE INDEX uuid_gameType_index (uuid, gameType));"; - private static String INSERT_ELO = "INSERT INTO eloRating (uuid, gameType, elo) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE elo=VALUES(elo);"; +{ + private static String INSERT_ELO = "INSERT INTO eloRating (accountId, gameType, elo) VALUES (?, ?, ?);"; + private static String UPDATE_ELO = "UPDATE eloRating SET elo = elo + ? WHERE accountId = ? AND gameType = ?;"; + private static String UPDATE_ELO_ONLY_IF_MATCH = "UPDATE eloRating SET elo = elo + ? WHERE accountId = ? AND gameType = ? AND elo = ?;"; public EloRepository(JavaPlugin plugin) { @@ -23,14 +22,26 @@ public class EloRepository extends MinecraftRepository initialize(); } - public void initialize() + public void initialize() { } + + public boolean saveElo(int accountId, int gameType, int oldElo, int elo) throws SQLException { - //executeUpdate(CREATE_ELO_TABLE); - } + boolean updateSucceeded = false; + + // If we're increasing in elo we verify the server version matches the database version (prevent d/c and double wins with concurrent matches) + // Otherwise we always take their elo down if they lose. + if (elo > oldElo) + updateSucceeded = executeUpdate(UPDATE_ELO_ONLY_IF_MATCH, new ColumnInt("elo", elo - oldElo), new ColumnInt("accountId", accountId), new ColumnInt("gameType", gameType), new ColumnInt("elo", oldElo)) > 0; + else + { + updateSucceeded = executeUpdate(UPDATE_ELO, new ColumnInt("elo", elo - oldElo), new ColumnInt("accountId", accountId), new ColumnInt("gameType", gameType)) > 0; + + if (!updateSucceeded && executeUpdate(INSERT_ELO, new ColumnInt("accountId", accountId), new ColumnInt("gameType", gameType), new ColumnInt("elo", elo)) > 0) + updateSucceeded = true; + } - public void saveElo(String uuid, String gameType, int elo) - { - executeUpdate(INSERT_ELO, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("gameType", 100, gameType), new ColumnInt("elo", elo)); + + return updateSucceeded; } public EloClientData loadClientInformation(ResultSet resultSet) throws SQLException @@ -39,7 +50,7 @@ public class EloRepository extends MinecraftRepository while (resultSet.next()) { - clientData.Elos.put(resultSet.getString(1), resultSet.getInt(2)); + clientData.Elos.put(resultSet.getInt(1), resultSet.getInt(2)); } return clientData; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloTeam.java b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloTeam.java index 73f54168a..538fd22da 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/elo/EloTeam.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/elo/EloTeam.java @@ -1,23 +1,29 @@ package mineplex.core.elo; -import java.util.ArrayList; -import java.util.List; +import java.util.Collection; + +import mineplex.core.common.util.NautHashMap; public class EloTeam { - private List _players = new ArrayList(); - + private NautHashMap _players = new NautHashMap<>(); public int TotalElo = 0; + public boolean Winner = false; public void addPlayer(EloPlayer player) { - TotalElo += player.Rating; + TotalElo += player.getRating(); - _players.add(player); + _players.put(player.getPlayer().getUniqueId().toString(), player); } - public List getPlayers() + public EloPlayer getPlayer(String uuid) { - return _players; + return _players.get(uuid); + } + + public Collection getPlayers() + { + return _players.values(); } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/explosion/Explosion.java b/Plugins/Mineplex.Core/src/mineplex/core/explosion/Explosion.java index 31c8f24d7..b950fb05e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/explosion/Explosion.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/explosion/Explosion.java @@ -9,14 +9,13 @@ import java.util.Map.Entry; import java.util.UUID; import mineplex.core.MiniPlugin; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.core.updater.UpdateType; import mineplex.core.blockrestore.BlockRestore; import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; import org.bukkit.Effect; import org.bukkit.Location; @@ -32,7 +31,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.Vector; @@ -234,7 +232,7 @@ public class Explosion extends MiniPlugin fallingIterator.remove(); //Expire - if (cur.getTicksLived() > 400 || !cur.getWorld().isChunkLoaded(cur.getLocation().getBlockX() >> 4, cur.getLocation().getBlockZ() >> 4)) + if (cur.getTicksLived() > 100 || !cur.getWorld().isChunkLoaded(cur.getLocation().getBlockX() >> 4, cur.getLocation().getBlockZ() >> 4)) { cur.remove(); return; @@ -362,4 +360,16 @@ public class Explosion extends MiniPlugin } }, 1); } + + public void setEnabled(boolean var) + { + if (var) + { + registerSelf(); + } + else + { + deregisterSelf(); + } + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/fallingblock/FallingBlocks.java b/Plugins/Mineplex.Core/src/mineplex/core/fallingblock/FallingBlocks.java new file mode 100644 index 000000000..46b462c17 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/fallingblock/FallingBlocks.java @@ -0,0 +1,62 @@ +package mineplex.core.fallingblock; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.FallingBlock; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.Vector; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.UtilAction; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilEnt; + +public class FallingBlocks extends MiniPlugin +{ + public static FallingBlocks Instance; + + private static final String METADATA = "FALLING_BLOCK_SPECIAL"; + + public FallingBlocks(JavaPlugin plugin) + { + super("Falling Blocks", plugin); + + Instance = this; + } + + public void Spawn(Location location, Material type, byte data, Location center) + { + Vector vec = UtilAlg.getTrajectory(center, location); + + if (vec.getY() < 0) + { + vec.setY(vec.getY() * -1); + } + + Spawn(location, type, data, vec); + } + + public void Spawn(Location location, Material type, byte data, Vector velocity) + { + FallingBlock fall = location.getWorld().spawnFallingBlock(location.add(0.5, 0.5, 0.5), type, data); + fall.setDropItem(false); + + UtilAction.velocity(fall, velocity, 0.5 + 0.25 * Math.random(), false, 0, 0.4 + 0.20 * Math.random(), 10, false); + + fall.setMetadata(METADATA, new FixedMetadataValue(_plugin, "x")); + UtilEnt.SetMetadata(fall, METADATA, "x"); + } + + @EventHandler + public void BlockFall(EntityChangeBlockEvent event) + { + if (event.getEntity().hasMetadata(METADATA)) + { + event.getEntity().remove(); + event.setCancelled(true); + } + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/friend/FriendManager.java b/Plugins/Mineplex.Core/src/mineplex/core/friend/FriendManager.java index ba5558573..f76dc39f4 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/friend/FriendManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/friend/FriendManager.java @@ -29,6 +29,7 @@ import mineplex.core.friend.command.FriendsDisplay; import mineplex.core.friend.data.FriendData; import mineplex.core.friend.data.FriendRepository; import mineplex.core.friend.data.FriendStatus; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.portal.Portal; import mineplex.core.preferences.PreferencesManager; import mineplex.core.updater.UpdateType; @@ -278,7 +279,6 @@ public class FriendManager extends MiniDbClientPlugin if (friend.Status == FriendStatusType.Accepted) { - // Online Friend if (friend.Online) { if (friend.ServerName.contains("Staff") || friend.ServerName.contains("CUST")) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/friend/command/FriendsDisplay.java b/Plugins/Mineplex.Core/src/mineplex/core/friend/command/FriendsDisplay.java index 6109041f6..14c3b37ed 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/friend/command/FriendsDisplay.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/friend/command/FriendsDisplay.java @@ -26,14 +26,14 @@ public class FriendsDisplay extends CommandBase Plugin.getPreferenceManager().savePreferences(caller); caller.playSound(caller.getLocation(), Sound.NOTE_PLING, 1, 1.6f); - + if (preferences.friendDisplayInventoryUI) { - new FriendsGUI(Plugin, caller); + Plugin.runAsync(() -> new FriendsGUI(Plugin, caller)); } else { - Plugin.showFriends(caller); + Plugin.runAsync(() -> Plugin.showFriends(caller)); } } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/friend/ui/FriendsGUI.java b/Plugins/Mineplex.Core/src/mineplex/core/friend/ui/FriendsGUI.java index 7f2f27f1d..d492a2931 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/friend/ui/FriendsGUI.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/friend/ui/FriendsGUI.java @@ -32,6 +32,7 @@ import mineplex.core.friend.FriendManager; import mineplex.core.friend.FriendStatusType; import mineplex.core.friend.data.FriendData; import mineplex.core.friend.data.FriendStatus; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.itemstack.ItemBuilder; import mineplex.core.itemstack.ItemLayout; import mineplex.core.shop.item.IButton; @@ -127,7 +128,7 @@ public class FriendsGUI implements Listener } FriendStatus friend = friends.get(friendSlot); - + ItemBuilder builder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) (friend.Online ? 3 : 0)); builder.setTitle(C.cWhite + C.Bold + friend.Name); @@ -272,7 +273,7 @@ public class FriendsGUI implements Listener } FriendStatus friend = friends.get(friendSlot); - + ItemBuilder builder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) (friend.Online ? 3 : 0)); builder.setTitle(C.cWhite + C.Bold + friend.Name); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/morph/BlockForm.java b/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/morph/BlockForm.java index 4a4be4ccd..294e5f68c 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/morph/BlockForm.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/gadget/gadgets/morph/BlockForm.java @@ -13,6 +13,7 @@ import mineplex.core.disguise.disguises.DisguiseChicken; import mineplex.core.gadget.event.GadgetBlockEvent; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.recharge.Recharge; +import net.minecraft.server.v1_8_R3.Entity; import org.bukkit.Bukkit; import org.bukkit.Effect; @@ -30,25 +31,25 @@ public class BlockForm { private MorphBlock _host; private Player _player; - + private Material _mat; private Block _block; private Location _loc; - public BlockForm(MorphBlock host, Player player, Material mat) + public BlockForm(MorphBlock host, Player player, Material mat) { _host = host; _player = player; - + _mat = mat; _loc = player.getLocation(); - + Apply(); } - - public void Apply() + + public void Apply() { - //Remove Old + // Remove Old if (_player.getPassenger() != null) { Recharge.Instance.useForce(_player, "PassengerChange", 100); @@ -57,36 +58,42 @@ public class BlockForm _player.eject(); } - ((CraftEntity)_player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 32)); + ((CraftEntity) _player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 32), Entity.META_ENTITYDATA, (byte) 32); - //Player > Chicken + // Player > Chicken DisguiseChicken disguise = new DisguiseChicken(_player); - disguise.setBaby(); + disguise.setBaby(); disguise.setSoundDisguise(new DisguiseCat(_player)); disguise.setInvisible(true); _host.Manager.getDisguiseManager().disguise(disguise); - //Apply Falling Block + // Apply Falling Block FallingBlockCheck(); - //Inform - String blockName = F.elem(ItemStackFactory.Instance.GetName(_mat, (byte)0, false)); + // Inform + String blockName = F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false)); if (!blockName.contains("Block")) - UtilPlayer.message(_player, F.main("Morph", "You are now a " + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte)0, false) + " Block") + "!")); + UtilPlayer + .message( + _player, + F.main("Morph", + "You are now a " + + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false) + " Block") + "!")); else - UtilPlayer.message(_player, F.main("Morph", "You are now a " + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte)0, false)) + "!")); + UtilPlayer.message(_player, + F.main("Morph", "You are now a " + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false)) + "!")); - //Sound + // Sound _player.playSound(_player.getLocation(), Sound.ZOMBIE_UNFECT, 2f, 2f); } - public void Remove() + public void Remove() { SolidifyRemove(); _host.Manager.getDisguiseManager().undisguise(_player); - //Remove FB + // Remove FB if (_player.getPassenger() != null) { Recharge.Instance.useForce(_player, "PassengerChange", 100); @@ -95,97 +102,99 @@ public class BlockForm _player.eject(); } - ((CraftEntity)_player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0)); + ((CraftEntity) _player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0), Entity.META_ENTITYDATA, (byte) 0); } public void SolidifyUpdate() { if (!_player.isSprinting()) - ((CraftEntity)_player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 32)); - - //Not a Block + ((CraftEntity) _player).getHandle().getDataWatcher() + .watch(0, Byte.valueOf((byte) 32), Entity.META_ENTITYDATA, (byte) 32); + + // Not a Block if (_block == null) { - //Moved + // Moved if (!_loc.getBlock().equals(_player.getLocation().getBlock())) { _player.setExp(0); _loc = _player.getLocation(); } - //Unmoved + // Unmoved else { double hideBoost = 0.025; _player.setExp((float) Math.min(0.999f, _player.getExp() + hideBoost)); - //Set Block + // Set Block if (_player.getExp() >= 0.999f) { Block block = _player.getLocation().getBlock(); List blockList = new ArrayList(); blockList.add(block); - + GadgetBlockEvent event = new GadgetBlockEvent(_host, blockList); - + Bukkit.getServer().getPluginManager().callEvent(event); - - //Not Able - if (block.getType() != Material.AIR || !UtilBlock.solid(block.getRelative(BlockFace.DOWN)) || event.getBlocks().isEmpty() || event.isCancelled()) + + // Not Able + if (block.getType() != Material.AIR || !UtilBlock.solid(block.getRelative(BlockFace.DOWN)) + || event.getBlocks().isEmpty() || event.isCancelled()) { UtilPlayer.message(_player, F.main("Morph", "You cannot become a Solid Block here.")); _player.setExp(0f); return; } - //Set Block + // Set Block _block = block; - //Effect + // Effect _player.playEffect(_player.getLocation(), Effect.STEP_SOUND, _mat); - //block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, _mat); + // block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, _mat); - //Display + // Display SolidifyVisual(); - //Invisible - //Host.Manager.GetCondition().Factory().Cloak("Disguised as Block", Player, Player, 60000, false, false); + // Invisible + // Host.Manager.GetCondition().Factory().Cloak("Disguised as Block", Player, Player, 60000, false, false); - //Sound + // Sound _player.playSound(_player.getLocation(), Sound.NOTE_PLING, 1f, 2f); } } } - //Is a Block + // Is a Block else { - //Moved + // Moved if (!_loc.getBlock().equals(_player.getLocation().getBlock())) { SolidifyRemove(); } - //Send Packets + // Send Packets else { SolidifyVisual(); } - } + } } public void SolidifyRemove() { if (_block != null) { - MapUtil.QuickChangeBlockAt(_block.getLocation(), 0, (byte)0); + MapUtil.QuickChangeBlockAt(_block.getLocation(), 0, (byte) 0); _block = null; } _player.setExp(0f); - //Host.Manager.GetCondition().EndCondition(Player, null, "Disguised as Block"); + // Host.Manager.GetCondition().EndCondition(Player, null, "Disguised as Block"); - //Inform + // Inform _player.playSound(_player.getLocation(), Sound.NOTE_PLING, 1f, 0.5f); FallingBlockCheck(); @@ -197,7 +206,7 @@ public class BlockForm if (_block == null) return; - //Remove Old + // Remove Old if (_player.getPassenger() != null) { Recharge.Instance.useForce(_player, "PassengerChange", 100); @@ -206,49 +215,49 @@ public class BlockForm _player.eject(); } - //Others + // Others for (Player other : UtilServer.getPlayers()) - other.sendBlockChange(_player.getLocation(), _mat, (byte)0); + other.sendBlockChange(_player.getLocation(), _mat, (byte) 0); - //Self - _player.sendBlockChange(_player.getLocation(), 36, (byte)0); + // Self + _player.sendBlockChange(_player.getLocation(), 36, (byte) 0); FallingBlockCheck(); } - public void FallingBlockCheck() + public void FallingBlockCheck() { - //Block Form (Hide Falling) + // Block Form (Hide Falling) if (_block != null) return; - //Recreate Falling + // Recreate Falling if (_player.getPassenger() == null || !_player.getPassenger().isValid()) { if (!Recharge.Instance.use(_player, "PassengerChange", 100, false, false)) return; - //Falling Block - FallingBlock block = _player.getWorld().spawnFallingBlock(_player.getEyeLocation(), _mat, (byte)0); - - //No Arrow Collision - ((CraftFallingSand)block).getHandle().spectating = true; - + // Falling Block + FallingBlock block = _player.getWorld().spawnFallingBlock(_player.getEyeLocation(), _mat, (byte) 0); + + // No Arrow Collision + ((CraftFallingSand) block).getHandle().spectating = true; + _player.setPassenger(block); - + _host.fallingBlockRegister(block); } - //Ensure Falling doesnt Despawn + // Ensure Falling doesnt Despawn else { - ((CraftFallingSand)_player.getPassenger()).getHandle().ticksLived = 1; + ((CraftFallingSand) _player.getPassenger()).getHandle().ticksLived = 1; _player.getPassenger().setTicksLived(1); } } - public Block GetBlock() + public Block GetBlock() { return _block; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/game/GameDisplay.java b/Plugins/Mineplex.Core/src/mineplex/core/game/GameDisplay.java index ba348de05..c8180c277 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/game/GameDisplay.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/game/GameDisplay.java @@ -21,6 +21,7 @@ public enum GameDisplay Dragons("Dragons", Material.ENDER_STONE, (byte)0, GameCategory.ARCADE, 13), DragonsTeams("Dragons Teams", Material.DRAGON_EGG, (byte)0, GameCategory.TEAM_VARIANT, 14), Draw("Draw My Thing", Material.BOOK_AND_QUILL, (byte)0, GameCategory.CLASSICS, 15), + ElytraRings("Elytra Rings", Material.ELYTRA, (byte) 0, GameCategory.CLASSICS, 61), Evolution("Evolution", Material.EMERALD, (byte)0, GameCategory.ARCADE, 16), Gravity("Gravity", Material.ENDER_PORTAL_FRAME, (byte)0, GameCategory.EXTRA, 18), Halloween("Halloween Horror", Material.PUMPKIN, (byte)0, GameCategory.CLASSICS, 19), @@ -68,14 +69,17 @@ public enum GameDisplay Lobbers("Bomb Lobbers", Material.FIREBALL, (byte) 0, GameCategory.ARCADE, 54), + Minecraft_League("MC League", Material.DIAMOND_SWORD, (byte)0, GameCategory.SURVIVAL, 62), + ChampionsCTF("Champions CTF", "Champions", Material.BANNER, DyeColor.RED.getDyeData(), GameCategory.CHAMPIONS, 56), + BouncyBalls("Bouncy Balls", Material.SLIME_BALL, (byte)0, GameCategory.ARCADE, 57), Gladiators("Gladiators", Material.IRON_SWORD, (byte)0, GameCategory.ARCADE, 58), TypeWars("Type Wars", Material.NAME_TAG, (byte) 0, GameCategory.CLASSICS, 59), SpeedBuilders("Speed Builders", Material.QUARTZ_BLOCK, (byte) 0, GameCategory.CLASSICS, 60), - Valentines("Valentines Vendetta", Material.LEATHER, (byte)0, GameCategory.EXTRA, 60), + Valentines("Valentines Vendetta", Material.LEATHER, (byte)0, GameCategory.EXTRA, 61), Event("Mineplex Event", Material.CAKE, (byte)0, GameCategory.EVENT, 999); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java b/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java index a569b9612..4a768f50a 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/hologram/Hologram.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; +import java.util.UUID; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -13,6 +14,7 @@ import org.bukkit.util.Vector; import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilPlayer; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; @@ -20,11 +22,9 @@ import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityTeleport; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; -public class Hologram -{ +public class Hologram { - public enum HologramTarget - { + public enum HologramTarget { BLACKLIST, WHITELIST; } @@ -37,7 +37,8 @@ public class Hologram private HologramManager _hologramManager; private String[] _hologramText = new String[0]; /** - * Keeps track of the holograms movements. This fixes offset that occasionally happens when moving a hologram around. + * Keeps track of the holograms movements. This fixes offset that + * occasionally happens when moving a hologram around. */ private Vector _lastMovement; private Location _location; @@ -53,38 +54,41 @@ public class Hologram private boolean _hideBoundingBox; private HologramInteraction _interaction; - public Hologram(HologramManager hologramManager, Location location, String... text) - { + private long _maxLifetime = -1; + private long _startTime; + + public Hologram(HologramManager hologramManager, Location location, String... text) { + this(hologramManager, location, -1l, text); + } + + public Hologram(HologramManager hologramManager, Location location, long maxLifetime, String... text) { _hologramManager = hologramManager; _location = location.clone(); + _maxLifetime = maxLifetime; setText(text); } - public Hologram setInteraction(HologramInteraction interact) - { + public Hologram setInteraction(HologramInteraction interact) { _interaction = interact; return this; } - public HologramInteraction getInteraction() - { + public HologramInteraction getInteraction() { return _interaction; } /** * Adds the player to the Hologram to be effected by Whitelist or Blacklist */ - public Hologram addPlayer(Player player) - { + public Hologram addPlayer(Player player) { return addPlayer(player.getName()); } /** * Adds the player to the Hologram to be effected by Whitelist or Blacklist */ - public Hologram addPlayer(String player) - { + public Hologram addPlayer(String player) { _playersInList.add(player); return this; } @@ -94,8 +98,7 @@ public class Hologram * * @return */ - public Hologram setHideBoundingBox() - { + public Hologram setHideBoundingBox() { _hideBoundingBox = true; return this; } @@ -103,23 +106,19 @@ public class Hologram /** * Is there a player entry in the hologram for Whitelist and Blacklist */ - public boolean containsPlayer(Player player) - { + public boolean containsPlayer(Player player) { return _playersInList.contains(player.getName()); } /** * Is there a player entry in the hologram for Whitelist and Blacklist */ - public boolean containsPlayer(String player) - { + public boolean containsPlayer(String player) { return _playersInList.contains(player); } - protected Packet getDestroyPacket() - { - if (_makeDestroyPackets) - { + protected Packet getDestroyPacket() { + if (_makeDestroyPackets) { makeDestroyPacket(); _makeDestroyPackets = false; } @@ -127,8 +126,7 @@ public class Hologram return _destroy1_8; } - public Entity getEntityFollowing() - { + public Entity getEntityFollowing() { return _followEntity; } @@ -138,27 +136,22 @@ public class Hologram * @Whitelist = Only people added can see the hologram * @Blacklist = Anyone but people added can see the hologram */ - public HologramTarget getHologramTarget() - { + public HologramTarget getHologramTarget() { return _target; } /** * Get the hologram location */ - public Location getLocation() - { + public Location getLocation() { return _location.clone(); } - protected ArrayList getNearbyPlayers() - { + protected ArrayList getNearbyPlayers() { ArrayList nearbyPlayers = new ArrayList(); - for (Player player : getLocation().getWorld().getPlayers()) - { - if (isVisible(player)) - { + for (Player player : getLocation().getWorld().getPlayers()) { + if (isVisible(player)) { nearbyPlayers.add(player); } } @@ -166,15 +159,12 @@ public class Hologram return nearbyPlayers; } - protected ArrayList getPlayersTracking() - { + protected ArrayList getPlayersTracking() { return _playersTracking; } - protected Packet[] getSpawnPackets() - { - if (_makeSpawnPackets) - { + protected Packet[] getSpawnPackets() { + if (_makeSpawnPackets) { makeSpawnPackets(); _makeSpawnPackets = false; } @@ -185,13 +175,12 @@ public class Hologram /** * Get the text in the hologram */ - public String[] getText() - { - // We reverse it again as the hologram would otherwise display the text from the bottom row to the top row + public String[] getText() { + // We reverse it again as the hologram would otherwise display the text + // from the bottom row to the top row String[] reversed = new String[_hologramText.length]; - for (int i = 0; i < reversed.length; i++) - { + for (int i = 0; i < reversed.length; i++) { reversed[i] = _hologramText[reversed.length - (i + 1)]; } @@ -201,32 +190,25 @@ public class Hologram /** * Get the view distance the hologram is viewable from. Default is 70 */ - public int getViewDistance() - { + public int getViewDistance() { return _viewDistance; } /** * Is the hologram holograming? */ - public boolean isInUse() - { + public boolean isInUse() { return _lastMovement != null; } - public boolean isRemoveOnEntityDeath() - { + public boolean isRemoveOnEntityDeath() { return _removeEntityDeath; } - public boolean isVisible(Player player) - { - if (getLocation().getWorld() == player.getWorld()) - { - if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player)) - { - if (getLocation().distance(player.getLocation()) < getViewDistance()) - { + public boolean isVisible(Player player) { + if (getLocation().getWorld() == player.getWorld()) { + if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player)) { + if (getLocation().distance(player.getLocation()) < getViewDistance()) { return true; } } @@ -235,53 +217,42 @@ public class Hologram return false; } - private void makeDestroyPacket() - { + private void makeDestroyPacket() { int[] entityIds1_8 = new int[_entityIds.size()]; - for (int i = 0; i < _entityIds.size(); i++) - { + for (int i = 0; i < _entityIds.size(); i++) { entityIds1_8[i] = _entityIds.get(i); } _destroy1_8 = new PacketPlayOutEntityDestroy(entityIds1_8); } - private void makeSpawnPackets() - { + private void makeSpawnPackets() { _packets1_8 = new Packet[_hologramText.length * 1]; - if (_entityIds.size() < _hologramText.length) - { + if (_entityIds.size() < _hologramText.length) { _makeDestroyPackets = true; - for (int i = _entityIds.size(); i < _hologramText.length; i++) - { - _entityIds.add(UtilEnt.getNewEntityId()); + for (int i = _entityIds.size(); i < _hologramText.length; i++) { + _entityIds.add(Integer.valueOf(UtilEnt.getNewEntityId())); } - } - else - { + } else { _makeDestroyPackets = true; - while (_entityIds.size() > _hologramText.length) - { + while (_entityIds.size() > _hologramText.length) { _entityIds.remove(_hologramText.length); } } - for (int textRow = 0; textRow < _hologramText.length; textRow++) - { + for (int textRow = 0; textRow < _hologramText.length; textRow++) { Packet[] packets1_8 = makeSpawnPackets1_8(textRow, _entityIds.get(textRow), _hologramText[textRow]); - for (int i = 0; i < packets1_8.length; i++) - { + for (int i = 0; i < packets1_8.length; i++) { _packets1_8[textRow + i] = packets1_8[i]; } } } - private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText) - { + private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText) { PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(); DataWatcher watcher = new DataWatcher(null); @@ -291,50 +262,54 @@ public class Hologram packet.d = (int) ((getLocation().getY() + (_hideBoundingBox ? 0 : -2.1) + ((double) textRow * 0.285)) * 32); packet.e = (int) (getLocation().getZ() * 32); packet.l = watcher; + packet.uuid = UUID.randomUUID(); // Setup datawatcher for armor stand - watcher.a(0, (byte) 32); - watcher.a(2, lineOfText); - watcher.a(3, (byte) 1); + watcher.a(0, (byte) 32, EntityArmorStand.META_ENTITYDATA, (byte) 32); + watcher.a(2, lineOfText, EntityArmorStand.META_CUSTOMNAME, lineOfText); + watcher.a(3, (byte) 1, EntityArmorStand.META_CUSTOMNAME_VISIBLE, true); - if (_hideBoundingBox) - { - watcher.a(10, (byte) 16); // TODO Uncomment after we can enforce 1.8.3 + if (_hideBoundingBox) { + watcher.a(10, (byte) 16, EntityArmorStand.META_ARMOR_OPTION, (byte) 16); // TODO + // Uncomment + // after + // we + // can + // enforce + // 1.8.3 } // Also correct hologram positioning - return new Packet[] - { - packet - }; + return new Packet[] { packet }; } /** - * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist + * Removes the player from the Hologram so they are no longer effected by + * Whitelist or Blacklist */ - public Hologram removePlayer(Player player) - { + public Hologram removePlayer(Player player) { return removePlayer(player.getName()); } /** - * Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist + * Removes the player from the Hologram so they are no longer effected by + * Whitelist or Blacklist */ - public Hologram removePlayer(String player) - { + public Hologram removePlayer(String player) { _playersInList.remove(player); return this; } /** - * If the entity moves, the hologram will update its position to appear relative to the movement. + * If the entity moves, the hologram will update its position to appear + * relative to the movement. * * @Please note the hologram updates every tick. */ - public Hologram setFollowEntity(Entity entityToFollow) - { + public Hologram setFollowEntity(Entity entityToFollow) { _followEntity = entityToFollow; - relativeToEntity = entityToFollow == null ? null : _location.clone().subtract(entityToFollow.getLocation()).toVector(); + relativeToEntity = entityToFollow == null ? null + : _location.clone().subtract(entityToFollow.getLocation()).toVector(); return this; } @@ -345,8 +320,7 @@ public class Hologram * @Whitelist = Only people added can see the hologram * @Blacklist = Anyone but people added can see the hologram */ - public Hologram setHologramTarget(HologramTarget newTarget) - { + public Hologram setHologramTarget(HologramTarget newTarget) { _target = newTarget; return this; } @@ -354,52 +328,43 @@ public class Hologram /** * Sets the hologram to appear at this location */ - public Hologram setLocation(Location newLocation) - { + public Hologram setLocation(Location newLocation) { _makeSpawnPackets = true; Location oldLocation = getLocation(); _location = newLocation.clone(); - if (getEntityFollowing() != null) - { + if (getEntityFollowing() != null) { relativeToEntity = _location.clone().subtract(getEntityFollowing().getLocation()).toVector(); } - if (isInUse()) - { + if (isInUse()) { ArrayList canSee = getNearbyPlayers(); Iterator itel = _playersTracking.iterator(); - while (itel.hasNext()) - { + while (itel.hasNext()) { Player player = itel.next(); - if (!canSee.contains(player)) - { + if (!canSee.contains(player)) { itel.remove(); - if (player.getWorld() == getLocation().getWorld()) - { + if (player.getWorld() == getLocation().getWorld()) { UtilPlayer.sendPacket(player, getDestroyPacket()); } } } itel = canSee.iterator(); - while (itel.hasNext()) - { + while (itel.hasNext()) { Player player = itel.next(); - if (!_playersTracking.contains(player)) - { + if (!_playersTracking.contains(player)) { _playersTracking.add(player); itel.remove(); UtilPlayer.sendPacket(player, getSpawnPackets()); } } - if (!canSee.isEmpty()) - { - _lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(), newLocation.getY() - oldLocation.getY(), - newLocation.getZ() - oldLocation.getZ())); + if (!canSee.isEmpty()) { + _lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(), + newLocation.getY() - oldLocation.getY(), newLocation.getZ() - oldLocation.getZ())); int x = (int) Math.floor(32 * _lastMovement.getX()); int y = (int) Math.floor(32 * _lastMovement.getY()); @@ -409,11 +374,9 @@ public class Hologram int i = 0; - if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) - { + if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) { _lastMovement.subtract(new Vector(x / 32D, y / 32D, z / 32D)); - for (Integer entityId : _entityIds) - { + for (Integer entityId : _entityIds) { PacketPlayOutEntity.PacketPlayOutRelEntityMove relMove = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(); relMove.a = entityId; @@ -424,16 +387,13 @@ public class Hologram packets1_8[i] = relMove; i++; } - } - else - { + } else { x = (int) Math.floor(32 * newLocation.getX()); z = (int) Math.floor(32 * newLocation.getZ()); _lastMovement = new Vector(newLocation.getX() - (x / 32D), 0, newLocation.getZ() - (z / 32D)); - for (Integer entityId : _entityIds) - { + for (Integer entityId : _entityIds) { PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport(); teleportPacket.a = entityId; teleportPacket.b = x; @@ -446,10 +406,8 @@ public class Hologram } } - for (Player player : canSee) - { - for (Packet packet : packets1_8) - { + for (Player player : canSee) { + for (Packet packet : packets1_8) { UtilPlayer.sendPacket(player, packet); } } @@ -458,48 +416,50 @@ public class Hologram return this; } - public Hologram setRemoveOnEntityDeath() + public long getStartTime() { + return _startTime; + } + + public long getMaxLifetime() + { + return _maxLifetime; + } + + public Hologram setRemoveOnEntityDeath() { _removeEntityDeath = true; return this; } - public boolean isEntityId(int entityId) - { + public boolean isEntityId(int entityId) { return _entityIds.contains(entityId); } /** * Set the hologram text */ - public Hologram setText(String... newLines) - { + public Hologram setText(String... newLines) { String[] newText = new String[newLines.length]; - for (int i = 0; i < newText.length; i++) - { + for (int i = 0; i < newText.length; i++) { newText[i] = newLines[newText.length - (i + 1)]; } if (newText.equals(_hologramText)) return this; - if (isInUse()) - { + if (isInUse()) { int[] destroy1_8 = new int[0]; ArrayList packets1_8 = new ArrayList(); - if (_hologramText.length != newText.length) - { + if (_hologramText.length != newText.length) { _makeDestroyPackets = true; } - for (int i = 0; i < Math.max(_hologramText.length, newText.length); i++) - { + for (int i = 0; i < Math.max(_hologramText.length, newText.length); i++) { // If more lines than previously - if (i >= _hologramText.length) - { + if (i >= _hologramText.length) { // Add entity id and send spawn packets // You add a entity id because the new hologram needs int entityId = UtilEnt.getNewEntityId(); @@ -508,16 +468,13 @@ public class Hologram packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(i, entityId, newText[i]))); } // If less lines than previously - else if (i >= newText.length) - { + else if (i >= newText.length) { // Remove entity id and send destroy packets Integer entityId = _entityIds.remove(newText.length); destroy1_8 = Arrays.copyOf(destroy1_8, destroy1_8.length + 1); destroy1_8[destroy1_8.length - 1] = entityId; - } - else if (!newText[i].equals(_hologramText[i])) - { + } else if (!newText[i].equals(_hologramText[i])) { // Send update metadata packets Integer entityId = _entityIds.get(i); @@ -527,10 +484,11 @@ public class Hologram DataWatcher watcher1_8 = new DataWatcher(null); - watcher1_8.a(0, (byte) 32); - watcher1_8.a(2, newText[i]); - watcher1_8.a(3, (byte) 1); - // watcher1_8.a(10, (byte) 16);// TODO Uncomment after we can enforce 1.8.3 + watcher1_8.a(0, (byte) 32, EntityArmorStand.META_ENTITYDATA, (byte) 32); + watcher1_8.a(2, newText[i], EntityArmorStand.META_CUSTOMNAME, newText[i]); + watcher1_8.a(3, (byte) 1, EntityArmorStand.META_CUSTOMNAME_VISIBLE, true); + // watcher1_8.a(10, (byte) 16);// TODO Uncomment after we + // can enforce 1.8.3 // Also correct hologram positioning metadata1_8.b = watcher1_8.c(); @@ -538,15 +496,12 @@ public class Hologram } } - if (destroy1_8.length > 0) - { + if (destroy1_8.length > 0) { packets1_8.add(new PacketPlayOutEntityDestroy(destroy1_8)); } - for (Player player : _playersTracking) - { - for (Packet packet : packets1_8) - { + for (Player player : _playersTracking) { + for (Packet packet : packets1_8) { UtilPlayer.sendPacket(player, packet); } } @@ -561,8 +516,7 @@ public class Hologram /** * Set the distance the hologram is viewable from. Default is 70 */ - public Hologram setViewDistance(int newDistance) - { + public Hologram setViewDistance(int newDistance) { _viewDistance = newDistance; return setLocation(getLocation()); } @@ -570,15 +524,15 @@ public class Hologram /** * Start the hologram */ - public Hologram start() - { - if (!isInUse()) - { + public Hologram start() { + if (!isInUse()) { + + _startTime = System.currentTimeMillis(); + _hologramManager.addHologram(this); _playersTracking.addAll(getNearbyPlayers()); - for (Player player : _playersTracking) - { + for (Player player : _playersTracking) { UtilPlayer.sendPacket(player, getSpawnPackets()); } @@ -590,14 +544,11 @@ public class Hologram /** * Stop the hologram */ - public Hologram stop() - { - if (isInUse()) - { + public Hologram stop() { + if (isInUse()) { _hologramManager.removeHologram(this); - for (Player player : _playersTracking) - { + for (Player player : _playersTracking) { UtilPlayer.sendPacket(player, getDestroyPacket()); } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/hologram/HologramManager.java b/Plugins/Mineplex.Core/src/mineplex/core/hologram/HologramManager.java index df8a9352b..3ff9c3a35 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/hologram/HologramManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/hologram/HologramManager.java @@ -5,6 +5,7 @@ import java.util.Iterator; import java.util.List; import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTime; import mineplex.core.packethandler.IPacketHandler; import mineplex.core.packethandler.PacketHandler; import mineplex.core.packethandler.PacketInfo; @@ -52,15 +53,20 @@ public class HologramManager implements Listener, IPacketHandler List worlds = Bukkit.getWorlds(); - Iterator itel = _activeHolograms.iterator(); + Iterator iterator = _activeHolograms.iterator(); - while (itel.hasNext()) + while (iterator.hasNext()) { - Hologram hologram = itel.next(); - - if (!worlds.contains(hologram.getLocation().getWorld())) + Hologram hologram = iterator.next(); + + if (hologram.getMaxLifetime() != -1 && UtilTime.elapsed(hologram.getStartTime(), hologram.getMaxLifetime())) { - itel.remove(); + iterator.remove(); + hologram.stop(); + } + else if (!worlds.contains(hologram.getLocation().getWorld())) + { + iterator.remove(); hologram.stop(); } else @@ -71,7 +77,7 @@ public class HologramManager implements Listener, IPacketHandler if (hologram.isRemoveOnEntityDeath() && !following.isValid()) { - itel.remove(); + iterator.remove(); hologram.stop(); continue; } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/IncognitoManager.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/IncognitoManager.java new file mode 100644 index 000000000..18b94a27b --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/IncognitoManager.java @@ -0,0 +1,228 @@ +package mineplex.core.incognito; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniDbClientPlugin; +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.Rank; +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.incognito.commands.IncognitoToggleCommand; +import mineplex.core.incognito.events.IncognitoHidePlayerEvent; +import mineplex.core.incognito.events.IncognitoStatusChangeEvent; +import mineplex.core.incognito.repository.IncognitoClient; +import mineplex.core.incognito.repository.IncognitoRepository; +import mineplex.core.packethandler.PacketHandler; +import mineplex.core.preferences.PreferencesManager; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + +public class IncognitoManager extends MiniDbClientPlugin +{ + private CoreClientManager _clientManager; + private IncognitoRepository _repository; + private PreferencesManager _preferencesManager; + + public IncognitoManager(JavaPlugin plugin, CoreClientManager clientManager, PacketHandler packetHandler) + { + super("Incognito", plugin, clientManager); + + _repository = new IncognitoRepository(this); + _clientManager = clientManager; + } + + public void addCommands() + { + addCommand(new IncognitoToggleCommand(this)); + } + + public boolean toggle(Player caller) + { + boolean enabled = !Get(caller).Status; + + IncognitoStatusChangeEvent event = UtilServer.CallEvent(new IncognitoStatusChangeEvent(caller, enabled)); + + if (event.isCancelled()) + { + return false; + } + + Get(caller).Status = enabled; + + if (!enabled) + { + if (event.doShow()) + { + for (Player other : UtilServer.getPlayers()) + { + other.showPlayer(caller); + } + } + } + else + { + IncognitoHidePlayerEvent customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(caller)); + + if (!customEvent.isCancelled()) + { + UtilServer.getPlayersCollection().forEach(player -> { + player.hidePlayer(caller); + }); + } + } + + runAsync(() -> _repository.setStatus(_clientManager.getAccountId(caller), enabled)); + + return enabled; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void Join(PlayerJoinEvent event) + { + Player player = event.getPlayer(); + + if (Get(event.getPlayer()).Status && !_clientManager.hasRank(event.getPlayer(), Rank.HELPER)) + { + Get(event.getPlayer()).Status = false; + runAsync(() -> _repository.setStatus(_clientManager.getAccountId(player), false)); + return; + } + + if (Get(event.getPlayer()).Status) + { + event.setJoinMessage(null); + informIncognito(player); + } + + IncognitoHidePlayerEvent customEvent = null; + + if (Get(event.getPlayer()).Status) + { + customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(player)); + } + + for (Player other : UtilServer.getPlayers()) + { + if (customEvent != null && !customEvent.isCancelled() && !_clientManager.hasRank(other, _clientManager.Get(player).GetRank())) + { + other.hidePlayer(player); + } + + if (Get(other).Status) + { + IncognitoHidePlayerEvent customEvent2 = UtilServer.CallEvent(new IncognitoHidePlayerEvent(other)); + + if (!customEvent2.isCancelled() && !_clientManager.hasRank(player, _clientManager.Get(other).GetRank())) + { + player.hidePlayer(other); + } + } + } + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + { + return; + } + + for (Player player : UtilServer.getPlayers()) + { + for (Player other : UtilServer.getPlayers()) + { + if (Get(player).Status) + { + IncognitoHidePlayerEvent customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(player)); + + if (!customEvent.isCancelled() && !_clientManager.hasRank(other, _clientManager.Get(player).GetRank())) + { + other.hidePlayer(player); + } + } + + if (Get(other).Status) + { + IncognitoHidePlayerEvent customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(other)); + + if (!customEvent.isCancelled() && !_clientManager.hasRank(player, _clientManager.Get(other).GetRank())) + { + player.hidePlayer(other); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void Quit(PlayerQuitEvent event) + { + if (Get(event.getPlayer()).Status) + { + event.setQuitMessage(null); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void Kick(PlayerKickEvent event) + { + if (Get(event.getPlayer()).Status) + { + event.setLeaveMessage(null); + } + } + + private void informIncognito(Player player) + { + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cGoldB + "You are currently incognito."); + UtilPlayer.message(player, C.cYellow + "This means you are invisible to all except for those who are " + _clientManager.Get(player).GetRank().getTag(true, false) + C.mBody + "+"); + UtilPlayer.message(player, " "); + } + + protected IncognitoClient AddPlayer(String player) + { + return new IncognitoClient(); + } + + public IncognitoRepository getRepository() + { + return _repository; + } + + @Override + public String getQuery(int accountId, String uuid, String name) + { + return "SELECT * FROM incognitoStaff WHERE accountId = " + accountId + ";"; + } + + @Override + public void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException + { + while (resultSet.next()) + { + Get(playerName).Status = resultSet.getInt("status") == 1; + } + } + + public PreferencesManager getPreferences() + { + return _preferencesManager; + } + + public void setPreferencesManager(PreferencesManager preferencesManager) + { + _preferencesManager = preferencesManager; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/commands/IncognitoToggleCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/commands/IncognitoToggleCommand.java new file mode 100644 index 000000000..83eefcdc9 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/commands/IncognitoToggleCommand.java @@ -0,0 +1,36 @@ +package mineplex.core.incognito.commands; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.incognito.IncognitoManager; + +public class IncognitoToggleCommand extends CommandBase +{ + public IncognitoToggleCommand(IncognitoManager plugin) + { + super(plugin, Rank.HELPER, "incognito", "vanish"); + } + + @Override + public void Execute(Player caller, String[] args) + { + if (Plugin.getPreferences().Get(caller).Invisibility) + { + UtilPlayer.message(caller, F.main("Incognito", "You are not allowed to toggle incognito on while Hub Invisibility is enabled.")); + return; + } + + if (Plugin.toggle(caller)) + { + UtilPlayer.message(caller, F.main("Incognito", "You are now incognito. Your status will only change when you run " + F.elem(AliasUsed) + " again.")); + } + else + { + UtilPlayer.message(caller, F.main("Incognito", "You are no longer incognito. Your status will only change when you run " + F.elem(AliasUsed) + " again.")); + } + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java new file mode 100644 index 000000000..54dabeebc --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java @@ -0,0 +1,47 @@ +package mineplex.core.incognito.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called when an Incognito player is getting hidden from all other players. + */ +public class IncognitoHidePlayerEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private boolean _cancelled; + + public IncognitoHidePlayerEvent(Player player) + { + _player = player; + } + + public Player getPlayer() + { + return _player; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoStatusChangeEvent.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoStatusChangeEvent.java new file mode 100644 index 000000000..79e3291ee --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/events/IncognitoStatusChangeEvent.java @@ -0,0 +1,64 @@ +package mineplex.core.incognito.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class IncognitoStatusChangeEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private boolean _newState; + + private boolean _cancelled; + + private boolean _show = true; + + public IncognitoStatusChangeEvent(Player player, boolean newState) + { + _player = player; + _newState = newState; + } + + public boolean getNewState() + { + return _newState; + } + + public Player getPlayer() + { + return _player; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public void show(boolean show) + { + _show = show; + } + + public boolean doShow() + { + return _show; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoClient.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoClient.java new file mode 100644 index 000000000..18382fd22 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoClient.java @@ -0,0 +1,6 @@ +package mineplex.core.incognito.repository; + +public class IncognitoClient +{ + public boolean Status; +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoRepository.java new file mode 100644 index 000000000..b27472430 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/incognito/repository/IncognitoRepository.java @@ -0,0 +1,33 @@ +package mineplex.core.incognito.repository; + +import mineplex.core.database.MinecraftRepository; +import mineplex.core.incognito.IncognitoManager; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnInt; + +public class IncognitoRepository extends MinecraftRepository +{ + private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS incognitoStaff (accountId INT NOT NULL, status TINYINT(1) DEFAULT '0', PRIMARY KEY (accountId));"; + private static final String INSERT_STATUS = "INSERT INTO incognitoStaff (accountId, status) VALUES (?, ?);"; + private static final String UPDATE_STATUS = "UPDATE incognitoStaff SET status=? WHERE accountId=?;"; + + public IncognitoRepository(IncognitoManager incognitoManager) + { + super(incognitoManager.getPlugin(), DBPool.getAccount()); + } + + public void setStatus(int accountId, boolean status) + { + if (executeUpdate(UPDATE_STATUS, new ColumnInt("status", status ? 1 : 0), new ColumnInt("accountId", accountId)) <= 0) + executeInsert(INSERT_STATUS, null, new ColumnInt("accountId", accountId), new ColumnInt("status", status ? 1 : 0)); + } + + protected void initialize() + { + executeUpdate(CREATE_TABLE); + } + + protected void update() + { + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/inventory/command/GiveItemCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/inventory/command/GiveItemCommand.java index 94e726ad8..b5f03fe3e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/inventory/command/GiveItemCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/inventory/command/GiveItemCommand.java @@ -9,6 +9,7 @@ import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; import mineplex.core.inventory.InventoryManager; import mineplex.core.inventory.data.Item; @@ -47,6 +48,15 @@ public class GiveItemCommand extends CommandBase { UtilPlayer.message(caller, F.main("Item", "Item with the name " + F.item(itemName) + " not found!")); } + else if (playerName.equalsIgnoreCase("@a")) + { + for (Player pl : UtilServer.getPlayers()) + { + Plugin.addItemToInventory(pl, item.Name, amount); + } + + UtilPlayer.message(caller, F.main("Item", "You gave " + F.elem(amount + " " + itemName) + " to everyone")); + } else if (player != null) { Plugin.addItemToInventory(player, item.Name, amount); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/itemstack/ItemBuilder.java b/Plugins/Mineplex.Core/src/mineplex/core/itemstack/ItemBuilder.java index 4f555ab3d..49d0af8e3 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/itemstack/ItemBuilder.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/itemstack/ItemBuilder.java @@ -277,12 +277,9 @@ public class ItemBuilder ItemBuilder newBuilder = new ItemBuilder(_mat); newBuilder.setTitle(_title); - - for (String lore : _lore) - { - newBuilder.addLore(lore); - } - + + _lore.forEach(newBuilder::addLore); + for (Map.Entry entry : _enchants.entrySet()) { newBuilder.addEnchantment(entry.getKey(), entry.getValue()); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/map/TeamMap.java b/Plugins/Mineplex.Core/src/mineplex/core/map/TeamMap.java new file mode 100644 index 000000000..d7336ae21 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/map/TeamMap.java @@ -0,0 +1,106 @@ +package mineplex.core.map; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.map.MapView; +import org.bukkit.map.MapView.Scale; + +public class TeamMap +{ + List _players; + final ItemStack _map; + + public TeamMap(List display, Location loc, Scale scale) + { + _players = display; + MapView view = Bukkit.createMap(loc.getWorld()); + view.setCenterX(loc.getBlockX()); + view.setCenterZ(loc.getBlockZ()); + view.setScale(scale); + + _map = new ItemStack(Material.MAP); + _map.setDurability(view.getId()); + } + + public void update(Player... forceRemove) + { + if (forceRemove != null) + { + for (Player remove : forceRemove) + { + _players.remove(remove); + } + } + + List confirmed = new ArrayList(); + + for (Player check : _players) + { + if (!UtilPlayer.isOnline(check.getName())) + continue; + + if (UtilPlayer.isSpectator(check)) + continue; + + confirmed.add(check); + } + + _players.clear(); + for (Player add : confirmed) + _players.add(add); + } + + public void giveMaps() + { + update(null); + + for (Player player : _players) + { + UtilInv.insert(player, _map); + UtilInv.Update(player); + } + } + + public void giveMap(Player player) + { + giveMap(player, true, ""); + } + + public void giveMap(Player player, boolean add, String displayName, String... lore) + { + if (!_players.contains(player)) + { + if (add) + { + _players.add(player); + } + } + + ItemStack map = _map.clone(); + ItemMeta im = map.getItemMeta(); + if (!displayName.equalsIgnoreCase("")) + im.setDisplayName(displayName); + + List lores = new ArrayList(); + for (String s : lore) + lores.add(s); + + if (!lores.isEmpty()) + im.setLore(lores); + + map.setItemMeta(im); + + UtilInv.insert(player, map); + UtilInv.Update(player); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java b/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java index 10b0c9707..8385f00a7 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/message/MessageManager.java @@ -26,7 +26,13 @@ import mineplex.core.friend.FriendManager; import mineplex.core.friend.data.FriendData; import mineplex.core.friend.data.FriendStatus; import mineplex.core.ignore.IgnoreManager; -import mineplex.core.message.commands.*; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.message.commands.AdminCommand; +import mineplex.core.message.commands.AnnounceCommand; +import mineplex.core.message.commands.MessageAdminCommand; +import mineplex.core.message.commands.MessageCommand; +import mineplex.core.message.commands.ResendAdminCommand; +import mineplex.core.message.commands.ResendCommand; import mineplex.core.message.redis.AnnouncementHandler; import mineplex.core.message.redis.MessageHandler; import mineplex.core.message.redis.RedisMessage; @@ -44,6 +50,8 @@ public class MessageManager extends MiniClientPlugin private CoreClientManager _clientManager; private FriendManager _friendsManager; private IgnoreManager _ignoreManager; + private IncognitoManager _incognitoManager; + private HashMap _messageTimeouts = new HashMap(); private PreferencesManager _preferences; private Punish _punish; @@ -51,11 +59,12 @@ public class MessageManager extends MiniClientPlugin private ArrayList _randomMessage; private String _serverName; - public MessageManager(JavaPlugin plugin, CoreClientManager clientManager, PreferencesManager preferences, + public MessageManager(JavaPlugin plugin, IncognitoManager incognitoManager, CoreClientManager clientManager, PreferencesManager preferences, IgnoreManager ignoreManager, Punish punish, FriendManager friendManager, Chat chat) { super("Message", plugin); - + + _incognitoManager = incognitoManager; _clientManager = clientManager; _preferences = preferences; _ignoreManager = ignoreManager; @@ -217,7 +226,7 @@ public class MessageManager extends MiniClientPlugin Get(from).LastToTime = System.currentTimeMillis(); // Chiss or defek7 - if (to.getName().equals("Chiss") || to.getName().equals("defek7") || to.getName().equals("Phinary") || to.getName().equals("fooify") || to.getName().equals("sampepere")) + if (to.getName().equals("Chiss") || to.getName().equals("defek7") || to.getName().equals("Phinary") || to.getName().equals("AlexTheCoder")) { UtilPlayer.message(from, C.cPurple + to.getName() + " is often AFK or minimized, due to plugin development."); UtilPlayer.message(from, C.cPurple + "Please be patient if he does not reply instantly."); @@ -462,10 +471,9 @@ public class MessageManager extends MiniClientPlugin { FriendData friends = _friendsManager.Get(sender); FriendStatus friend = null; - + if (!adminMessage) { - for (FriendStatus friendInfo : friends.getFriends()) { @@ -523,6 +531,12 @@ public class MessageManager extends MiniClientPlugin // If this is a message inside the server if (to != null) { + if (_incognitoManager.Get(to).Status) + { + UtilPlayer.message(sender, F.main("Online Player Search", F.elem("0") + " matches for [" + F.elem(target) + "].")); + return; + } + if (adminMessage) { DoMessageAdmin(sender, to, message); @@ -542,46 +556,69 @@ public class MessageManager extends MiniClientPlugin // If this is a admin message, or the sender isn't muted/ignoring the target if (adminMessage || canSenderMessageThem(sender, playerTarget)) { - // Construct the command to send to redis - RedisMessage globalMessage = new RedisMessage(_serverName, - - sender.getName(), - - adminMessage ? null : friend.ServerName, - - playerTarget, - - message, - - // Include the sender's rank if this is a admin message. So we can format the receivers chat. - adminMessage ? F.rank(_clientManager.Get(sender).GetRank()) : null); - - final UUID uuid = globalMessage.getUUID(); - - // A backup for the rare case where the message fails to deliver. Server doesn't respond - BukkitRunnable runnable = new BukkitRunnable() - { - public void run() + runAsync(new Runnable() { - _messageTimeouts.remove(uuid); - - // Inform the player that the message failed to deliver - UtilPlayer.message( - sender, - F.main((adminMessage ? "Admin " : "") + "Message", C.mBody + " Failed to send message to [" - + C.mElem + playerTarget + C.mBody + "].")); + @Override + public void run() + { + // TODO Newgarbo wrote this stuff inefficiently and for sake of time and thousands of players i'm going to just comment this out + /* + if (IncognitoManager.Instance.getRepository().GetStatus(playerTarget)) + { + UtilPlayer.message(sender, F.main("Online Player Search", F.elem("0") + " matches for [" + F.elem(target) + "].")); + return; + } + */ + + runSync(new Runnable() + { + public void run() + { + // Construct the command to send to redis + RedisMessage globalMessage = new RedisMessage(_serverName, + sender.getName(), + adminMessage ? null : friend.ServerName, + playerTarget, + message, + // Include the sender's rank if this is a admin message. So we can format the receivers chat. + adminMessage ? F.rank(_clientManager.Get(sender).GetRank()) : null); + + final UUID uuid = globalMessage.getUUID(); + + // A backup for the rare case where the message fails to deliver. Server doesn't respond + BukkitRunnable runnable = new BukkitRunnable() + { + public void run() + { + _messageTimeouts.remove(uuid); + + // Inform the player that the message failed to deliver + UtilPlayer.message( + sender, + F.main((adminMessage ? "Admin " : "") + "Message", C.mBody + " Failed to send message to [" + + C.mElem + playerTarget + C.mBody + "].")); + } + }; + + // This will activate in 2 seconds + runnable.runTaskLater(getPlugin(), 40); + + // The key is the UUID its trading between servers + _messageTimeouts.put(uuid, runnable); + + // Time to send the message! + globalMessage.publish(); + } + }); + } } - }; - - // This will activate in 2 seconds - runnable.runTaskLater(getPlugin(), 40); - - // The key is the UUID its trading between servers - _messageTimeouts.put(uuid, runnable); - - // Time to send the message! - globalMessage.publish(); + ); } } } + + public IncognitoManager getIncognitoManager() + { + return _incognitoManager; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AdminCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AdminCommand.java index f9c2242d1..d12470834 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AdminCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AdminCommand.java @@ -9,8 +9,8 @@ import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.message.MessageManager; -import mineplex.core.visibility.VisibilityManager; public class AdminCommand extends CommandBase { @@ -51,6 +51,11 @@ public class AdminCommand extends CommandBase { if (Plugin.GetClientManager().Get(to).GetRank().has(Rank.HELPER)) { + if (Plugin.getIncognitoManager().Get(to).Status) + { + continue; + } + if (!to.equals(caller)) UtilPlayer.message(to, F.rank(Plugin.GetClientManager().Get(caller).GetRank()) + " " + caller.getName() + " " + C.cPurple + message); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AnnounceCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AnnounceCommand.java index cbdddc228..d233056d0 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AnnounceCommand.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/message/commands/AnnounceCommand.java @@ -1,18 +1,15 @@ package mineplex.core.message.commands; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + import mineplex.core.command.CommandBase; import mineplex.core.common.Rank; -import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.message.MessageManager; import mineplex.serverdata.commands.AnnouncementCommand; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - public class AnnounceCommand extends CommandBase { public AnnounceCommand(MessageManager plugin) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/npc/NpcManager.java b/Plugins/Mineplex.Core/src/mineplex/core/npc/NpcManager.java index a94be37fe..87c84076d 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/npc/NpcManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/npc/NpcManager.java @@ -478,6 +478,17 @@ public class NpcManager extends MiniPlugin } } + public void addFakeNpc(Npc npc) + { + _npcs.add(npc); + } + + public void removeFakeNpc(Npc npc) + { + _npcs.remove(npc); + npc.getEntity().remove(); + } + public void loadNpcs() throws SQLException { String serverType = getServerName(); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/packethandler/PacketHandler.java b/Plugins/Mineplex.Core/src/mineplex/core/packethandler/PacketHandler.java index 44f2086be..5e76bf104 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/packethandler/PacketHandler.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/packethandler/PacketHandler.java @@ -87,7 +87,8 @@ public class PacketHandler extends MiniPlugin return _playerVerifierMap.get(player); } - public void addPacketHandler(IPacketHandler packetHandler, Class... packetsToListen) + @SafeVarargs + public final void addPacketHandler(IPacketHandler packetHandler, Class... packetsToListen) { if (packetsToListen.length == 0) { diff --git a/Plugins/Mineplex.Core/src/mineplex/core/personalServer/PersonalServerManager.java b/Plugins/Mineplex.Core/src/mineplex/core/personalServer/PersonalServerManager.java index 8f8e68dc9..ee40a0e6f 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/personalServer/PersonalServerManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/personalServer/PersonalServerManager.java @@ -131,7 +131,11 @@ public class PersonalServerManager extends MiniPlugin } if (eventServer) + { + ram = 4096; + cpu = 8; createGroup(player, "EVENT", ram, cpu, 40, 80, "Event", eventServer); + } else createGroup(player, serverName, ram, cpu, 40, 80, "Smash", eventServer); } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesManager.java b/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesManager.java index ae7f67755..9d6439e46 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/preferences/PreferencesManager.java @@ -4,20 +4,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map.Entry; -import mineplex.core.MiniDbClientPlugin; -import mineplex.core.account.CoreClientManager; -import mineplex.core.common.util.C; -import mineplex.core.common.util.NautHashMap; -import mineplex.core.common.util.UtilGear; -import mineplex.core.common.util.UtilInv; -import mineplex.core.donation.DonationManager; -import mineplex.core.itemstack.ItemStackFactory; -import mineplex.core.preferences.command.PreferencesCommand; -import mineplex.core.preferences.ui.ExclusivePreferencesShop; -import mineplex.core.preferences.ui.PreferencesShop; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; - import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -29,17 +15,35 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.MiniDbClientPlugin; +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.C; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.common.util.UtilGear; +import mineplex.core.common.util.UtilInv; +import mineplex.core.donation.DonationManager; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.itemstack.ItemStackFactory; +import mineplex.core.packethandler.PacketHandler; +import mineplex.core.preferences.command.PreferencesCommand; +import mineplex.core.preferences.ui.ExclusivePreferencesShop; +import mineplex.core.preferences.ui.PreferencesShop; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + public class PreferencesManager extends MiniDbClientPlugin { private PreferencesRepository _repository; private PreferencesShop _shop; private ExclusivePreferencesShop _exclusiveShop; + private IncognitoManager _incognitoManager; + private NautHashMap _saveBuffer = new NautHashMap(); public boolean GiveItem; - public PreferencesManager(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager) + public PreferencesManager(JavaPlugin plugin, IncognitoManager incognito, CoreClientManager clientManager, DonationManager donationManager) { super("Preferences", plugin, clientManager); @@ -47,6 +51,8 @@ public class PreferencesManager extends MiniDbClientPlugin _exclusiveShop = new ExclusivePreferencesShop(this, clientManager, donationManager); _shop = new PreferencesShop(this, clientManager, donationManager, _exclusiveShop); + _incognitoManager = incognito; + _exclusiveShop.setPreferencesShop(_shop); addCommand(new PreferencesCommand(this)); @@ -138,4 +144,9 @@ public class PreferencesManager extends MiniDbClientPlugin { return "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests, friendDisplayInventoryUI, clanTips, hubMusic, disableAds FROM accountPreferences WHERE accountPreferences.uuid = '" + uuid + "' LIMIT 1;"; } + + public IncognitoManager getIncognitoManager() + { + return _incognitoManager; + } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/preferences/ui/ExclusivePreferencesPage.java b/Plugins/Mineplex.Core/src/mineplex/core/preferences/ui/ExclusivePreferencesPage.java index 2cde41914..65f7d4b58 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/preferences/ui/ExclusivePreferencesPage.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/preferences/ui/ExclusivePreferencesPage.java @@ -8,6 +8,8 @@ import org.bukkit.event.inventory.ClickType; import mineplex.core.account.CoreClientManager; import mineplex.core.common.Rank; import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilUI; import mineplex.core.donation.DonationManager; import mineplex.core.preferences.PreferencesManager; @@ -149,6 +151,12 @@ public class ExclusivePreferencesPage extends ShopPageBase[] _resourcePackUrls; private boolean _resourcePackRequired; private NautHashMap _resourcePackUsers = new NautHashMap(); private NautHashMap _resourcePackNoResponse = new NautHashMap(); @@ -45,13 +47,32 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback ServerCommandManager.getInstance().registerCommandType("RedisUnloadResPack", RedisUnloadResPack.class, this); } + + public void setPlayerPack(Player player) + { + MinecraftVersion version = UtilPlayer.getVersion(player); + + if (_resourcePackUrls == null || _resourcePackUrls.length == 0) + return; + + for (Pair entry : _resourcePackUrls) + { + if (entry.getLeft() == version || entry.getLeft() == MinecraftVersion.ALL) + { + player.setResourcePack(entry.getRight()); + return; + } + } + + player.setResourcePack(_resourcePackUrls[0].getRight()); + } @EventHandler public void ResourcePackJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); - if (_resourcePackUrl == null) + if (_resourcePackUrls == null) { return; } @@ -62,7 +83,8 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback } _resourcePackUsers.put(player.getName(), false); - player.setResourcePack(_resourcePackUrl); + + setPlayerPack(player); } @EventHandler @@ -89,14 +111,15 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback // Send it again, enforce it! _resourcePackNoResponse.put(player.getName(), System.currentTimeMillis()); - player.setResourcePack(_resourcePackUrl); + + setPlayerPack(player); } } @EventHandler public void onResourcePackStatus(PlayerResourcePackStatusEvent event) { - if (_resourcePackUrl == null) + if (_resourcePackUrls == null) { return; } @@ -176,19 +199,19 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback returnHubNoResPack(player); } - public void setResourcePack(String resourcePack, boolean forceResourcePack) + public void setResourcePack(Pair[] resourcePack, boolean forceResourcePack) { - if (Objects.equal(resourcePack, _resourcePackUrl) && forceResourcePack == _resourcePackRequired) + if (Objects.equal(resourcePack, _resourcePackUrls) && forceResourcePack == _resourcePackRequired) { return; } _resourcePackNoResponse.clear(); _resourcePackUsers.clear(); - _resourcePackUrl = resourcePack == null || resourcePack.isEmpty() ? null : resourcePack; + _resourcePackUrls = resourcePack == null || (resourcePack.length == 0) ? null : resourcePack; _resourcePackRequired = forceResourcePack; - if (_resourcePackUrl == null || _resourcePackUrl.isEmpty()) + if (_resourcePackUrls == null || _resourcePackUrls.length == 0) { _resourcePackRequired = false; @@ -207,7 +230,8 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback } _resourcePackUsers.put(player.getName(), false); - player.setResourcePack(_resourcePackUrl); + + setPlayerPack(player); } } } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java b/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java index d2fe4c26e..31a6065c9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/shop/ShopBase.java @@ -36,7 +36,7 @@ public abstract class ShopBase implements Listene private NautHashMap _errorThrottling; private NautHashMap _purchaseBlock; - private List _availableCurrencyTypes; + private List _availableCurrencyTypes = new ArrayList(); private PluginType _plugin; private CoreClientManager _clientManager; @@ -57,8 +57,8 @@ public abstract class ShopBase implements Listene _errorThrottling = new NautHashMap(); _purchaseBlock = new NautHashMap(); - _availableCurrencyTypes = new ArrayList(); - _availableCurrencyTypes.addAll(Arrays.asList(currencyTypes)); + if (currencyTypes != null && currencyTypes.length > 0) + _availableCurrencyTypes.addAll(Arrays.asList(currencyTypes)); _plugin.registerEvents(this); } diff --git a/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ShopPageBase.java b/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ShopPageBase.java index 56fa078f7..e68b0c594 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ShopPageBase.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/shop/page/ShopPageBase.java @@ -23,15 +23,15 @@ import mineplex.core.shop.item.IButton; public abstract class ShopPageBase> extends CraftInventoryCustom implements Listener { - private PluginType _plugin; - private CoreClientManager _clientManager; - private DonationManager _donationManager; - private ShopType _shop; - private Player _player; - private CoreClient _client; - private CurrencyType _currencyType; - private NautHashMap _buttonMap; - private boolean _showCurrency = false; + protected PluginType _plugin; + protected CoreClientManager _clientManager; + protected DonationManager _donationManager; + protected ShopType _shop; + protected Player _player; + protected CoreClient _client; + protected CurrencyType _currencyType; + protected NautHashMap _buttonMap; + protected boolean _showCurrency = false; private int _currencySlot = 4; diff --git a/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackAPI.java b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackAPI.java new file mode 100644 index 000000000..9bce0f192 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackAPI.java @@ -0,0 +1,129 @@ +package mineplex.core.slack; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; + +import com.google.gson.JsonObject; +import mineplex.core.thread.ThreadPool; + +/** + * An API for sending and handling Slack messages. + */ +public class SlackAPI +{ + // Default emoji. + public static final String DEFAULT_ICON = ":mineplex:"; + + // Singular instance. + private static SlackAPI _instance; + + // Don't allow instantiation elsewhere. + private SlackAPI() {} + + /** + * Sends a message asynchronously to a Slack channel. + * + * @param team The team which contains the target channel. + * @param channel The target channel for the message. + * @param message The message to be displayed. + * @param customTitle Whether or not to use a custom title for the message. + * If false the default team title is used. + */ + public void sendMessage(SlackTeam team, String channel, SlackMessage message, boolean customTitle) + { + ThreadPool.ASYNC.execute(() -> + { + // Set message title. + if (!customTitle) + { + message.setUsername(team.getTitle()); + message.setIcon(DEFAULT_ICON); + } + + // Set message channel. + JsonObject msg = message.toJson(); + msg.addProperty("channel", channel); + + // Run the call. + runWebCall(team, msg); + }); + } + + /** + * Runs a web call to a specified Slack incoming-hook. + * + * @param team The team to run the call on. + * @param call The call to be run. + */ + private String runWebCall(SlackTeam team, JsonObject call) + { + HttpURLConnection connection = null; + try + { + // Create connection. + URL url = new URL(team.getURL()); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setConnectTimeout(5000); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + + // Setup payload. + String payload = "payload=" + URLEncoder.encode(call.toString(), "UTF-8"); + + // Send request. + DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); + dos.writeBytes(payload); + dos.flush(); + dos.close(); + + // Receive response. + InputStream is = connection.getInputStream(); + BufferedReader rd = new BufferedReader(new InputStreamReader(is)); + String line; + String response = ""; + while ((line = rd.readLine()) != null) + { + response += line + "\n"; + } + + rd.close(); + return response.toString(); + } + catch (Exception e) + { + e.printStackTrace(); + } + finally + { + if (connection != null) + { + // Terminate connection. + connection.disconnect(); + } + } + + return "500 Error"; + } + + /** + * Gets the singular instance of the Slack API. + * + * @return The {@link SlackAPI} instance. + */ + public static SlackAPI getInstance() + { + if (_instance == null) + { + _instance = new SlackAPI(); + } + + return _instance; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackMessage.java b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackMessage.java new file mode 100644 index 000000000..ad0ce7de4 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackMessage.java @@ -0,0 +1,139 @@ +package mineplex.core.slack; + +import com.google.gson.JsonObject; + +/** + * A message to be sent through the {@link SlackAPI}. + */ +public class SlackMessage +{ + private String _username; + private String _icon; + + private String _content; + + /** + * Class constructor. + * + * @param content The content of the message. + */ + public SlackMessage(String content) + { + _icon = SlackAPI.DEFAULT_ICON; + _content = content; + } + + /** + * Class constructor. + * + * @param username The username of the message. + * @param content The content of the message. + */ + public SlackMessage(String username, String content) + { + _username = username; + _icon = SlackAPI.DEFAULT_ICON; + _content = content; + } + + /** + * Class constructor. + * + * @param username The username of the message. + * @param icon The icon/emoji of the message. + * @param content The content of the message. + */ + public SlackMessage(String username, String icon, String content) + { + _username = username; + _icon = ":" + icon + ":"; + _content = content; + } + + /** + * Converts the message to JSON format. + * + * @return The {@link SlackMessage} in the form of a {@link JsonObject}. + */ + public JsonObject toJson() + { + JsonObject msg = new JsonObject(); + + if (_username != null) + { + msg.addProperty("username", _username); + } + + if (_icon != null) + { + msg.addProperty("icon_emoji", _icon); + } + + if (_content != null) + { + msg.addProperty("text", _content); + } + + return msg; + } + + /** + * Gets the username that displays as a title. + * + * @return The username in use. + */ + public String getUsername() + { + return _username; + } + + /** + * Sets the username that displays as a title. + * + * @param username The username to use. + */ + public void setUsername(String username) + { + _username = username; + } + + /** + * Gets the icon that displays with the title. + * + * @return The icon in use. + */ + public String getIcon() + { + return _icon; + } + + /** + * Sets the icon that displays with the title. + * + * @param icon The icon to use. + */ + public void setIcon(String icon) + { + _icon = icon; + } + + /** + * Gets the content of the message. + * + * @return The content of the message. + */ + public String getContent() + { + return _content; + } + + /** + * Sets the content of the message. + * + * @param content The content of the message. + */ + public void setContent(String content) + { + _content = content; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackTeam.java b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackTeam.java new file mode 100644 index 000000000..965346791 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/slack/SlackTeam.java @@ -0,0 +1,79 @@ +package mineplex.core.slack; + +/** + * An enumeration of Mineplex Slack teams. + */ +public enum SlackTeam +{ + // Dev team - mineplex.slack.com + DEVELOPER("Mineplex Dev", "T045RUM7F", "B0VK6GFKN", "6GxwJsDfEpbVnQl8pYuEyq5T"), + + // QA team - mineplexqa.slack.com + QA("Mineplex QA", "todo", "todo", "todo"), // TODO: new details + + ; + + private String _title; + private String _id1; + private String _id2; + private String _token; + + SlackTeam(String title, String id1, String id2, String token) + { + _title = title; + _id1 = id1; + _id2 = id2; + _token = token; + } + + /** + * Gets the title that will be displayed that the top of each + * {@link SlackMessage}. + * + * @return The title of this team. + */ + public String getTitle() + { + return _title; + } + + /** + * Gets the first ID of this Slack team. + * + * @return The individual first ID. + */ + public String getId1() + { + return _id1; + } + + /** + * Gets the second ID of this Slack team. + * + * @return The individual second ID. + */ + public String getId2() + { + return _id2; + } + + /** + * Gets the token key of this Slack team. + * + * @return The individual and secret token. + */ + public String getToken() + { + return _token; + } + + /** + * Gets the web hook in the form of a URL. + * + * @return The URL as a string. + */ + public String getURL() + { + return "https://hooks.slack.com/services/" + getId1() + "/" + getId2() + "/" + getToken(); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsManager.java b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsManager.java index ae88b6cb1..8c2bc5e06 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/stats/StatsManager.java @@ -294,6 +294,8 @@ public class StatsManager extends MiniDbClientPlugin }); } + + public int getStatId(String statName) { return _stats.get(statName); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/task/TaskManager.java b/Plugins/Mineplex.Core/src/mineplex/core/task/TaskManager.java index 85608613e..0427cb53e 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/task/TaskManager.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/task/TaskManager.java @@ -118,7 +118,7 @@ public class TaskManager extends MiniDbClientPlugin { public void run(Boolean success) { - if (!success) + if (!success.booleanValue()) { System.out.println("Add task FAILED for " + player.getName()); diff --git a/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/TextTutorialManager.java b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/TextTutorialManager.java new file mode 100644 index 000000000..57c4d924c --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/TextTutorialManager.java @@ -0,0 +1,154 @@ +package mineplex.core.texttutorial; + +import java.util.HashSet; +import java.util.Iterator; + +import org.bukkit.Sound; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.C; +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.donation.DonationManager; +import mineplex.core.task.TaskManager; +import mineplex.core.texttutorial.tutorial.Tutorial; +import mineplex.core.texttutorial.tutorial.TutorialData; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + +public class TextTutorialManager extends MiniPlugin +{ + private DonationManager _donationManager; + private TaskManager _taskManager; + + private HashSet _tutorials; + + public TextTutorialManager(JavaPlugin plugin, DonationManager donationManager, TaskManager taskManager) + { + super("Text Tutorial", plugin); + + _donationManager = donationManager; + _taskManager = taskManager; + } + + @EventHandler + public void startTutorial(PlayerInteractEntityEvent event) + { + if (isInTutorial(event.getPlayer())) + return; + + if (!(event.getRightClicked() instanceof LivingEntity)) + return; + + LivingEntity ent = (LivingEntity)event.getRightClicked(); + + String name = ent.getCustomName(); + if (name == null) + return; + + for (Tutorial tut : _tutorials) + { + if (name.contains(tut.getName())) + { + UtilPlayer.message(event.getPlayer(), F.main("Tutorial", "You started " + F.elem(tut.getName()) + ".")); + tut.startTutorial(event.getPlayer()); + return; + } + } + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + for (final Tutorial tut : _tutorials) + { + Iterator iterator = tut.getTutorialDatas().iterator(); + while (iterator.hasNext()) + { + TutorialData data = iterator.next(); + final Player player = data.getPlayer(); + + //Check if Phase Completed + if (data.tick()) + { + //Next Phase + if (data.getPhaseStep() < tut.getPhaseSize()) + { + data.setNextPhase(tut.getPhase(data.getPhaseStep())); + } + //End Tutorial + else + { + iterator.remove(); + + //Inform + UtilPlayer.message(player, F.main("Tutorial", "You completed " + F.elem(tut.getName()) + ".")); + + //Gems + if (tut.getGemReward() > 0) + { + if (!_taskManager.hasCompletedTask(player, tut.getTaskId())) + { + _taskManager.completedTask(new Callback() + { + public void run(Boolean completed) + { + _donationManager.RewardGems(new Callback() + { + public void run(Boolean completed) + { + if (completed) + { + UtilPlayer.message(player, F.main("Tutorial", "You received " + F.elem(C.cGreen + tut.getGemReward() + " Gems") + ".")); + + //Sound + player.playSound(player.getLocation(), Sound.LEVEL_UP, 2f, 1.5f); + } + } + }, "Tutorial " + tut.getName(), player.getName(), player.getUniqueId(), tut.getGemReward()); + } + }, player, tut.getTaskId()); + } + } + } + } + } + } + } + + @EventHandler + public void playerQuit(PlayerQuitEvent event) + { + for (Tutorial tut : _tutorials) + tut.stopTutorial(event.getPlayer()); + } + + @EventHandler + public void cancelInteract(PlayerInteractEvent event) + { + if (isInTutorial(event.getPlayer())) + event.setCancelled(true); + } + + public boolean isInTutorial(Player player) + { + for (Tutorial tutorial : _tutorials) + { + if (tutorial.isInTutorial(player)) + return true; + } + + return false; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Phase.java b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Phase.java new file mode 100644 index 000000000..7cd9a80a9 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Phase.java @@ -0,0 +1,47 @@ +package mineplex.core.texttutorial.tutorial; + +import org.bukkit.Location; + +public class Phase +{ + private Location _location; + private String _header; + private String[] _text; + + public Phase(Location location, String header, String[] text) + { + _location = location; + _header = header; + _text = text; + } + + public Location getLocation() + { + return _location; + } + + public void setLocation(Location location) + { + _location = location; + } + + public String getHeader() + { + return _header; + } + + public void setHeader(String header) + { + _header = header; + } + + public String[] getText() + { + return _text; + } + + public void setText(String[] text) + { + _text = text; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Tutorial.java b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Tutorial.java new file mode 100644 index 000000000..362139c9c --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/Tutorial.java @@ -0,0 +1,74 @@ +package mineplex.core.texttutorial.tutorial; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + +import org.bukkit.entity.Player; + +public abstract class Tutorial +{ + private String _name; + private String _taskId; + private int _gemReward; + + private ArrayList _phases; + private HashMap _playerMap; + + public Tutorial(String name, String taskId, int gemReward) + { + _name = name; + _taskId = taskId; + _gemReward = gemReward; + } + + public String getName() + { + return _name; + } + + public String getTaskId() + { + return _taskId; + } + + public void startTutorial(Player player) + { + _playerMap.put(player, new TutorialData(player, _phases.get(0))); + } + + public void stopTutorial(Player player) + { + _playerMap.remove(player); + } + + public boolean isInTutorial(Player player) + { + return _playerMap.containsKey(player); + } + + protected void addPhase(Phase phase) + { + _phases.add(phase); + } + + public Collection getTutorialDatas() + { + return _playerMap.values(); + } + + public Phase getPhase(int phaseIndex) + { + return _phases.get(phaseIndex); + } + + public int getPhaseSize() + { + return _phases.size(); + } + + public int getGemReward() + { + return _gemReward; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/TutorialData.java b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/TutorialData.java new file mode 100644 index 000000000..fdad7738f --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/texttutorial/tutorial/TutorialData.java @@ -0,0 +1,102 @@ +package mineplex.core.texttutorial.tutorial; + +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; + +public class TutorialData +{ + private Player _player; + private Phase _phase; + private int _phaseStep; + private int _textStep; + private long _sleep; + + public TutorialData(Player player, Phase startPhase) + { + _player = player; + _phase = startPhase; + _phaseStep = 0; + _textStep = 0; + _sleep = System.currentTimeMillis() + 3000; + } + + public boolean tick() + { + if (!_player.getLocation().equals(_phase.getLocation())) + _player.teleport(_phase.getLocation()); + + if (System.currentTimeMillis() < _sleep) + return false; + + if (_textStep >= _phase.getText().length) + { + // No more text to display, move to next phase + _phaseStep++; + _sleep = System.currentTimeMillis() + 2000; + + return true; + } + + // Display Text + String text = _phase.getText()[_textStep]; + + UtilPlayer.message(_player, " "); + UtilPlayer.message(_player, " "); + UtilPlayer.message(_player, " "); + UtilPlayer.message(_player, C.cGreen + C.Strike + C.Bold + "========================================"); + UtilPlayer.message(_player, C.cGold + C.Bold + _phase.getHeader()); + UtilPlayer.message(_player, " "); + + for (int i=0 ; i<=_textStep ; i++) + UtilPlayer.message(_player, " " + _phase.getText()[i]); + + for (int i=_textStep ; i<=5 ; i++) + UtilPlayer.message(_player, " "); + + UtilPlayer.message(_player, C.cGreen + C.Strike + C.Bold + "========================================"); + + if (text.length() > 0) + { + _player.playSound(_player.getLocation(), Sound.ORB_PICKUP, 2f, 1.5f); + _sleep = System.currentTimeMillis() + 1000 + (50*text.length()); + } + else + { + _sleep = System.currentTimeMillis() + 600; + } + + _textStep++; + + return false; + } + + public void setNextPhase(Phase phase) + { + _phase = phase; + _textStep = 0; + _player.teleport(_phase.getLocation()); + } + + public Phase getPhase() + { + return _phase; + } + + public long getSleep() + { + return _sleep; + } + + public int getPhaseStep() + { + return _phaseStep; + } + + public Player getPlayer() + { + return _player; + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/thread/ThreadPool.java b/Plugins/Mineplex.Core/src/mineplex/core/thread/ThreadPool.java new file mode 100644 index 000000000..7e9af44b1 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/thread/ThreadPool.java @@ -0,0 +1,19 @@ +package mineplex.core.thread; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; + +/** + * A collection of threads for different uses. + */ +public class ThreadPool +{ + + // Async Thread + public static ExecutorService ASYNC = Executors.newCachedThreadPool( + new ThreadFactoryBuilder().setNameFormat("MiniPlugin Async %1$d").build() + ); + +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/DebugShopCommand.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/DebugShopCommand.java new file mode 100644 index 000000000..c7b3a9bae --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/DebugShopCommand.java @@ -0,0 +1,20 @@ +package mineplex.core.tournament; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; + +public class DebugShopCommand extends CommandBase +{ + public DebugShopCommand(TournamentManager plugin) + { + super(plugin, Rank.ALL, "ots"); + } + + @Override + public void Execute(Player caller, String[] args) + { + Plugin.openShop(caller); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentManager.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentManager.java new file mode 100644 index 000000000..d5bdf1a0b --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentManager.java @@ -0,0 +1,139 @@ +package mineplex.core.tournament; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.UUID; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scoreboard.Team; + +import mineplex.core.MiniDbClientPlugin; +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.F; +import mineplex.core.donation.DonationManager; +import mineplex.core.recharge.Recharge; +import mineplex.core.tournament.data.ClientTournamentData; +import mineplex.core.tournament.data.Tournament; +import mineplex.core.tournament.data.TournamentInviteStatus; +import mineplex.core.tournament.data.TournamentParticipant; +import mineplex.core.tournament.data.TournamentTeam; +import mineplex.core.tournament.ui.TournamentShop; + +public class TournamentManager extends MiniDbClientPlugin +{ + private TournamentRepository _repository; + private TournamentShop _shop; + private HashSet _tournaments = new HashSet<>(); + + public TournamentManager(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager) + { + super("Tournament Manager", plugin, clientManager); + + _repository = new TournamentRepository(plugin); + _shop = new TournamentShop(this, clientManager, donationManager); + addCommand(new DebugShopCommand(this)); + _tournaments = _repository.getTournaments(); + } + + @Override + public String getQuery(int accountId, String uuid, String name) + { + return "SELECT TT.id, TT.tournamentId, accounts.id, accounts.uuid, accounts.name, TT.status FROM tournamentTeams AS TT INNER JOIN accounts ON accounts.id = TT.accountId WHERE TT.accountId = " + accountId + ";"; + } + + @Override + public void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException + { + ClientTournamentData clientData = Get(playerName); + + while (resultSet.next()) + { + int teamId = resultSet.getInt(1); + int tournamentId = resultSet.getInt(2); + int id = resultSet.getInt(3); + String uuid = resultSet.getString(4); + String name = resultSet.getString(5); + String status = resultSet.getString(6); + + if (!clientData.Tournaments.containsKey(tournamentId)) + { + clientData.Tournaments.put(tournamentId, new Tournament()); + } + + Tournament tournament = clientData.Tournaments.get(tournamentId); + + if (!tournament.Teams.containsKey(teamId)) + { + tournament.Teams.put(teamId, new TournamentTeam()); + } + + TournamentTeam team = tournament.Teams.get(teamId); + TournamentParticipant participant = new TournamentParticipant(); + participant.Name = name; + participant.Uuid = UUID.fromString(uuid); + participant.Status = Enum.valueOf(TournamentInviteStatus.class, status); + + team.Members.put(id, participant); + } + } + + @Override + protected ClientTournamentData AddPlayer(String player) + { + return new ClientTournamentData(); + } + + public void openShop(Player player) + { + _shop.attemptShopOpen(player); + } + + public HashSet getTournaments() + { + return _tournaments; + } + + public void registerForTournament(Player player, Tournament tournament, Runnable runnable) + { + if (!Recharge.Instance.use(player, "Tournament Registration", 1000, true, false)) + return; + + runAsync(new Runnable() + { + @Override + public void run() + { + int teamId = _repository.registerForTournament(getClientManager().getAccountId(player), tournament.TournamentId); + + runSync(new Runnable() + { + @Override + public void run() + { + if (teamId != -1) + { + player.sendMessage(F.main(getName(), "You have successfully registered for " + tournament.Name + " tournament!")); + + TournamentTeam team = new TournamentTeam(); + TournamentParticipant participant = new TournamentParticipant(); + participant.Name = player.getName(); + participant.Uuid = player.getUniqueId(); + participant.Status = TournamentInviteStatus.OWNER; + + team.Members.put(getClientManager().getAccountId(player), participant); + tournament.Teams.put(teamId, team); + } + else + { + player.sendMessage(F.main(getName(), "There was an error registering you for " + tournament.Name + " tournament. Please try again later.")); + } + + runnable.run(); + } + }); + } + }); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentRepository.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentRepository.java new file mode 100644 index 000000000..115d2855d --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/TournamentRepository.java @@ -0,0 +1,92 @@ +package mineplex.core.tournament; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.database.MinecraftRepository; +import mineplex.core.tournament.data.Tournament; +import mineplex.core.tournament.data.TournamentInviteStatus; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.ResultSetCallable; +import mineplex.serverdata.database.column.ColumnInt; +import mineplex.serverdata.database.column.ColumnVarChar; + +public class TournamentRepository extends MinecraftRepository +{ + private static String REGISTER_FOR_TOURNAMENT = "INSERT INTO tournamentTeams(accountId, tournamentId, status) VALUES (?, ?, ?);"; + private static String UNREGISTER_FOR_TOURNAMENT = "DELETE FROM TTI FROM tournamentTeamInvites AS TTI INNER JOIN tournamentTeams AS TT ON TT.id = TTI.teamId WHERE TTI.accountId = ? AND TT.tournamentId = ?;"; + private static String UNREGISTER_TEAM_FOR_TOURNAMENT = "DELETE FROM tournamentTeams WHERE accountId = ? AND tournamentId = ?;"; + private static String RETRIEVE_ALL_TOURNAMENTS = "SELECT * FROM tournaments;"; + + public TournamentRepository(JavaPlugin plugin) + { + super(plugin, DBPool.getAccount()); + } + + public int registerForTournament(int accountId, int tournamentId) + { + List teamId = new ArrayList<>(); + + executeInsert(REGISTER_FOR_TOURNAMENT, new ResultSetCallable() + { + @Override + public void processResultSet(ResultSet resultSet) throws SQLException + { + if (resultSet.next()) + { + teamId.add(resultSet.getInt(1)); + } + } + }, new ColumnInt("accountId", accountId), + new ColumnInt("tournamentId", tournamentId), + new ColumnVarChar("status", 11, TournamentInviteStatus.OWNER.toString())); + + return teamId.size() > 0 ? teamId.get(0) : -1; + } + + public boolean unregisterFromTeam(int accountId, int tournamentId, int teamId) + { + return executeUpdate(UNREGISTER_FOR_TOURNAMENT, new ColumnInt("accountId", accountId), new ColumnInt("tournamentId", tournamentId), new ColumnInt("teamId", teamId)) > 0; + } + + public boolean unregisterTeamFromTournament(int accountId, int tournamentId) + { + return executeUpdate(UNREGISTER_TEAM_FOR_TOURNAMENT, new ColumnInt("accountId", accountId), new ColumnInt("tournamentId", tournamentId)) > 0; + } + + public HashSet getTournaments() + { + HashSet tournaments = new HashSet<>(); + + executeQuery(RETRIEVE_ALL_TOURNAMENTS, new ResultSetCallable() + { + @Override + public void processResultSet(ResultSet resultSet) throws SQLException + { + while (resultSet.next()) + { + Tournament tournament = new Tournament(); + tournament.TournamentId = resultSet.getInt(1); + tournament.Name = resultSet.getString(2); + tournament.Date = resultSet.getTimestamp(3).getTime(); + tournament.GameType = resultSet.getString(4); + + tournaments.add(tournament); + } + } + }); + + return tournaments; + } + + @Override + protected void initialize() { } + + @Override + protected void update() { } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/ClientTournamentData.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/ClientTournamentData.java new file mode 100644 index 000000000..9270bf354 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/ClientTournamentData.java @@ -0,0 +1,8 @@ +package mineplex.core.tournament.data; + +import mineplex.core.common.util.NautHashMap; + +public class ClientTournamentData +{ + public NautHashMap Tournaments = new NautHashMap<>(); +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/Tournament.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/Tournament.java new file mode 100644 index 000000000..25e2439e4 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/Tournament.java @@ -0,0 +1,13 @@ +package mineplex.core.tournament.data; + +import mineplex.core.common.util.NautHashMap; + +public class Tournament +{ + public int TournamentId = -1; + public String Name; + public String GameType; + public long Date = 0; + public NautHashMap Teams = new NautHashMap<>(); + +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentInviteStatus.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentInviteStatus.java new file mode 100644 index 000000000..c21f6af0b --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentInviteStatus.java @@ -0,0 +1,9 @@ +package mineplex.core.tournament.data; + +public enum TournamentInviteStatus +{ + INVITED, + ACCEPTED, + DENIED, + OWNER +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentParticipant.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentParticipant.java new file mode 100644 index 000000000..5054f50e6 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentParticipant.java @@ -0,0 +1,10 @@ +package mineplex.core.tournament.data; + +import java.util.UUID; + +public class TournamentParticipant +{ + public UUID Uuid = null; + public String Name; + public TournamentInviteStatus Status; +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentTeam.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentTeam.java new file mode 100644 index 000000000..84b1cee81 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/data/TournamentTeam.java @@ -0,0 +1,8 @@ +package mineplex.core.tournament.data; + +import mineplex.core.common.util.NautHashMap; + +public class TournamentTeam +{ + public NautHashMap Members = new NautHashMap<>(); +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/TournamentShop.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/TournamentShop.java new file mode 100644 index 000000000..603960ec8 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/TournamentShop.java @@ -0,0 +1,25 @@ +package mineplex.core.tournament.ui; + +import org.bukkit.entity.Player; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.CurrencyType; +import mineplex.core.donation.DonationManager; +import mineplex.core.shop.ShopBase; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.core.tournament.TournamentManager; +import mineplex.core.tournament.ui.page.MainMenu; + +public class TournamentShop extends ShopBase +{ + public TournamentShop(TournamentManager plugin, CoreClientManager clientManager, DonationManager donationManager) + { + super(plugin, clientManager, donationManager, "Tournaments", CurrencyType.Gems); + } + + @Override + protected ShopPageBase> buildPagesFor(Player player) + { + return new MainMenu(getPlugin(), this, getClientManager(), getDonationManager(), player); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/MainMenu.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/MainMenu.java new file mode 100644 index 000000000..92193fac9 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/MainMenu.java @@ -0,0 +1,57 @@ +package mineplex.core.tournament.ui.page; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.donation.DonationManager; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.shop.item.IButton; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.core.tournament.TournamentManager; +import mineplex.core.tournament.ui.TournamentShop; + +public class MainMenu extends ShopPageBase +{ + private static IButton _friendsButton = null; + private static IButton _tournamentsButton = null; + + public MainMenu(TournamentManager plugin, TournamentShop shop, CoreClientManager clientManager, DonationManager donationManager, Player player) + { + super(plugin, shop, clientManager, donationManager, "Tournament Menu", player, 9); + + if (_friendsButton == null) + { + _friendsButton = new IButton() + { + @Override + public void onClick(Player player, ClickType clickType) + { + shop.openPageForPlayer(player, new SoloTournamentMenu(plugin, shop, clientManager, donationManager, player)); + } + }; + } + + if (_tournamentsButton == null) + { + _tournamentsButton = new IButton() + { + @Override + public void onClick(Player player, ClickType clickType) + { + shop.openPageForPlayer(player, new TournamentsMenu(plugin, shop, clientManager, donationManager, player)); + } + }; + } + + buildPage(); + } + + @Override + protected void buildPage() + { + addButton(0, new ItemBuilder(Material.SKULL_ITEM, 1, (short) 3).setTitle("Friends").build(), _friendsButton); + addButton(1, new ItemBuilder(Material.CHEST, 1).setTitle("Tournaments").build(), _tournamentsButton); + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/SoloTournamentMenu.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/SoloTournamentMenu.java new file mode 100644 index 000000000..e46b12d23 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/SoloTournamentMenu.java @@ -0,0 +1,24 @@ +package mineplex.core.tournament.ui.page; + +import org.bukkit.entity.Player; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.donation.DonationManager; +import mineplex.core.shop.ShopBase; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.core.tournament.TournamentManager; +import mineplex.core.tournament.ui.TournamentShop; + +public class SoloTournamentMenu extends ShopPageBase +{ + public SoloTournamentMenu(TournamentManager plugin, TournamentShop shop, CoreClientManager clientManager, DonationManager donationManager, Player player) + { + super(plugin, shop, clientManager, donationManager, "Solo Tournaments", player); + } + + @Override + protected void buildPage() + { + + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/TournamentsMenu.java b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/TournamentsMenu.java new file mode 100644 index 000000000..c3917e296 --- /dev/null +++ b/Plugins/Mineplex.Core/src/mineplex/core/tournament/ui/page/TournamentsMenu.java @@ -0,0 +1,107 @@ +package mineplex.core.tournament.ui.page; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.donation.DonationManager; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.shop.item.IButton; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.core.tournament.TournamentManager; +import mineplex.core.tournament.data.Tournament; +import mineplex.core.tournament.ui.TournamentShop; +import net.md_5.bungee.api.ChatColor; + +public class TournamentsMenu extends ShopPageBase +{ + private static Calendar _calendar = Calendar.getInstance(); + + private static SimpleDateFormat _tournamentStart = new SimpleDateFormat("h:mma z"); + private static SimpleDateFormat _tournamentCountdown = new SimpleDateFormat("h:mm:ss"); + + public TournamentsMenu(TournamentManager plugin, TournamentShop shop, CoreClientManager clientManager, DonationManager donationManager, Player player) + { + super(plugin, shop, clientManager, donationManager, "Tournament Calender", player, 45); + + buildPage(); + } + + @Override + protected void buildPage() + { + NautHashMap tournamentDateMap = new NautHashMap<>(); + + for (Tournament tournament : getPlugin().getTournaments()) + { + _calendar.setTime(new Date(tournament.Date)); + + tournamentDateMap.put(_calendar.get(Calendar.DAY_OF_MONTH), tournament); + } + + int currentDayOfMonth = _calendar.get(Calendar.DAY_OF_MONTH); + int maxDaysThisMonth = _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + + _calendar.set(Calendar.DAY_OF_MONTH, 1); + int startDayOfMonth = _calendar.get(Calendar.DAY_OF_WEEK); + int slot = startDayOfMonth; + + for (int i=1; i <= maxDaysThisMonth; i++) + { + if ((slot + 1) % 9 == 0) + slot += 2; + + if (tournamentDateMap.containsKey(i)) + { + final Tournament tournament = tournamentDateMap.get(i); + boolean registered = getPlugin().Get(getPlayer()).Tournaments.containsKey(tournament.TournamentId); + + addButton(slot, new ItemBuilder(Material.PAPER, i).setTitle(ChatColor.RESET + "" + ChatColor.BOLD + ChatColor.GOLD + tournament.Name).setLore + ( + ChatColor.GRAY + tournament.GameType, " ", + ChatColor.WHITE + "Take part in a super competitive", + ChatColor.WHITE + "tournament between all kinds of", + ChatColor.WHITE + "people in the Mineplex community!", + registered ? ChatColor.GREEN + "" + ChatColor.BOLD + "You are registered for this tournament!" : " ", + ChatColor.GRAY + "Time: " + ChatColor.YELLOW + _tournamentStart.format(new Date(tournament.Date)), + ChatColor.GRAY + "Countdown: " + ChatColor.LIGHT_PURPLE + _tournamentCountdown.format(new Date(tournament.Date - System.currentTimeMillis())) + ).build(), !registered ? new IButton() + { + @Override + public void onClick(Player player, ClickType clickType) + { + getPlugin().registerForTournament(player, tournament, new Runnable() + { + @Override + public void run() + { + buildPage(); + } + }); + } + } : null); + } + else + { + /* + if (i == currentDayOfMonth) + addItem(slot, new ItemBuilder(Material.STAINED_GLASS_PANE, i, (byte)5).setTitle("TODAY.").build()); + else + */ + addItem(slot, new ItemBuilder(Material.STAINED_GLASS_PANE, i, (byte)14).setTitle(ChatColor.RESET + "" + ChatColor.BOLD + ChatColor.RED + "No Events").setLore + ( + ChatColor.GRAY + "Sorry, there are no events", + ChatColor.GRAY + "on this particular date." + ).build()); + } + + slot++; + } + } +} diff --git a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureLocation.java b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureLocation.java index 2c48bea27..d74defe01 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureLocation.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/treasure/TreasureLocation.java @@ -4,6 +4,7 @@ import java.util.List; import mineplex.core.account.CoreClientManager; import mineplex.core.common.util.C; +import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilAlg; @@ -101,12 +102,6 @@ public class TreasureLocation implements Listener return; } - if (!chargeAccount(player, treasureType)) - { - player.sendMessage(F.main("Treasure", "You dont have any chests to open!")); - return; - } - TreasureStartEvent event = new TreasureStartEvent(player); Bukkit.getPluginManager().callEvent(event); @@ -115,48 +110,73 @@ public class TreasureLocation implements Listener return; } - // Treasure is now being opened - setHoloChestVisible(false); - - if (treasureType == TreasureType.ANCIENT) - Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening an " + treasureType.getName())); - - if (treasureType == TreasureType.MYTHICAL) - Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + treasureType.getName())); - - if (treasureType == TreasureType.CHRISTMAS) - Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + treasureType.getName())); - - Reward[] rewards = _treasureManager.getRewards(player, treasureType.getRewardPool(), treasureType.getRewardType()); - Treasure treasure = new Treasure(player, rewards, treasureType.getRewardType(), _chestBlock, _chestSpawns, treasureType, _treasureManager.getBlockRestore(), _hologramManager, _statusManager); - _currentTreasure = treasure; - - UtilTextMiddle.display(treasureType.getName(), "Choose 4 Chests To Open", 20, 180, 20, player); - UtilPlayer.message(player, F.main("Treasure", "Choose 4 Chests To Open")); - - Location teleportLocation = treasure.getCenterBlock().getLocation().add(0.5, 0, 0.5); - teleportLocation.setPitch(player.getLocation().getPitch()); - teleportLocation.setYaw(player.getLocation().getYaw()); - - for (Entity entity : player.getNearbyEntities(3, 3, 3)) + chargeAccount(player, treasureType, new Callback() { - UtilAction.velocity(entity, UtilAlg.getTrajectory(entity.getLocation(), treasure.getCenterBlock().getLocation()).multiply(-1), 1.5, true, 0.8, 0, 1.0, true); - } + @Override + public void run(Boolean success) + { + if (!success) + { + player.sendMessage(F.main("Treasure", "You dont have any chests to open!")); + } + else + { + if (isTreasureInProgress()) + { + // Need to check again because of callback. Add item back + player.sendMessage(F.main("Treasure", "Please wait for the current chest to be opened")); + _inventoryManager.addItemToInventory(player, treasureType.getItemName(), 1); + return; + } - player.teleport(teleportLocation); + // Treasure is now being opened + setHoloChestVisible(false); - _treasureManager.addOpenStat(player, treasureType); + if (treasureType == TreasureType.ANCIENT) + Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening an " + treasureType.getName())); + + if (treasureType == TreasureType.MYTHICAL) + Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + treasureType.getName())); + + if (treasureType == TreasureType.CHRISTMAS) + Bukkit.broadcastMessage(F.main("Treasure", F.name(player.getName()) + " is opening a " + treasureType.getName())); + + Reward[] rewards = _treasureManager.getRewards(player, treasureType.getRewardPool(), treasureType.getRewardType()); + Treasure treasure = new Treasure(player, rewards, treasureType.getRewardType(), _chestBlock, _chestSpawns, treasureType, _treasureManager.getBlockRestore(), _hologramManager, _statusManager); + _currentTreasure = treasure; + + UtilTextMiddle.display(treasureType.getName(), "Choose 4 Chests To Open", 20, 180, 20, player); + UtilPlayer.message(player, F.main("Treasure", "Choose 4 Chests To Open")); + + Location teleportLocation = treasure.getCenterBlock().getLocation().add(0.5, 0, 0.5); + teleportLocation.setPitch(player.getLocation().getPitch()); + teleportLocation.setYaw(player.getLocation().getYaw()); + + for (Entity entity : player.getNearbyEntities(3, 3, 3)) + { + UtilAction.velocity(entity, UtilAlg.getTrajectory(entity.getLocation(), treasure.getCenterBlock().getLocation()).multiply(-1), 1.5, true, 0.8, 0, 1.0, true); + } + + player.teleport(teleportLocation); + + _treasureManager.addOpenStat(player, treasureType); + } + } + }); } - private boolean chargeAccount(Player player, TreasureType treasureType) + private void chargeAccount(Player player, TreasureType treasureType, Callback callback) { int itemCount = _inventoryManager.Get(player).getItemCount(treasureType.getItemName()); if (itemCount > 0) { - _inventoryManager.addItemToInventory(player, treasureType.getItemName(), -1); - return true; + // Should always handle the callback for us + _inventoryManager.addItemToInventory(callback, player, treasureType.getItemName(), -1); + } + else + { + callback.run(false); } - return false; } private void setHoloChestVisible(boolean visible) diff --git a/Plugins/Mineplex.Core/src/mineplex/core/updater/UpdateType.java b/Plugins/Mineplex.Core/src/mineplex/core/updater/UpdateType.java index 52d63e2a1..68f1634b9 100644 --- a/Plugins/Mineplex.Core/src/mineplex/core/updater/UpdateType.java +++ b/Plugins/Mineplex.Core/src/mineplex/core/updater/UpdateType.java @@ -53,9 +53,13 @@ public enum UpdateType */ SLOWEST(32000), /** - * ONce every 30 seconds + * Once every 30 seconds */ SEC_30(30000), + /** + * Once every 20 seconds + */ + SEC_20(20000), /** * Once every 16 seconds */ @@ -64,6 +68,10 @@ public enum UpdateType * Once every 8 seconds */ SEC_08(8000), + /** + * Once every 5 seconds + */ + SEC_05(5000), /** * Once every 4 seconds */ diff --git a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/ClanRepository.java b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/ClanRepository.java index 8e2068a2d..229ebaacf 100644 --- a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/ClanRepository.java +++ b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/ClanRepository.java @@ -44,9 +44,9 @@ public class ClanRepository extends MinecraftRepository private static String CREATE_CLAN_TERRITORY_TABLE = "CREATE TABLE IF NOT EXISTS clanTerritory (id INT NOT NULL AUTO_INCREMENT, clanId INT, chunk VARCHAR(100), safe BIT(1), PRIMARY KEY (id), FOREIGN KEY (clanId) REFERENCES clans(id));"; private static String CREATE_CLAN_ALLIANCE_TABLE = "CREATE TABLE IF NOT EXISTS clanAlliances (id INT NOT NULL AUTO_INCREMENT, clanId INT, otherClanId INT, trusted BIT(1), PRIMARY KEY (id), FOREIGN KEY (otherClanId) REFERENCES clans(id), FOREIGN KEY (clanId) REFERENCES clans(id), INDEX clanIdIndex (clanId));"; - private static String RETRIEVE_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline FROM clans AS c WHERE lower(c.name) = ?;"; + private static String RETRIEVE_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, c.eloRating FROM clans AS c WHERE lower(c.name) = ?;"; private static String RETRIEVE_PLAYER_CLAN_INFO = "SELECT clans.name, accountClan.clanRole, clanServer.serverName, clans.id FROM accountClan INNER JOIN clans ON clans.id = accountClan.clanId INNER JOIN clanServer ON clans.serverId = clanServer.id WHERE accountClan.accountId = ?;"; - private static String RETRIEVE_START_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, ct.chunk, ct.safe FROM clans AS c LEFT JOIN clanTerritory AS ct ON ct.clanId = c.id WHERE c.serverId = ? OR c.admin = 1;"; + private static String RETRIEVE_START_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, c.eloRating, ct.chunk, ct.safe FROM clans AS c LEFT JOIN clanTerritory AS ct ON ct.clanId = c.id WHERE c.serverId = ? OR c.admin = 1;"; private static String RETRIEVE_CLAN_MEMBER_INFO = "SELECT c.name, a.name, a.uuid, clanRole FROM accountClan AS ac INNER JOIN accounts AS a ON a.id = ac.accountId INNER JOIN clans AS c on c.id = ac.clanId WHERE c.serverId = ?;"; private static String RETRIEVE_CLAN_MEMBERS = "SELECT c.name, a.name, a.uuid, clanRole FROM accountClan AS ac INNER JOIN accounts AS a ON a.id = ac.accountId INNER JOIN clans AS c on c.id = ac.clanId WHERE lower(c.name) = ?;"; private static String RETRIEVE_CLAN_ALLIANCE_INFO = "SELECT c.name, cOther.name, ca.trusted FROM clanAlliances AS ca INNER JOIN clans AS c ON c.id = ca.clanId INNER JOIN clans as cOther ON cOther.id = ca.otherClanId WHERE c.serverId = ?;"; @@ -71,6 +71,7 @@ public class ClanRepository extends MinecraftRepository private static String ADD_CLAN_WAR = "INSERT INTO clanWar (initiatorId, clanId, score, created, lastUpdated) VALUES (?, ?, ?, ?, ?)"; private static String ADD_CLAN_TERRITORY = "INSERT INTO clanTerritory (clanId, chunk, safe) VALUES (?, ?, ?);"; + //Not Sure if UPDATE_CLAN should set eloRating, but I would think it would need to private static String UPDATE_CLAN = "UPDATE clans SET name = ?, description = ?, home = ?, admin = ?, energy = ?, kills = ?, murder = ?, deaths = ?, warWins = ?, warLosses = ?, lastOnline = ? WHERE id = ?;"; private static String UPDATE_CLAN_MEMBER = "UPDATE accountClan AS AC INNER JOIN accounts ON accounts.id = AC.accountId SET AC.clanRole = ? WHERE AC.clanId = ? AND accounts.name = ?;"; private static String UPDATE_CLAN_ALLIANCE = "UPDATE clanAlliances SET trusted = ? WHERE clanId = ? AND otherClanId = ?;"; @@ -200,10 +201,12 @@ public class ClanRepository extends MinecraftRepository clan.Deaths = resultSet.getInt(9); clan.WarWins = resultSet.getInt(10); clan.WarLosses = resultSet.getInt(11); - clan.Generator = resultSet.getString(12); + clan.GeneratorBuyer = resultSet.getString(12); clan.GeneratorStock = resultSet.getInt(13); clan.DateCreated = resultSet.getTimestamp(14); clan.LastOnline = resultSet.getTimestamp(15); + + clan.EloRating = resultSet.getInt(16); } } }, new ColumnVarChar("name", 100, clanName.toLowerCase())); @@ -290,15 +293,18 @@ public class ClanRepository extends MinecraftRepository token.Deaths = resultSet.getInt(9); token.WarWins = resultSet.getInt(10); token.WarLosses = resultSet.getInt(11); - token.Generator = resultSet.getString(12); + + token.GeneratorBuyer = resultSet.getString(12); token.GeneratorStock = resultSet.getInt(13); token.DateCreated = resultSet.getTimestamp(14); token.LastOnline = resultSet.getTimestamp(15); + token.EloRating = resultSet.getInt(16); + ClanTerritoryToken territoryToken = new ClanTerritoryToken(); territoryToken.ClanName = token.Name; - territoryToken.Chunk = resultSet.getString(16); - territoryToken.Safe = resultSet.getBoolean(17); + territoryToken.Chunk = resultSet.getString(17); + territoryToken.Safe = resultSet.getBoolean(18); if (!clans.containsKey(token.Name)) { @@ -561,6 +567,11 @@ public class ClanRepository extends MinecraftRepository // new ColumnInt("clanScore", clanScore), new ColumnInt("otherClanScore", otherClanScore), new ColumnInt("clanKills", clanKills), // new ColumnInt("otherClanKills", otherClanKills), new ColumnInt("clanId", clanId), new ColumnInt("otherClanId", otherClanId)); // } + + public int getServerId() + { + return _serverId; + } public boolean updateClanGenerator(int clanId, String generator, int generatorStock) { diff --git a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/ClanToken.java b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/ClanToken.java index 1d49a9d62..64fc17224 100644 --- a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/ClanToken.java +++ b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/ClanToken.java @@ -17,7 +17,8 @@ public class ClanToken public int Deaths; public int WarWins; public int WarLosses; - public String Generator; + public int EloRating; + public String GeneratorBuyer; public int GeneratorStock; public Timestamp DateCreated; public Timestamp LastOnline; diff --git a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/SimpleClanToken.java b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/SimpleClanToken.java index 70757bd98..e7fd13ca0 100644 --- a/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/SimpleClanToken.java +++ b/Plugins/Mineplex.Game.Clans.Core/src/mineplex/game/clans/core/repository/tokens/SimpleClanToken.java @@ -3,7 +3,7 @@ package mineplex.game.clans.core.repository.tokens; public class SimpleClanToken { - private String _clanName; + private String _clanName = ""; public String getClanName() { return _clanName; } private String _clanRole; @@ -22,4 +22,6 @@ public class SimpleClanToken _homeServer = homeServer; _clanId = clanId; } + + public SimpleClanToken() { } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java new file mode 100644 index 000000000..54dabeebc --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/core/incognito/events/IncognitoHidePlayerEvent.java @@ -0,0 +1,47 @@ +package mineplex.core.incognito.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called when an Incognito player is getting hidden from all other players. + */ +public class IncognitoHidePlayerEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private boolean _cancelled; + + public IncognitoHidePlayerEvent(Player player) + { + _player = player; + } + + public Player getPlayer() + { + return _player; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Clans.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Clans.java index 5dedde239..15e9c9edc 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Clans.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Clans.java @@ -7,20 +7,25 @@ import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.CustomTagFix; import mineplex.core.FoodDupeFix; +import mineplex.core.PacketsInteractionFix; import mineplex.core.account.CoreClientManager; import mineplex.core.achievement.AchievementManager; import mineplex.core.antihack.AntiHack; import mineplex.core.blockrestore.BlockRestore; import mineplex.core.chat.Chat; import mineplex.core.command.CommandCenter; +import mineplex.core.common.MinecraftVersion; +import mineplex.core.common.Pair; import mineplex.core.common.events.ServerShutdownEvent; import mineplex.core.delayedtask.DelayedTask; import mineplex.core.donation.DonationManager; import mineplex.core.explosion.Explosion; +import mineplex.core.fallingblock.FallingBlocks; import mineplex.core.friend.FriendManager; import mineplex.core.give.Give; import mineplex.core.hologram.HologramManager; import mineplex.core.ignore.IgnoreManager; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.inventory.InventoryManager; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.memory.MemoryFix; @@ -53,7 +58,7 @@ import net.minecraft.server.v1_8_R3.MinecraftServer; public class Clans extends JavaPlugin { - public static final String VERSION = "1.0"; + public static final String VERSION = "Beta 1.0"; private String WEB_CONFIG = "webServer"; // Modules @@ -88,10 +93,16 @@ public class Clans extends JavaPlugin _donationManager = new DonationManager(this, _clientManager, webServerAddress); + new FallingBlocks(this); + new ServerConfiguration(this, _clientManager); - PreferencesManager preferenceManager = new PreferencesManager(this, _clientManager, _donationManager); - + PacketHandler packetHandler = new PacketHandler(this); + IncognitoManager incognito = new IncognitoManager(this, _clientManager, packetHandler); + PreferencesManager preferenceManager = new PreferencesManager(this, incognito, _clientManager, _donationManager); + + incognito.setPreferencesManager(preferenceManager); + ServerStatusManager serverStatusManager = new ServerStatusManager(this, _clientManager, new LagMeter(this, _clientManager)); // TODO: Add spawn locations to a configuration file of some sort? @@ -102,7 +113,7 @@ public class Clans extends JavaPlugin Portal portal = new Portal(this, _clientManager, serverStatusManager.getCurrentServerName()); new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion()); - new ClansBanManager(this, _clientManager, _donationManager); +// ClansBanManager clansBans = new ClansBanManager(this, _clientManager, _donationManager); Punish punish = new Punish(this, webServerAddress, _clientManager); AntiHack.Initialize(this, punish, portal, preferenceManager, _clientManager); @@ -111,27 +122,29 @@ public class Clans extends JavaPlugin BlockRestore blockRestore = new BlockRestore(this); IgnoreManager ignoreManager = new IgnoreManager(this, _clientManager, preferenceManager, portal); - + StatsManager statsManager = new StatsManager(this, _clientManager); AchievementManager achievementManager = new AchievementManager(statsManager, _clientManager, _donationManager); - Chat chat = new Chat(this, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); - new MessageManager(this, _clientManager, preferenceManager, ignoreManager, punish, new FriendManager(this, _clientManager, preferenceManager, portal), chat); + Chat chat = new Chat(this, incognito, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); + new MessageManager(this, incognito, _clientManager, preferenceManager, ignoreManager, punish, new FriendManager(this, _clientManager, preferenceManager, portal), chat); new MemoryFix(this); new FoodDupeFix(this); new Explosion(this, blockRestore); - new FriendManager(this, _clientManager, preferenceManager, portal); new InventoryManager(this, _clientManager); ResourcePackManager resourcePackManager = new ResourcePackManager(this, portal); - resourcePackManager.setResourcePack("http://file.mineplex.com/ResClans.zip", true); + resourcePackManager.setResourcePack(new Pair[] + { + Pair.create(MinecraftVersion.Version1_8, "http://phinary.ca/ResClans.zip"), + Pair.create(MinecraftVersion.Version1_9, "http://phinary.ca/ResClans19.zip") + }, true); // Enable custom-gear related managers - PacketHandler packetHandler = new PacketHandler(this); new CustomTagFix(this, packetHandler); GearManager customGear = new GearManager(this, packetHandler, _clientManager, _donationManager); HologramManager hologram = new HologramManager(this, packetHandler); - _clansManager = new ClansManager(this, serverStatusManager.getCurrentServerName(), packetHandler, punish, _clientManager, _donationManager, preferenceManager, blockRestore, teleport, chat, customGear, hologram, webServerAddress); + _clansManager = new ClansManager(this, /*clansBans,*/ serverStatusManager.getCurrentServerName(), incognito, packetHandler, punish, _clientManager, _donationManager, preferenceManager, blockRestore, statsManager, teleport, chat, customGear, hologram, webServerAddress); new Recipes(this); new Farming(this); new BuildingShop(_clansManager, _clientManager, _donationManager); @@ -152,8 +165,6 @@ public class Clans extends JavaPlugin new Updater(this); MinecraftServer.getServer().getPropertyManager().setProperty("debug", true); - - getServer().setWhitelist(false); // TODO: remove } public static String prettifyName(Material material) @@ -179,4 +190,9 @@ public class Clans extends JavaPlugin getServer().getPluginManager().callEvent(new ServerShutdownEvent(this)); } + + public static String version() + { + return VERSION; + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Recipes.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Recipes.java index 26c41fd33..8615db3df 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Recipes.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/Recipes.java @@ -1,27 +1,23 @@ package mineplex.game.clans; -import java.util.ArrayList; -import java.util.List; - -import mineplex.core.MiniPlugin; -import mineplex.core.common.util.UtilGear; -import mineplex.core.itemstack.ItemStackFactory; -import mineplex.core.common.util.C; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilServer; - import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.PrepareItemCraftEvent; import org.bukkit.inventory.CraftingInventory; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.material.SmoothBrick; import org.bukkit.plugin.java.JavaPlugin; +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilGear; +import mineplex.core.common.util.UtilServer; +import mineplex.core.itemstack.ItemStackFactory; + public class Recipes extends MiniPlugin { public Recipes(JavaPlugin plugin) @@ -41,7 +37,14 @@ public class Recipes extends MiniPlugin diamondAxe.setIngredient('M', Material.DIAMOND_BLOCK); diamondAxe.setIngredient('S', Material.STICK); UtilServer.getServer().addRecipe(diamondAxe); - + + + ShapedRecipe bricks = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); + bricks.shape("XX", "XX"); + bricks.setIngredient('X', new SmoothBrick(Material.COBBLESTONE)); + UtilServer.getServer().addRecipe(bricks); + + ItemStack boosterSword = ItemStackFactory.Instance.CreateStack(Material.GOLD_SWORD, (byte) 0, 1, "Booster Sword", false); ShapedRecipe goldSword = new ShapedRecipe(boosterSword); goldSword.shape("M","M","S"); @@ -141,6 +144,28 @@ public class Recipes extends MiniPlugin chainBoots2.setIngredient('S', Material.IRON_INGOT); UtilServer.getServer().addRecipe(chainBoots2); + + ShapedRecipe stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); + stonebrick.shape("SS#", "SS#"); + stonebrick.setIngredient('S', Material.STONE); + UtilServer.getServer().addRecipe(stonebrick); + + stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); + stonebrick.shape("#SS", "#SS"); + stonebrick.setIngredient('S', Material.STONE); + UtilServer.getServer().addRecipe(stonebrick); + + stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); + stonebrick.shape("###", "SS#", "SS#"); + stonebrick.setIngredient('S', Material.STONE); + UtilServer.getServer().addRecipe(stonebrick); + + stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); + stonebrick.shape("###", "#SS", "#SS"); + stonebrick.setIngredient('S', Material.STONE); + UtilServer.getServer().addRecipe(stonebrick); + + } @EventHandler(priority = EventPriority.LOW) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanEnergyTracker.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanEnergyTracker.java index 307768c84..e7a2a998a 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanEnergyTracker.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanEnergyTracker.java @@ -61,7 +61,7 @@ public class ClanEnergyTracker extends MiniPlugin Triple energyBounds = _updateMap.get(type); - if (energyBounds != null && energyRemaining > energyBounds.getLeft() && energyRemaining < energyBounds.getMiddle()) + if (energyBounds != null && energyRemaining > energyBounds.getLeft().longValue() && energyRemaining < energyBounds.getMiddle().longValue()) { _clans.middleTextClan(clan, energyBounds.getRight()[0], energyBounds.getRight()[1], 20, 200, 80); _clans.sendTipToClan(clan, TipType.ENERGY); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanInfo.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanInfo.java index e5dd03b0b..f7df176ea 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanInfo.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanInfo.java @@ -48,6 +48,7 @@ public class ClanInfo private int _deaths; private int _warWins; private int _warLosses; + private int _eloRating; private boolean _admin = false; @@ -86,6 +87,7 @@ public class ClanInfo _id = token.Id; _name = token.Name; _desc = token.Description; + _eloRating = token.EloRating; try { @@ -119,23 +121,6 @@ public class ClanInfo _bedStatus = BedStatus.DOESNT_EXIST; } - try - { - if (token.Generator != null && token.Generator.length() > 0) - { - Block block = UtilWorld.strToBlock(token.Generator); - if (block != null) - { - _generator = new TntGenerator(block); - _generator.setStock(token.GeneratorStock); - } - } - } - catch (Exception e) - { - - } - _energy = token.Energy; _admin = token.Admin; @@ -169,6 +154,39 @@ public class ClanInfo ClanWarData warData = warToken.WarData; _warOut.put(warData.getClanB(), warData); } + + try + { + if (token.GeneratorBuyer != null && token.GeneratorBuyer.length() > 0) + { + if (token.GeneratorBuyer.contains(",")) + { + // Convert to new generator format; + + for (ClanMemberToken memberToken : token.Members) + { + ClanRole role = ClanRole.valueOf(memberToken.ClanRole); + + if (role.equals(ClanRole.LEADER)) + { + token.GeneratorBuyer = memberToken.PlayerUUID.toString(); + break; + } + } + + System.out.println("Clans> Converted " + _name + "'s generator to the new format."); + } + + _generator = new TntGenerator(token.GeneratorBuyer); + _generator.setStock(token.GeneratorStock); + + Clans.getClanDataAccess().updateGenerator(this, null); + } + } + catch (Exception e) + { + + } } public int getClaims() @@ -246,12 +264,17 @@ public class ClanInfo public boolean isAlly(ClanInfo other) { + if (other == null) + { + return false; + } + return isAlly(other.getName()); } public boolean isSelf(String other) { - return this.getName().equals(other); + return getName().equals(other); } public boolean isNeutral(String other) @@ -594,6 +617,16 @@ public class ClanInfo { _warLosses += amount; } + + public int getEloRating() + { + return _eloRating; + } + + public void addEloRating(int amount) + { + _eloRating += amount; + } public ClanWarData getWarData(ClanInfo against) { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanTips.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanTips.java index c4e4f8f87..4f2c6e166 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanTips.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClanTips.java @@ -219,6 +219,16 @@ public class ClanTips extends MiniPlugin C.cDAqua + "Clan Home", C.cAqua + "Your Clan Home is a bed in your Territory which you can teleport to from the Spawn Islands. However, you are unable to teleport to your Clan Home if the bed is broken, blocks have been placed above the bed, or enemies are in your Territory." }), + MOUNT_CANNON( + new String[] { + C.cDAqua + "Meownon", + C.cAqua + "Congratulations on your new purchase! You are now in possesion, of the one, and only, Meownon 3000.24! " + C.Italics + "we are not responsible for any injuries caused by the meownon, or any related products. stay safe kids." + }), + ENTER_NETHER( + new String[] { + C.cDAqua + "The Nether", + C.cAqua + "Welcome to the Nether. This is a very scary place full of fire and is a place for people to battle to the death! TODO: Write something better about the nether here" + }), ; // this is only LinkedList because UtilPlayer.message wants it diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAdmin.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAdmin.java index a5c23d8a7..b7d073814 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAdmin.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAdmin.java @@ -1,7 +1,12 @@ package mineplex.game.clans.clans; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + import mineplex.core.common.Rank; import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; @@ -10,10 +15,9 @@ import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilWorld; import mineplex.game.clans.core.repository.ClanTerritory; +import mineplex.game.clans.core.repository.tokens.ClanToken; import mineplex.game.clans.core.war.ClanWarData; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import mineplex.serverdata.database.ResultSetCallable; public class ClansAdmin { @@ -84,6 +88,9 @@ public class ClansAdmin else if (args[1].equalsIgnoreCase("wp")) wp(caller, args); + + else if (args[1].equalsIgnoreCase("rename")) + rename(caller, args); else if (args[1].equalsIgnoreCase("timer")) resetTime(caller, args); @@ -110,6 +117,7 @@ public class ClansAdmin UtilPlayer.message(caller, F.help("/c x trust ", "Give Trust to Clan", Rank.CMOD)); UtilPlayer.message(caller, F.help("/c x neutral ", "Set Neutrality", Rank.CMOD)); UtilPlayer.message(caller, F.help("/c x enemy ", "Start Invasion", Rank.CMOD)); + UtilPlayer.message(caller, F.help("/c x rename ", "Change the name of Mimic", Rank.CMOD)); UtilPlayer.message(caller, F.help("/c x claim", "Claim Territory for Mimic", Rank.CMOD)); UtilPlayer.message(caller, F.help("/c x unclaim (all)", "Unclaim Territory for Mimic", Rank.CMOD)); UtilPlayer.message(caller, F.help("/c x delete", "Delete Mimic Clan", Rank.CMOD)); @@ -194,80 +202,80 @@ public class ClansAdmin public void create(final Player caller, final String[] args) { - if (args.length < 3) - { - UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a Clan name.")); - return; - } + if (args.length < 3) + { + UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a Clan name.")); + return; + } - if (!UtilInput.valid(args[2])) - { - UtilPlayer.message(caller, F.main("Clans Admin", "Invalid characters in Clan name.")); - return; - } + if (!UtilInput.valid(args[2])) + { + UtilPlayer.message(caller, F.main("Clans Admin", "Invalid characters in Clan name.")); + return; + } - if (args[2].length() < Clans.getNameMin()) - { - UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too short. Minimum length is " + (Clans.getNameMin()) + ".")); - return; - } + if (args[2].length() < Clans.getNameMin()) + { + UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too short. Minimum length is " + (Clans.getNameMin()) + ".")); + return; + } - if (args[2].length() > Clans.getNameMax()) - { - UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too long. Maximum length is " + (Clans.getNameMax()) + ".")); - return; - } + if (args[2].length() > Clans.getNameMax()) + { + UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too long. Maximum length is " + (Clans.getNameMax()) + ".")); + return; + } - if (!ClansBlacklist.isValidClanName(args[2])) - { - UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Clan command.")); - } + if (!Clans.getBlacklist().allowed(args[2])) + { + UtilPlayer.message(caller, F.main("Clans Admin", "That name is blacklisted, please choose another one.")); + } - if (Clans.getClan(args[2]) != null) + if (Clans.getClan(args[2]) != null) + { + UtilPlayer.message(caller, F.main("Clans Admin", F.elem("Clan " + args[2]) + " already exists.")); + return; + } + + Clans.getClientManager().checkPlayerNameExact(new Callback() + { + public void run(final Boolean nameExists) { - UtilPlayer.message(caller, F.main("Clans Admin", F.elem("Clan " + args[2]) + " already exists.")); - return; - } - - Clans.getClientManager().checkPlayerNameExact(new Callback() - { - public void run(final Boolean nameExists) + Bukkit.getServer().getScheduler().runTask(Clans.getPlugin(), new Runnable() { - Bukkit.getServer().getScheduler().runTask(Clans.getPlugin(), new Runnable() + public void run() { - public void run() + if (nameExists.booleanValue()) + UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Player name.")); + else { - if (nameExists) - UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Player name.")); - else + Clans.getClanDataAccess().create(caller.getName(), args[2], true, new Callback() { - Clans.getClanDataAccess().create(caller.getName(), args[2], true, new Callback() + @Override + public void run(ClanInfo data) { - @Override - public void run(ClanInfo data) + if (data != null) { - if (data != null) - { - //Inform - UtilServer.broadcast(F.main("Clans Admin", caller.getName() + " formed " + F.elem("Admin Clan " + args[2]) + ".")); + //Inform + UtilServer.broadcast(F.main("Clans Admin", caller.getName() + " formed " + F.elem("Admin Clan " + args[2]) + ".")); - // Set Mimic - Clans.Get(caller).setMimic(args[2]); + // Set Mimic + Clans.Get(caller).setMimic(args[2]); - // Inform - UtilPlayer.message(caller, F.main("Clans Admin", "You are mimicing Clan " + args[2] + ".")); - } - else - { - UtilPlayer.message(caller, F.main("Clans", "There was an error creating a clan! Try again later")); - } + // Inform + UtilPlayer.message(caller, F.main("Clans Admin", "You are mimicing Clan " + args[2] + ".")); } - }); - } + else + { + UtilPlayer.message(caller, F.main("Clans", "There was an error creating a clan! Try again later")); + } + } + }); } - }); - } - }, args[2]); + } + }); + } + }, args[2]); } public void delete(final Player caller, String[] args) @@ -480,7 +488,7 @@ public class ClansAdmin UtilPlayer.message(caller, F.main("Clans Admin", "You demoted " + target + " to " + newRank + " in Mimic Clan.")); clan.inform(F.main("Clans Admin", caller.getName() + " demoted " + target + " to " + newRank + "."), null); } - + public void kick(final Player caller, String[] args) { final ClanInfo clan = getMimic(caller, true); @@ -577,6 +585,46 @@ public class ClansAdmin cB.inform("Clan " + cA.getName() + " has requested alliance with you.", null); } } + + + public void rename(Player caller, String[] args) + { + ClanInfo cA = getMimic(caller, true); + + if (cA == null) + return; + + if (args.length < 3) + { + UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a new name.")); + return; + } + + String name = args[2]; + + final ClanToken clan = new ClanToken(); + + // Populate simple fields + clan.Id = cA.getId(); + clan.Name = cA.getName(); + clan.Description = cA.getDesc(); + clan.Home = UtilWorld.locToStr(cA.getHome()); + clan.Admin = cA.isAdmin(); + clan.Energy = cA.getEnergy(); + clan.Kills = cA.getKills(); + clan.Murder = cA.getMurder(); + clan.Deaths = cA.getDeaths(); + clan.WarWins = cA.getWarWins(); + clan.WarLosses = cA.getWarLosses(); + clan.GeneratorBuyer = cA.getGenerator().getBuyer().toString(); + clan.GeneratorStock = cA.getGenerator().getStock(); + clan.DateCreated = cA.getDateCreated(); + clan.LastOnline = cA.getLastOnline(); + clan.EloRating = cA.getEloRating(); + +// clan.Members = cA.getMembers(); + + } // public void trust(Player caller, String[] args) // { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAlphaManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAlphaManager.java deleted file mode 100644 index df206e60e..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansAlphaManager.java +++ /dev/null @@ -1,75 +0,0 @@ -package mineplex.game.clans.clans; - -import java.util.Arrays; -import java.util.LinkedList; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerJoinEvent; - -import mineplex.core.MiniPlugin; -import mineplex.core.common.util.C; -import mineplex.core.common.util.Callback; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.task.TaskManager; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; - -public class ClansAlphaManager extends MiniPlugin -{ - private static final LinkedList> ANNOUNCEMENTS = new LinkedList<>(Arrays.asList(new LinkedList<>(Arrays.asList(C.cDAquaB + "Welcome to Clans Alpha", C.cAqua + "Clans is in early Alpha stages so expect there to be bugs/issues. Please report any bugs to staff, we hope you enjoy this early test!")))); - - private static final boolean RANDOM_ANNOUNCEMENT = true; - - /** - * This is useful if the above boolean (RANDOM_ANNOUNCEMENT) is set to - * false, then the announcement at index SET_ANNOUNCEMENT will be used every - * time. - */ - private static final int SET_ANNOUNCEMENT = 0; - - private static final LinkedList FIRST_JOIN_MESSAGES = new LinkedList<>(ANNOUNCEMENTS.getFirst()); - private static final UpdateType ANNOUNCEMENT_DELAY = UpdateType.MIN_16; - - private TaskManager _taskManager; - - public ClansAlphaManager(ClansManager manager, TaskManager taskManager) - { - super("Announcements", manager.getPlugin()); - - _taskManager = taskManager; - } - - @EventHandler - public void onPlayerJoin(final PlayerJoinEvent event) - { - if (!_taskManager.hasCompletedTask(event.getPlayer(), "ClansAlphaJoinMessage")) - { - _taskManager.completedTask(new Callback() - { - public void run(Boolean data) - { - UtilPlayer.message(event.getPlayer(), FIRST_JOIN_MESSAGES); - } - }, event.getPlayer(), "ClansAlphaJoinMessage"); - } - } - - @EventHandler - public void onUpdate(UpdateEvent event) - { - if (event.getType().equals(ANNOUNCEMENT_DELAY)) - { - if (RANDOM_ANNOUNCEMENT) - { - UtilServer.broadcast(UtilMath.randomElement(ANNOUNCEMENTS)); - } - else - { - UtilServer.broadcast(ANNOUNCEMENTS.get(SET_ANNOUNCEMENT)); - } - } - } - -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBetaManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBetaManager.java new file mode 100644 index 000000000..a669ca6f4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBetaManager.java @@ -0,0 +1,27 @@ +package mineplex.game.clans.clans; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerJoinEvent; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.task.TaskManager; +import mineplex.game.clans.Clans; + +public class ClansBetaManager extends MiniPlugin +{ + public ClansBetaManager(ClansManager manager, TaskManager taskManager) + { + super("Clans Beta", manager.getPlugin()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(final PlayerJoinEvent event) + { + UtilPlayer.message(event.getPlayer(), C.cDAquaB + "Welcome to Mineplex Clans " + Clans.VERSION); + + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBlacklist.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBlacklist.java deleted file mode 100644 index 1483b9949..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansBlacklist.java +++ /dev/null @@ -1,41 +0,0 @@ -package mineplex.game.clans.clans; - -import java.util.Arrays; -import java.util.List; - -/** - * ClansBlacklist represents the blacklist of all disallowed names for clan creation. - * @author MrTwiggy - * - */ -public class ClansBlacklist -{ - - // Set of all blacklisted clan names that are NOT valid. - private final static List BLACKLISTED_NAMES = Arrays.asList(new String[] - { - "Youtube", "Owner", "Admin", "Mod", "Trainee", "Twitch", - "Wilderness", "Shops", "Builder", "Spawn", "Clan", "Clans", - "Fields", "Sr.Mod", "Sr. Mod", "Dev", "Jr.Dev", "Jr. Dev", "create", - "join", "leave", "map", "cc", "ac", "invite", "kick", "neutral", - "enemy", "trust", "unclaim", "claim", "delete", "SrMod", "Twitch", "YouTube", "Event", - "Media", "MapLead", "JrDev", "Developer", "Leader", "LT", "Support" - }); - - /** - * @param clanName - the name of the clan to validate - * @return true, if {@code clanName} is a valid and non-blacklisted clan name, false otherwise. - */ - public static boolean isValidClanName(String clanName) - { - for (String blacklistedName : BLACKLISTED_NAMES) - { - if (blacklistedName.equalsIgnoreCase(clanName)) - { - return false; - } - } - - return true; - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDataAccessLayer.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDataAccessLayer.java index 9ca0714f1..f92282c73 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDataAccessLayer.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDataAccessLayer.java @@ -16,6 +16,7 @@ import mineplex.core.common.util.UtilBlock; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilWorld; import mineplex.game.clans.clans.event.ClanCreatedEvent; +import mineplex.game.clans.clans.event.ClanCreationCompleteEvent; import mineplex.game.clans.clans.event.ClanDeleteEvent; import mineplex.game.clans.clans.event.ClanJoinEvent; import mineplex.game.clans.clans.event.ClanLeaveEvent; @@ -195,6 +196,9 @@ public class ClansDataAccessLayer } if (callback != null) callback.run(clanInfo); + + ClanCreationCompleteEvent event = new ClanCreationCompleteEvent(token, Bukkit.getPlayer(creator)); + UtilServer.getServer().getPluginManager().callEvent(event); } }); } @@ -724,17 +728,17 @@ public class ClansDataAccessLayer public void updateGenerator(final ClanInfo clanInfo, final Callback callback) { TntGenerator generator = clanInfo.getGenerator(); - final String location; + final String creator; final int generatorStock; if (generator != null) { - location = UtilWorld.blockToStr(generator.getBlock()); + creator = generator.getBuyer().toString(); generatorStock = generator.getStock(); } else { - location = ""; + creator = ""; generatorStock = 0; } @@ -743,7 +747,7 @@ public class ClansDataAccessLayer @Override public void run() { - final boolean ran = _repository.updateClanGenerator(clanInfo.getId(), location, generatorStock); + final boolean ran = _repository.updateClanGenerator(clanInfo.getId(), creator, generatorStock); runSync(new Runnable() { @Override @@ -751,9 +755,14 @@ public class ClansDataAccessLayer { if (callback != null) { - callback.run(ran); - } else { - if(!ran) System.out.println("Tnt Gen didn't save!"); + callback.run(Boolean.valueOf(ran)); + } + else + { + if (!ran) + { + System.out.println("Tnt Gen didn't save!"); + } } } }); @@ -776,8 +785,14 @@ public class ClansDataAccessLayer // Memory claim.Safe = !claim.Safe; - // Save - _repository.updateTerritoryClaim(claim.Chunk, claim.Safe); + runAsync(new Runnable() + { + @Override + public void run() + { + _repository.updateTerritoryClaim(claim.Chunk, claim.Safe); + } + }); // Log _manager.log("Safe Zone at [" + claim.Chunk + "] set to [" + claim.Safe + "] by [" + player + "]."); @@ -791,14 +806,35 @@ public class ClansDataAccessLayer public void run() { ClanToken clan = _repository.retrieveClan(clanName); - callback.run(clan); + runSync(() -> callback.run(clan)); } }); } public void clanExists(String clanName, Callback callback) { - _repository.clanExists(clanName, callback); + runAsync(new Runnable() + { + @Override + public void run() + { + _repository.clanExists(clanName, new Callback() + { + @Override + public void run(Boolean data) + { + runSync(new Runnable() + { + @Override + public void run() + { + if (callback != null) callback.run(data); + } + }); + } + }); + } + }); } public ClanRepository getRepository() diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDisplay.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDisplay.java index 46f5a3708..17d27fc9c 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDisplay.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansDisplay.java @@ -24,13 +24,13 @@ import mineplex.game.clans.core.repository.ClanTerritory; public class ClansDisplay extends MiniPlugin { - private ClansManager Clans; + private ClansManager _clansManager; public ClansDisplay(JavaPlugin plugin, ClansManager clans) { super("Clans Display", plugin); - Clans = clans; + _clansManager = clans; } @EventHandler @@ -46,7 +46,7 @@ public class ClansDisplay extends MiniPlugin { if (player.getWorld().getEnvironment() != Environment.NORMAL) return; - ClientClan client = Clans.Get(player); + ClientClan client = _clansManager.Get(player); if (client == null) return; // Same Chunk @@ -56,16 +56,16 @@ public class ClansDisplay extends MiniPlugin client.setTerritory(UtilWorld.chunkToStr(player.getLocation().getChunk())); // AutoClaim - if (client.isAutoClaim()) Clans.getClanAdmin().claim(player); + if (client.isAutoClaim()) _clansManager.getClanAdmin().claim(player); // Map String owner = "Wilderness"; - ClanInfo ownerClan = Clans.getClanUtility().getOwner(player.getLocation()); + ClanInfo ownerClan = _clansManager.getClanUtility().getOwner(player.getLocation()); if (ownerClan != null) owner = ownerClan.getName(); - boolean safe = Clans.getClanUtility().isSafe(player); + boolean safe = _clansManager.getClanUtility().isSafe(player); - PlayerEnterTerritoryEvent event = new PlayerEnterTerritoryEvent(player, client.getOwner(), owner, owner.equals("Wilderness") ? false : Clans.getClanUtility().getClaim(player.getLocation()).isSafe(player.getLocation()), true); + PlayerEnterTerritoryEvent event = new PlayerEnterTerritoryEvent(player, client.getOwner(), owner, owner.equals("Wilderness") ? false : _clansManager.getClanUtility().getClaim(player.getLocation()).isSafe(player.getLocation()), true); UtilServer.getServer().getPluginManager().callEvent(event); @@ -105,19 +105,26 @@ public class ClansDisplay extends MiniPlugin // Name String ownerString = C.xWilderness + "Wilderness"; - ClanTerritory claim = Clans.getClanUtility().getClaim(player.getLocation()); + ClanTerritory claim = _clansManager.getClanUtility().getClaim(player.getLocation()); if (claim != null) { // Relation - ClanRelation relation = Clans.getClanUtility().relPT(player, claim.Chunk); + ClanRelation relation = _clansManager.getClanUtility().relPT(player, claim.Chunk); // Name - ownerString = Clans.getClanUtility().mRel(relation, claim.Owner, false); + ownerString = _clansManager.getClanUtility().mRel(relation, claim.Owner, false); // Trust if (relation == ClanRelation.ALLY_TRUST) ownerString += " " + C.mBody + "(" + C.mElem + "Trusted" + C.mBody + ")"; } +// if (_clansManager.getNetherManager().isInNether(player)) +// { +// _clansManager.message(player, "You are not allowed to claim territory in " + F.clansNether("The Nether") + "."); +// +// ownerString = C.cRed + "The Nether"; +// } + UtilTextMiddle.display("", ownerString, 0, 25, 10, player); UtilPlayer.message(player, F.main("Territory", ownerString)); } @@ -137,7 +144,7 @@ public class ClansDisplay extends MiniPlugin if (player.getItemInHand().getType() == Material.MAP) { - ClanInfo clan = Clans.getClanUtility().getClanByPlayer(player); + ClanInfo clan = _clansManager.getClanUtility().getClanByPlayer(player); if (clan != null) if (clan.getHome() != null) home = mLocalMap(player, clan.getHome().getChunk(), false); } @@ -177,14 +184,14 @@ public class ClansDisplay extends MiniPlugin } // Get Data - ClanInfo curOwner = Clans.getClanUtility().getOwner(UtilWorld.chunkToStr(curChunk)); - ClanTerritory curClaim = Clans.getClanUtility().getClaim(UtilWorld.chunkToStr(curChunk)); + ClanInfo curOwner = _clansManager.getClanUtility().getOwner(UtilWorld.chunkToStr(curChunk)); + ClanTerritory curClaim = _clansManager.getClanUtility().getClaim(UtilWorld.chunkToStr(curChunk)); // Add Icon if (i == chunk.getX() && j == chunk.getZ()) - output += getMapIcon(Clans.getClanUtility().relPC(player, curOwner), curClaim, curOwner, curChunk, pCount, true, local); + output += getMapIcon(_clansManager.getClanUtility().relPC(player, curOwner), curClaim, curOwner, curChunk, pCount, true, local); else - output += getMapIcon(Clans.getClanUtility().relPC(player, curOwner), curClaim, curOwner, curChunk, pCount, false, local); + output += getMapIcon(_clansManager.getClanUtility().relPC(player, curOwner), curClaim, curOwner, curChunk, pCount, false, local); } output += ">"; @@ -236,7 +243,7 @@ public class ClansDisplay extends MiniPlugin { if (players > 0) return "" + C.xSelf + players; - else if (Clans.getClanUtility().isChunkHome(owner, chunk)) + else if (_clansManager.getClanUtility().isChunkHome(owner, chunk)) return "" + C.xSelf + "H"; else return "" + C.xSelf + "#"; @@ -246,7 +253,7 @@ public class ClansDisplay extends MiniPlugin { if (players > 0) return "" + C.xAlly + players; - else if (Clans.getClanUtility().isChunkHome(owner, chunk)) + else if (_clansManager.getClanUtility().isChunkHome(owner, chunk)) return "" + C.xAlly + "H"; else return "" + C.xAlly + "#"; @@ -256,7 +263,7 @@ public class ClansDisplay extends MiniPlugin { if (players > 0) return "" + C.xdAlly + players; - else if (Clans.getClanUtility().isChunkHome(owner, chunk)) + else if (_clansManager.getClanUtility().isChunkHome(owner, chunk)) return "" + C.xdAlly + "H"; else return "" + C.xdAlly + "#"; @@ -264,7 +271,7 @@ public class ClansDisplay extends MiniPlugin if (players > 0) return "" + C.xEnemy + players; - else if (Clans.getClanUtility().isChunkHome(owner, chunk)) + else if (_clansManager.getClanUtility().isChunkHome(owner, chunk)) return "" + C.xEnemy + "H"; else return "" + C.xEnemy + "#"; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansGame.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansGame.java index b1e198995..00d3f6229 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansGame.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansGame.java @@ -1,6 +1,8 @@ package mineplex.game.clans.clans; import java.sql.Timestamp; +import java.util.Arrays; +import java.util.Iterator; import org.bukkit.Bukkit; import org.bukkit.Effect; @@ -18,14 +20,11 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; -import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; @@ -51,9 +50,7 @@ import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansUtility.ClanRelation; import mineplex.game.clans.core.repository.ClanTerritory; -import mineplex.game.clans.spawn.Spawn; import mineplex.minecraft.game.core.damage.CustomDamageEvent; -import net.minecraft.server.v1_8_R3.EnumDirection; public class ClansGame extends MiniPlugin { @@ -81,6 +78,7 @@ public class ClansGame extends MiniPlugin } } + @EventHandler(priority = EventPriority.LOW) public void BlockBurn(BlockBurnEvent event) { @@ -213,15 +211,18 @@ public class ClansGame extends MiniPlugin } // Disallow Recruit Chest - if (_clans.getClanUtility().isClaimed(event.getBlock().getLocation())) if (event.getBlock().getTypeId() == 54) + if (_clans.getClanUtility().isClaimed(event.getBlock().getLocation())) { - if (_clans.getClanUtility().getRole(event.getPlayer()) == ClanRole.RECRUIT) + if (event.getBlock().getType() == Material.CHEST || event.getBlock().getType() == Material.TRAPPED_CHEST) { - // Disallow - event.setCancelled(true); - - // Inform - UtilPlayer.message(event.getPlayer(), F.main("Clans", "Clan Recruits cannot break " + F.elem(ItemStackFactory.Instance.GetName(event.getBlock(), true)) + ".")); + if (_clans.getClanUtility().getRole(event.getPlayer()) == ClanRole.RECRUIT) + { + // Disallow + event.setCancelled(true); + + // Inform + UtilPlayer.message(event.getPlayer(), F.main("Clans", "Clan Recruits cannot break " + F.elem(ItemStackFactory.Instance.GetName(event.getBlock(), true)) + ".")); + } } } @@ -521,8 +522,7 @@ public class ClansGame extends MiniPlugin ClanInfo clan = _clans.getClanUtility().getClanByPlayer(event.getPlayer()); if (clan == null) return; - if(!clan.isOnline()) clan.setLastOnline(new Timestamp(System.currentTimeMillis())); //Noone else on - else clan.setLastOnline(new Timestamp(0)); + clan.setLastOnline(new Timestamp(System.currentTimeMillis())); } @EventHandler(priority = EventPriority.LOWEST) @@ -673,7 +673,7 @@ public class ClansGame extends MiniPlugin if (claim != null) { - if (ClansBlacklist.isValidClanName(claim.Owner)) + if (_clans.getBlacklist().allowed(claim.Owner)) { blockClan = _clans.getClan(claim.Owner); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansManager.java index 7981a5a5e..4b4d008d9 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansManager.java @@ -9,15 +9,19 @@ import java.util.Set; import java.util.TimeZone; import java.util.UUID; +import mineplex.core.recharge.Recharge; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.entity.Horse; import org.bukkit.entity.Player; +import org.bukkit.entity.Vehicle; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.Action; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; @@ -28,6 +32,7 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; @@ -56,6 +61,8 @@ import mineplex.core.energy.Energy; import mineplex.core.explosion.Explosion; import mineplex.core.hologram.Hologram; import mineplex.core.hologram.HologramManager; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.incognito.events.IncognitoStatusChangeEvent; import mineplex.core.movement.Movement; import mineplex.core.npc.NpcManager; import mineplex.core.packethandler.PacketHandler; @@ -69,6 +76,7 @@ import mineplex.core.task.TaskManager; import mineplex.core.teleport.Teleport; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.Clans; import mineplex.game.clans.clans.ClanTips.TipType; import mineplex.game.clans.clans.ClansUtility.ClanRelation; import mineplex.game.clans.clans.commands.ClanManagementCommand; @@ -77,21 +85,24 @@ import mineplex.game.clans.clans.commands.ClansChatCommand; import mineplex.game.clans.clans.commands.ClansCommand; import mineplex.game.clans.clans.commands.KillCommand; import mineplex.game.clans.clans.commands.MapCommand; +import mineplex.game.clans.clans.commands.QueryCommand; import mineplex.game.clans.clans.commands.RegionsCommand; import mineplex.game.clans.clans.data.PlayerClan; import mineplex.game.clans.clans.event.ClansPlayerDeathEvent; import mineplex.game.clans.clans.gui.ClanShop; +import mineplex.game.clans.clans.invsee.Invsee; import mineplex.game.clans.clans.loot.LootManager; import mineplex.game.clans.clans.map.ItemMapManager; +import mineplex.game.clans.clans.nameblacklist.ClansBlacklist; +import mineplex.game.clans.clans.nether.NetherManager; import mineplex.game.clans.clans.observer.ObserverManager; import mineplex.game.clans.clans.playtime.Playtime; import mineplex.game.clans.clans.potato.PotatoManager; -import mineplex.game.clans.clans.pvptimer.PvpTimer; import mineplex.game.clans.clans.redis.ClanDeleteCommandHandler; import mineplex.game.clans.clans.redis.ClanLoadCommandHandler; import mineplex.game.clans.clans.regions.ClansRegions; import mineplex.game.clans.clans.scoreboard.ClansScoreboardManager; -import mineplex.game.clans.clans.stuck.StuckManager; +import mineplex.game.clans.clans.siege.SiegeManager; import mineplex.game.clans.clans.supplyDrop.SupplyDropManager; import mineplex.game.clans.clans.tntGenerator.TntGeneratorManager; import mineplex.game.clans.clans.war.WarManager; @@ -110,7 +121,7 @@ import mineplex.game.clans.gameplay.safelog.SafeLog; import mineplex.game.clans.gameplay.safelog.npc.NPCManager; import mineplex.game.clans.items.GearManager; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialManager; +import mineplex.game.clans.tutorial.TutorialManager; import mineplex.minecraft.game.classcombat.Class.ClassManager; import mineplex.minecraft.game.classcombat.Class.ClientClass; import mineplex.minecraft.game.classcombat.Class.IPvpClass; @@ -160,10 +171,17 @@ public class ClansManager extends MiniClientPluginimplements IRelati private GearManager _gearManager; private LootManager _lootManager; private DonationManager _donationManager; + private NetherManager _netherManager; + private DamageManager _damageManager; + private SiegeManager _siegeManager; + private IncognitoManager _incognitoManager; + private ClansBlacklist _blacklist; + private Playtime _playTracker; - - private TutorialManager _tutorialManager; + + private TutorialManager _tutorial; + private mineplex.game.clans.legacytutorial.TutorialManager _legacyTutorial; private ClassManager _classManager; @@ -184,7 +202,8 @@ public class ClansManager extends MiniClientPluginimplements IRelati private WarPointEvasion _warPointEvasion; private ObserverManager _observerManager; private Punish _punish; - + private TaskManager _taskManager; + private int _inviteExpire = 2; private int _nameMin = 3; private int _nameMax = 10; @@ -205,18 +224,22 @@ public class ClansManager extends MiniClientPluginimplements IRelati public String UserDataDir = UtilServer.getServer().getWorlds().get(0).getWorldFolder().getPath() + File.separator + ".." + File.separator + "CLANS_USER_DATA" + File.separator; + /*private ClansBanManager _clansBans;*/ + public ClanTips ClanTips; // Spawn area - public ClansManager(JavaPlugin plugin, String serverName, PacketHandler packetHandler, Punish punish, CoreClientManager clientManager, DonationManager donationManager, PreferencesManager preferencesManager, BlockRestore blockRestore, Teleport teleport, Chat chat, GearManager gearManager, HologramManager hologramManager, String webServerAddress) + public ClansManager(JavaPlugin plugin/*, ClansBanManager clansBans*/, String serverName, IncognitoManager incognitoManager, PacketHandler packetHandler, Punish punish, CoreClientManager clientManager, DonationManager donationManager, PreferencesManager preferencesManager, BlockRestore blockRestore, StatsManager statsManager, Teleport teleport, Chat chat, GearManager gearManager, HologramManager hologramManager, String webServerAddress) { super("Clans Manager", plugin); _instance = this; + /*_clansBans = clansBans;*/ _punish = punish; + _incognitoManager = incognitoManager; _serverName = serverName; _clientManager = clientManager; _combatManager = new CombatManager(plugin); @@ -229,6 +252,8 @@ public class ClansManager extends MiniClientPluginimplements IRelati _donationManager = donationManager; + _blacklist = new ClansBlacklist(plugin); + _goldManager = new GoldManager(this, _clientManager, donationManager); _gearManager = gearManager; _lootManager = new LootManager(gearManager, _goldManager); @@ -236,11 +261,14 @@ public class ClansManager extends MiniClientPluginimplements IRelati Creature creature = new Creature(plugin); _npcManager = new NpcManager(plugin, creature); _condition = new SkillConditionManager(plugin); - DamageManager damageManager = new DamageManager(plugin, _combatManager, _npcManager, _disguiseManager, _condition); - damageManager.addCommand(new KillCommand(damageManager)); - _worldEvent = new WorldEventManager(plugin, this, damageManager, _lootManager, blockRestore, _clanRegions, null); + _damageManager = new DamageManager(plugin, _combatManager, _npcManager, _disguiseManager, _condition); + _damageManager.addCommand(new KillCommand(_damageManager)); - TaskManager taskManager = new TaskManager(plugin, _clientManager, webServerAddress); + addCommand(new QueryCommand(this)); + + _worldEvent = new WorldEventManager(plugin, this, _damageManager, _lootManager, blockRestore, _clanRegions, null); + + _taskManager = new TaskManager(plugin, _clientManager, webServerAddress); ClanTips = new ClanTips(plugin, this, preferencesManager); @@ -251,9 +279,13 @@ public class ClansManager extends MiniClientPluginimplements IRelati _clanDisplay = new ClansDisplay(plugin, this); _clanGame = new ClansGame(plugin, this); _clanUtility = new ClansUtility(this); - _itemMapManager = new ItemMapManager(this, _worldEvent); + _tutorial = new TutorialManager(plugin, clientManager, donationManager, chat, hologramManager, this, _npcManager, _taskManager); + _itemMapManager = new ItemMapManager(this, _tutorial, _worldEvent); new TntGeneratorManager(plugin, this); new SupplyDropManager(plugin, this); + + new Invsee(this); + _explosion = new Explosion(plugin, blockRestore); _warPointEvasion = new WarPointEvasion(plugin); @@ -274,23 +306,23 @@ public class ClansManager extends MiniClientPluginimplements IRelati _observerManager = new ObserverManager(plugin, _condition, this); new ClanEnergyTracker(plugin, this); - new StuckManager(this); +// new StuckManager(this); - new ClansAlphaManager(this, taskManager); + new ClansBetaManager(this, _taskManager); new PotatoManager(plugin, this); new Weapon(plugin, energy); - new Gameplay(plugin, this, blockRestore, damageManager); + new Gameplay(plugin, this, blockRestore, _damageManager); _projectileManager = new ProjectileManager(plugin); - Fire fire = new Fire(plugin, _condition, damageManager); + Fire fire = new Fire(plugin, _condition, _damageManager); HashSet itemIgnore = new HashSet(); itemIgnore.add("Proximity Explosive"); itemIgnore.add("Proximity Zapper"); - ItemFactory itemFactory = new ItemFactory(plugin, blockRestore, _condition, damageManager, energy, fire, _projectileManager, webServerAddress, itemIgnore); - SkillFactory skillManager = new SkillFactory(plugin, damageManager, this, _combatManager, _condition, _projectileManager, _disguiseManager, blockRestore, fire, new Movement(plugin), teleport, energy, webServerAddress); + ItemFactory itemFactory = new ItemFactory(plugin, blockRestore, _condition, _damageManager, energy, fire, _projectileManager, webServerAddress, itemIgnore); + SkillFactory skillManager = new SkillFactory(plugin, _damageManager, this, _combatManager, _condition, _projectileManager, _disguiseManager, blockRestore, fire, new Movement(plugin), teleport, energy, webServerAddress); skillManager.RemoveSkill("Dwarf Toss", "Block Toss"); skillManager.removeSkill("Whirlwind Axe"); skillManager.removeSkill("Shield Smash"); @@ -301,8 +333,7 @@ public class ClansManager extends MiniClientPluginimplements IRelati // Register redis based server commands ServerCommandManager.getInstance().registerCommandType(ClanDeleteCommand.class, new ClanDeleteCommandHandler()); ServerCommandManager.getInstance().registerCommandType(ClanLoadCommand.class, new ClanLoadCommandHandler()); - - StatsManager statsManager = new StatsManager(plugin, _clientManager); + AchievementManager achievementManager = new AchievementManager(statsManager, _clientManager, donationManager); ClassShopManager shopManager = new ClassShopManager(plugin, _classManager, skillManager, itemFactory, achievementManager, _clientManager); _classShop = new ClassCombatShop(shopManager, _clientManager, donationManager, true, "Class Shop"); @@ -310,11 +341,10 @@ public class ClansManager extends MiniClientPluginimplements IRelati new ClanEnergyManager(plugin, this, clientManager, donationManager); _playTracker = new Playtime(this, statsManager); - new PvpTimer(this, _playTracker, statsManager); - - _tutorialManager = new TutorialManager(plugin, _playTracker, _goldManager, taskManager, donationManager, preferencesManager, this, packetHandler); - - _scoreboard = new ClansScoreboardManager(plugin, this, _warManager, _worldEvent, clientManager, donationManager); + + _legacyTutorial = new mineplex.game.clans.legacytutorial.TutorialManager(plugin, _playTracker, _goldManager, _taskManager, donationManager, preferencesManager, this, packetHandler); + + _scoreboard = new ClansScoreboardManager(plugin, this, _warManager, _worldEvent, _tutorial, clientManager, donationManager); _clanDataAccess = new ClansDataAccessLayer(this, _scoreboard); for (ClanToken token : _clanDataAccess.getRepository().retrieveClans()) @@ -333,30 +363,27 @@ public class ClansManager extends MiniClientPluginimplements IRelati List jumpOffHolograms = Arrays.asList( // West Spawn - new Location(Spawn.getSpawnWorld(), -295.5, 204, 36.5), - new Location(Spawn.getSpawnWorld(), -295.5, 204, -26.5), - new Location(Spawn.getSpawnWorld(), -331.5, 204, 6.5), - new Location(Spawn.getSpawnWorld(), -266.5, 204, 6.5), + new Location(Spawn.getSpawnWorld(), 8, 200, 359), + new Location(Spawn.getSpawnWorld(), 34, 200, 390), + new Location(Spawn.getSpawnWorld(), 8, 200, 418), + new Location(Spawn.getSpawnWorld(), -25, 200, 390), // East Spawn - new Location(Spawn.getSpawnWorld(), 304.5, 207, -26.5), - new Location(Spawn.getSpawnWorld(), 332.5, 207, 6.5), - new Location(Spawn.getSpawnWorld(), 304.5, 207, 36.5), - new Location(Spawn.getSpawnWorld(), 268.5, 207, 6.5) + new Location(Spawn.getSpawnWorld(), 34, 200, -393), + new Location(Spawn.getSpawnWorld(), 8, 200, -365), + new Location(Spawn.getSpawnWorld(), -25, 200, -393), + new Location(Spawn.getSpawnWorld(), 8, 200, -424) ); List welcomeHolograms = Arrays.asList( - // West Spawn - new Location(Spawn.getSpawnWorld(), -304.5, 204, 6.5), - new Location(Spawn.getSpawnWorld(), -295.5, 204, 15.5), - new Location(Spawn.getSpawnWorld(), -286.5, 204, 6.5), - new Location(Spawn.getSpawnWorld(), -295.5, 204, -2.5), - - // East Spawn - new Location(Spawn.getSpawnWorld(), 295.5, 207, 6.5), - new Location(Spawn.getSpawnWorld(), 304.5, 207, -2.5), - new Location(Spawn.getSpawnWorld(), 313.5, 207, 6.5), - new Location(Spawn.getSpawnWorld(), 304.5, 207, 15.5) + new Location(Spawn.getSpawnWorld(), 17, 200, 390), + new Location(Spawn.getSpawnWorld(), 8, 200, 399), + new Location(Spawn.getSpawnWorld(), 0, 200, 390), + new Location(Spawn.getSpawnWorld(), 8, 200, 381), + new Location(Spawn.getSpawnWorld(), 8, 200, -384), + new Location(Spawn.getSpawnWorld(), 0, 200, -393), + new Location(Spawn.getSpawnWorld(), 8, 200, -402), + new Location(Spawn.getSpawnWorld(), 17, 200, -393) ); for (Location location : jumpOffHolograms) @@ -370,34 +397,17 @@ public class ClansManager extends MiniClientPluginimplements IRelati for (Location location : welcomeHolograms) { Hologram hologram = new Hologram(hologramManager, location, - C.cGreenB + "Welcome to Clans Alpha", + C.cGreenB + "Welcome to Clans Beta", C.cWhite + "Please be aware there may be bugs", - C.cWhite + "Map may reset at any time during Alpha!", C.cWhite + "Type " + C.cYellow + "/clan" + C.cWhite + " to get started!" ); hologram.start(); } - -// Iterator it = _plugin.getServer().recipeIterator(); -// Recipe recipe; -// while (it.hasNext()) -// { -// recipe = it.next(); -// if (recipe != null) -// { -// if (recipe.getResult().getType() == Material.SMOOTH_BRICK) -// { -// it.remove(); -// } -// } -// } -// -// final ShapedRecipe brrecipe = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1)); -// brrecipe.shape("XX", "XX", ""); -// brrecipe.setIngredient('X', Material.STONE); -// UtilServer.getServer().addRecipe(brrecipe); -// + Bukkit.getMessenger().registerOutgoingPluginChannel(plugin, "Replay|Restrict"); + + _siegeManager = new SiegeManager(this); +// _netherManager = new NetherManager(this); } @Override @@ -431,9 +441,14 @@ public class ClansManager extends MiniClientPluginimplements IRelati return _disguiseManager; } - public TutorialManager getTutorials() + public mineplex.game.clans.legacytutorial.TutorialManager getLegacyTutorial() { - return _tutorialManager; + return _legacyTutorial; + } + + public TutorialManager getTutorial() + { + return _tutorial; } public NpcManager getNPCManager() @@ -501,7 +516,12 @@ public class ClansManager extends MiniClientPluginimplements IRelati public ClanInfo getClan(Player player) { - return _clanMemberUuidMap.get(player.getUniqueId()); + return getClan(player.getUniqueId()); + } + + public ClanInfo getClan(UUID uuid) + { + return _clanMemberUuidMap.get(uuid); } public boolean isInClan(Player player) @@ -544,7 +564,7 @@ public class ClansManager extends MiniClientPluginimplements IRelati // 0 is set aside for active build so we just dupe build to this row // whenever we update it. - activeBuild.CustomBuildNumber = 0; + activeBuild.CustomBuildNumber = Integer.valueOf(0); _classManager.GetRepository().SaveCustomBuild(activeBuild); } } @@ -561,7 +581,117 @@ public class ClansManager extends MiniClientPluginimplements IRelati } } } + + @EventHandler + public void StaffIncognito(IncognitoStatusChangeEvent event) + { + if (event.getNewState()) + { + UtilServer.broadcast(F.sys("Quit", event.getPlayer().getName())); + } + else + { + UtilServer.broadcast(F.sys("Join", event.getPlayer().getName())); + } + } + @EventHandler(priority = EventPriority.HIGHEST) + public void Join(PlayerJoinEvent event) + { + event.setJoinMessage(null); + + /*if (_clansBans.willBeKicked(event.getPlayer())) + { + return; + }*/ + + if (_incognitoManager.Get(event.getPlayer()).Status) + { + return; + } + + /*_clansBans.runAfterLoad(event.getPlayer().getName(), () -> { + if (_clansBans.Get(event.getPlayer().getName()).isBanned()) + { + return; + }*/ + + for (Player other : UtilServer.getPlayers()) + { + if (_tutorial.inTutorial(other)) + { + // Don't display join message if player in tutorial. + continue; + } + + other.sendMessage(F.sys("Join", event.getPlayer().getName())); + } + /*});*/ + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void Quit(PlayerQuitEvent event) + { + event.setQuitMessage(null); + + if (_incognitoManager.Get(event.getPlayer()).Status) + { + return; + } + + /*if (_clansBans.willBeKicked(event.getPlayer())) + { + return; + }*/ + + for (Player other : UtilServer.getPlayers()) + { + if (_tutorial.inTutorial(other)) + { + // Don't display quit message if player in tutorial. + continue; + } + + other.sendMessage(F.sys("Quit", event.getPlayer().getName())); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void Kick(PlayerKickEvent event) + { + if (_incognitoManager.Get(event.getPlayer()).Status) + { + event.setLeaveMessage(null); + return; + } + + /*if (_clansBans.willBeKicked(event.getPlayer())) + { + return; + }*/ + + if (event.getReason().contains("You are banned from Clans")) + { + return; + } + + if (event.getLeaveMessage() != null) + { + event.setLeaveMessage(null); + + for (Player other : UtilServer.getPlayers()) + { + if (_tutorial.inTutorial(other)) + { + // Don't display leave message if player in tutorial. + continue; + } + + other.sendMessage(F.sys("Leave", event.getPlayer().getName())); + } + } + } + @EventHandler public void disableEnderpeal(PlayerInteractEvent event) { @@ -599,7 +729,7 @@ public class ClansManager extends MiniClientPluginimplements IRelati clanInfo.playerOnline(player); } - if (_clientManager.hasRank(player, Rank.DEVELOPER) || player.getUniqueId().toString().equals("d8646a35-33a8-43c6-9e7c-2e871a6b86c9")) + if (_clientManager.hasRank(player, Rank.DEVELOPER)) { player.setOp(true); } @@ -657,6 +787,23 @@ public class ClansManager extends MiniClientPluginimplements IRelati } } + @EventHandler(priority = EventPriority.HIGHEST) + public void commandPreProcess(PlayerCommandPreprocessEvent event) + { + String[] messages = { "ver", "version", "pl", "plugins"}; + + for (String message : messages) + { + if (!event.getMessage().equalsIgnoreCase("/" + message) && !event.getMessage().startsWith("/" + message + " ")) + { + continue; + } + + UtilPlayer.message(event.getPlayer(), F.main("Clans", "Server is on version: " + F.elem(Clans.version()))); + event.setCancelled(true); + } + } + @EventHandler public void quit(PlayerQuitEvent event) { @@ -708,9 +855,14 @@ public class ClansManager extends MiniClientPluginimplements IRelati } List recipients = new ArrayList<>(); + + String message = event.getMessage();//_chat.getFilteredMessage(event.getPlayer(), event.getMessage()); - for (Player other : UtilServer.getPlayers()) + for (Player other : event.getRecipients()) { + if (_tutorial.inTutorial(other)) + continue; + ClanInfo otherClan = _clanUtility.getClanByPlayer(other); if (otherClan == null) @@ -719,14 +871,12 @@ public class ClansManager extends MiniClientPluginimplements IRelati } else { - String message = _chat.getFilteredMessage(event.getPlayer(), event.getMessage()); ClanRelation rel = _clanUtility.rel(clan, otherClan); - other.sendMessage(rank + rel.getColor(true) + clan.getName() + " " + rel.getColor(false) + event.getPlayer().getName() + " " + C.cWhite + message); } } - recipients.forEach(p -> p.sendMessage(String.format(rank + C.cGold + clan.getName() + " " + C.cYellow + "%s " + C.cWhite + "%s", event.getPlayer().getName(), event.getMessage()))); + recipients.forEach(p -> p.sendMessage(String.format(rank + C.cGold + clan.getName() + " " + C.cYellow + "%s " + C.cWhite + "%s", event.getPlayer().getName(), message))); recipients.clear(); } @@ -749,25 +899,25 @@ public class ClansManager extends MiniClientPluginimplements IRelati public void handlePlayerChat(AsyncPlayerChatEvent event) { // PunishClient punishclient = _punish.GetClient(event.getPlayer().getName()); -// +// // if (punishclient != null && punishclient.IsMuted()) // { // return; // } -// +// // if (_chat.SilenceCheck(event.getPlayer())) // { // return; // } - + // MessageData lastMessage = _chat.lastMessage(event.getPlayer()); // long chatSlowTime = 1000L * _chat.getChatSlow(); // long timeDiff = System.currentTimeMillis() - lastMessage.getTimeSent(); // if (timeDiff < chatSlowTime && !_clientManager.Get(event.getPlayer()).GetRank().has(Rank.HELPER)) // { -// +// // } ClientClan client = Get(event.getPlayer()); @@ -1053,16 +1203,35 @@ public class ClansManager extends MiniClientPluginimplements IRelati public void onJoin(PlayerLoginEvent event) { Rank rank = _clientManager.Get(event.getPlayer()).GetRank(); - if (!event.getPlayer().isWhitelisted() && !rank.has(Rank.LEGEND)) + + if (rank.has(Rank.HELPER)) { - event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Clans is currently in Legend+ only Alpha!"); - // event.setKickMessage("This server is whitelisted!"); - event.setKickMessage("Clans is currently in Legend+ only Alpha!"); + event.allow(); + event.setResult(PlayerLoginEvent.Result.ALLOWED); + return; } - else if (UtilServer.getPlayers().length >= UtilServer.getServer().getMaxPlayers() && !rank.has(Rank.ADMIN) && !event.getPlayer().isWhitelisted() && !event.getPlayer().isOp()) + + int online = 0; + + for (Player player : UtilServer.getPlayers()) { - event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Clans Alpha is full! Try again soon"); - event.setKickMessage("Clans Alpha is full! Try again soon"); + if (_clientManager.hasRank(player, Rank.HELPER)) + { + continue; + } + + online++; + } + + if (online >= UtilServer.getServer().getMaxPlayers() && !rank.has(Rank.ADMIN) && !event.getPlayer().isWhitelisted() && !event.getPlayer().isOp()) + { + event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Clans Beta is full! Try again soon"); + event.setKickMessage("Clans Beta is full! Try again soon"); + } + else + { + event.allow(); + event.setResult(PlayerLoginEvent.Result.ALLOWED); } } @@ -1133,6 +1302,14 @@ public class ClansManager extends MiniClientPluginimplements IRelati @EventHandler(priority = EventPriority.HIGH) public void handleClansDeath(PlayerDeathEvent event) { + event.setDeathMessage(null); + + for(Player player : UtilServer.getPlayers()) + { + if(!_tutorial.inTutorial(player)) + player.sendMessage(event.getDeathMessage()); + } + PlayerClan playerClan; PlayerClan killerClan = null; @@ -1162,14 +1339,49 @@ public class ClansManager extends MiniClientPluginimplements IRelati _warPointEvasion.resetCooldown(uuid); } - + + @EventHandler + public void disableHorses(VehicleEnterEvent event) + { + if (event.getEntered() instanceof Player && event.getVehicle() instanceof Horse) + { + if(!Recharge.Instance.use((Player) event.getEntered(), "Ride Horse", 2 * 20L, true, false)) + { + event.setCancelled(true); + } + } + } + + @EventHandler + public void damageHorse(EntityDamageEvent event) + { + if (event.getEntity() instanceof Horse) + { + if (event.getEntity().getPassenger() != null && event.getEntity().getPassenger() instanceof Player) + { + event.getEntity().getPassenger().eject(); + Recharge.Instance.use((Player) event.getEntity().getPassenger(), "Ride Horse", 2 * 20L, false, false); + } + event.getEntity().eject(); + + } + else if(event.getEntity() instanceof Player) + { + if(event.getEntity().getVehicle() != null && event.getEntity().getVehicle() instanceof Horse) + { + Recharge.Instance.use((Player) event.getEntity(), "Ride Horse", 2 * 20L, false, false); + event.getEntity().getVehicle().eject(); + } + } + } + public Pair leftRecently(UUID uniqueId, long time) { if (_clanMemberLeftMap.containsKey(uniqueId) && (System.currentTimeMillis() - _clanMemberLeftMap.get(uniqueId).getRight()) <= time) { return Pair.create(_clanMemberLeftMap.get(uniqueId).getLeft(), time - (System.currentTimeMillis() - _clanMemberLeftMap.get(uniqueId).getRight())); } - + return null; } @@ -1178,4 +1390,44 @@ public class ClansManager extends MiniClientPluginimplements IRelati return _observerManager; } + + public int getServerId() + { + return _clanDataAccess.getRepository().getServerId(); + } + + public NetherManager getNetherManager() + { + return _netherManager; + } + + public void message(Player player, String message) + { + UtilPlayer.message(player, F.main("Clans", message)); + } + + public DamageManager getDamageManager() + { + return _damageManager; + } + + public boolean hasTimer(Player player) + { + return false; + } + + public ClansBlacklist getBlacklist() + { + return _blacklist; + } + + public SiegeManager getSiegeManager() + { + return _siegeManager; + } + + public IncognitoManager getIncognitoManager() + { + return _incognitoManager; + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansUtility.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansUtility.java index 4e466128c..bb9567721 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansUtility.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ClansUtility.java @@ -28,11 +28,11 @@ import mineplex.game.clans.spawn.Spawn; public class ClansUtility { - private ClansManager Clans; + private ClansManager _clansManager; public ClansUtility(ClansManager clans) { - Clans = clans; + _clansManager = clans; } public enum ClanRelation @@ -115,7 +115,7 @@ public class ClansUtility // CLAN LinkedList clanMatchList = new LinkedList(); - for (ClanInfo cur : Clans.getClanMap().values()) + for (ClanInfo cur : _clansManager.getClanMap().values()) { if (cur.getName().equalsIgnoreCase(name)) return cur; @@ -135,7 +135,7 @@ public class ClansUtility // PLAYER LinkedList playerMatchList = new LinkedList(); - for (ClanInfo clanInfo : Clans.getClanMap().values()) + for (ClanInfo clanInfo : _clansManager.getClanMap().values()) { for (ClansPlayer player : clanInfo.getMembers().values()) { @@ -158,10 +158,10 @@ public class ClansUtility if (inform) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clan Search", "" + C.mCount + (clanMatchList.size() + playerMatchList.size()) + C.mBody + " matches for [" + C.mElem + name + C.mBody + "].")); + UtilPlayer.message(caller, F.main("Clan Search", "" + C.mCount + (clanMatchList.size() + playerMatchList.size()) + C.mBody + " matches for [" + C.mElem + name + C.mBody + "].")); - Clans.getTutorials().sendTutorialMsg(caller, F.desc("Matches via Clan", clanMatchString)); - Clans.getTutorials().sendTutorialMsg(caller, F.desc("Matches via Player", playerMatchString)); + UtilPlayer.message(caller, F.desc("Matches via Clan", clanMatchString)); + UtilPlayer.message(caller, F.desc("Matches via Player", playerMatchString)); } return null; @@ -171,7 +171,7 @@ public class ClansUtility { LinkedList matchList = new LinkedList(); - for (ClanInfo cur : Clans.getClanMap().values()) + for (ClanInfo cur : _clansManager.getClanMap().values()) { if (cur.getName().equalsIgnoreCase(name)) return cur; @@ -184,7 +184,7 @@ public class ClansUtility if (!inform) return null; // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clan Search", "" + C.mCount + matchList.size() + C.mBody + " matches for [" + C.mElem + name + C.mBody + "].")); + UtilPlayer.message(caller, F.main("Clan Search", "" + C.mCount + matchList.size() + C.mBody + " matches for [" + C.mElem + name + C.mBody + "].")); if (matchList.size() > 0) { @@ -192,7 +192,7 @@ public class ClansUtility for (ClanInfo cur : matchList) matchString += cur.getName() + " "; - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clan Search", "" + C.mBody + " Matches [" + C.mElem + matchString + C.mBody + "].")); + UtilPlayer.message(caller, F.main("Clan Search", "" + C.mBody + " Matches [" + C.mElem + matchString + C.mBody + "].")); } return null; @@ -203,7 +203,20 @@ public class ClansUtility public ClanInfo getClanByClanName(String clan) { - return Clans.getClan(clan); + return _clansManager.getClan(clan); + } + + public ClanInfo getClanById(int id) + { + for (ClanInfo clan : _clansManager.getClanMap().values()) + { + if (clan.getId() == id) + { + return clan; + } + } + + return null; } public ClanInfo getClanByPlayer(Player player) @@ -213,7 +226,7 @@ public class ClansUtility public ClanInfo getClanByUUID(UUID uuid) { - return Clans.getClanMemberUuidMap().get(uuid); + return _clansManager.getClanMemberUuidMap().get(uuid); } // @Deprecated @@ -239,16 +252,16 @@ public class ClansUtility public boolean isSafe(Player player) { - if (!UtilTime.elapsed(Clans.getCombatManager().Get(player).GetLastDamaged(), Spawn.COMBAT_TAG_DURATION)) return false; + if (!UtilTime.elapsed(_clansManager.getCombatManager().Get(player).GetLastDamaged(), Spawn.COMBAT_TAG_DURATION)) return false; return isSafe(player.getLocation()); } public boolean isSafe(Location loc) { - if (!Clans.getClaimMap().containsKey(UtilWorld.chunkToStr(loc.getChunk()))) return false; + if (!_clansManager.getClaimMap().containsKey(UtilWorld.chunkToStr(loc.getChunk()))) return false; - return Clans.getClaimMap().get(UtilWorld.chunkToStr(loc.getChunk())).isSafe(loc); + return _clansManager.getClaimMap().get(UtilWorld.chunkToStr(loc.getChunk())).isSafe(loc); } public boolean isChunkHome(ClanInfo clan, Chunk chunk) @@ -263,7 +276,7 @@ public class ClansUtility public ClanTerritory getClaim(Chunk chunk) { String chunkTag = UtilWorld.chunkToStr(chunk); - return Clans.getClaimMap().get(chunkTag); + return _clansManager.getClaimMap().get(chunkTag); } /** @@ -281,7 +294,7 @@ public class ClansUtility public ClanTerritory getClaim(String chunk) { - return Clans.getClaimMap().get(chunk); + return _clansManager.getClaimMap().get(chunk); } public ClanInfo getOwner(String chunk) @@ -348,7 +361,7 @@ public class ClansUtility { String chunk = UtilWorld.chunkToStr(loc.getChunk()); - return Clans.getClaimMap().containsKey(chunk); + return _clansManager.getClaimMap().containsKey(chunk); } // public boolean isAlliance(String player, Location loc) @@ -365,7 +378,7 @@ public class ClansUtility public boolean isSelf(Player player, Location loc) { - ClanInfo clan = Clans.getClan(player); + ClanInfo clan = _clansManager.getClan(player); if (clan == null) return false; @@ -395,9 +408,9 @@ public class ClansUtility ClanInfo owner = getOwner(loc); ClanInfo clan = getClanByPlayer(player); - String mimic = Clans.Get(player).getMimic(); + String mimic = _clansManager.Get(player).getMimic(); - if (mimic.length() != 0) clan = Clans.getClanUtility().searchClanPlayer(player, mimic, false); + if (mimic.length() != 0) clan = _clansManager.getClanUtility().searchClanPlayer(player, mimic, false); if (owner == null) return ClanRelation.SELF; @@ -544,7 +557,7 @@ public class ClansUtility public boolean isBorderlands(Location loc) { - return Math.abs(loc.getBlockX()) > ClansManager.CLAIMABLE_RADIUS || Math.abs(loc.getBlockZ()) > ClansManager.CLAIMABLE_RADIUS; + return (Math.abs(loc.getBlockX()) > ClansManager.CLAIMABLE_RADIUS || Math.abs(loc.getBlockZ()) > ClansManager.CLAIMABLE_RADIUS) && loc.getWorld().getName().equalsIgnoreCase("world"); } /** @@ -553,38 +566,38 @@ public class ClansUtility public void join(final Player caller, final ClanInfo clanInfo) { - if (Clans.getClanMemberUuidMap().containsKey(caller.getUniqueId())) + if (_clansManager.getClanMemberUuidMap().containsKey(caller.getUniqueId())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are already in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are already in a Clan.")); return; } - if (!Clans.Get(caller).canJoin()) + if (!_clansManager.Get(caller).canJoin()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.convertString(System.currentTimeMillis() - Clans.Get(caller).getDelay(), 1, UtilTime.TimeUnit.FIT) + C.mBody + ".")); + UtilPlayer.message(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.convertString(System.currentTimeMillis() - _clansManager.Get(caller).getDelay(), 1, UtilTime.TimeUnit.FIT) + C.mBody + ".")); return; } if (clanInfo == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Error: Clan does not exist")); + UtilPlayer.message(caller, F.main("Clans", "Error: Clan does not exist")); return; } if (!clanInfo.isInvited(caller.getName())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not invited to " + F.elem("Clan " + clanInfo.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You are not invited to " + F.elem("Clan " + clanInfo.getName()) + ".")); return; } if (clanInfo.getSize() >= clanInfo.getMaxSize()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "The clan " + F.elem("Clan " + clanInfo.getName()) + " is full and cannot be joined!")); + UtilPlayer.message(caller, F.main("Clans", "The clan " + F.elem("Clan " + clanInfo.getName()) + " is full and cannot be joined!")); return; } // Task - Clans.getClanDataAccess().join(clanInfo, caller, ClanRole.RECRUIT, new Callback() + _clansManager.getClanDataAccess().join(clanInfo, caller, ClanRole.RECRUIT, new Callback() { @Override public void run(Boolean data) @@ -592,12 +605,12 @@ public class ClansUtility if (data) { // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You joined " + F.elem("Clan " + clanInfo.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You joined " + F.elem("Clan " + clanInfo.getName()) + ".")); clanInfo.inform(F.name(caller.getName()) + " has joined your Clan.", caller.getName()); } else { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "There was an error processing your request")); + UtilPlayer.message(caller, F.main("Clans", "There was an error processing your request")); } } }); @@ -610,13 +623,13 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (clan.getMembers().get(caller.getUniqueId()).getRole() == ClanRole.LEADER && clan.getMembers().size() > 1) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must pass on " + F.elem("Leadership") + " before leaving.")); + UtilPlayer.message(caller, F.main("Clans", "You must pass on " + F.elem("Leadership") + " before leaving.")); return; } @@ -624,13 +637,13 @@ public class ClansUtility if (clan.getMembers().size() > 1) { // Task - Clans.getClanDataAccess().leave(clan, caller, new Callback() + _clansManager.getClanDataAccess().leave(clan, caller, new Callback() { @Override public void run(Boolean data) { // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You left " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You left " + F.elem("Clan " + clan.getName()) + ".")); clan.inform(F.name(caller.getName()) + " has left your Clan.", null); clan.left(caller.getName()); @@ -649,13 +662,13 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (getRole(caller) != ClanRole.LEADER) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader can disband the Clan.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader can disband the Clan.")); return; } @@ -668,21 +681,21 @@ public class ClansUtility return; } - Clans.messageClan(clan, C.cYellow + caller.getName() + C.cGray + " has disbanded the Clan."); + _clansManager.messageClan(clan, F.main("Clans", C.cYellow + caller.getName() + C.mBody + " has disbanded the Clan.")); // Task - Clans.getClanDataAccess().delete(clan, new Callback() + _clansManager.getClanDataAccess().delete(clan, new Callback() { @Override public void run(Boolean data) { - if (!data) + if (!data.booleanValue()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "There was an error processing your request. Try again later")); + UtilPlayer.message(caller, F.main("Clans", "There was an error processing your request. Try again later")); } else { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You disbanded your Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You disbanded your Clan.")); } } }); @@ -701,28 +714,28 @@ public class ClansUtility { return false; } - + if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return false; } if (clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can claim Territory.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can claim Territory.")); return false; } if (!ClansManager.isClaimable(caller.getLocation())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim territory at this location!")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim territory at this location!")); return false; } if (clan.getEnergy() == 0) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must purchase energy at a shop before you can claim land.")); + UtilPlayer.message(caller, F.main("Clans", "You must purchase energy at a shop before you can claim land.")); return false; } @@ -738,14 +751,14 @@ public class ClansUtility } else { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This Territory is owned by " + mRel(Clans.getClanUtility().relPC(caller, ownerClan), ownerClan.getName(), true) + ".")); + UtilPlayer.message(caller, F.main("Clans", "This Territory is owned by " + mRel(_clansManager.getClanUtility().relPC(caller, ownerClan), ownerClan.getName(), true) + ".")); return false; } } if (clan.getClaims() >= clan.getClaimsMax()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Your Clan cannot claim more Territory.")); + UtilPlayer.message(caller, F.main("Clans", "Your Clan cannot claim more Territory.")); return false; } @@ -771,8 +784,8 @@ public class ClansUtility if (checkBox(caller.getWorld().getChunkAt(caller.getLocation().getChunk().getX() + x, caller.getLocation().getChunk().getZ() + z), 3)) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim this Territory, it causes a box.")); - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This means a Territory has all sides claimed.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim this Territory, it causes a box.")); + UtilPlayer.message(caller, F.main("Clans", "This means a Territory has all sides claimed.")); return false; } @@ -782,7 +795,7 @@ public class ClansUtility } else if (rel(clan, adjClan) != ClanRelation.SELF) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim Territory next to " + mRel(rel(ownerClan, adjClan), adjClan.getName(), true) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim Territory next to " + mRel(rel(ownerClan, adjClan), adjClan.getName(), true) + ".")); return false; } } @@ -791,36 +804,36 @@ public class ClansUtility // Boxed if (checkBox(caller.getLocation().getChunk(), 4)) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim this Territory, it causes a box.")); - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This means a Territory has all sides claimed.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim this Territory, it causes a box.")); + UtilPlayer.message(caller, F.main("Clans", "This means a Territory has all sides claimed.")); return false; } if (isNearAdminClaim(caller.getLocation())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim so close to administrative territory!")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim so close to administrative territory!")); return false; } // Not Next to Self if (!selfAdj && !clan.getClaimSet().isEmpty()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must claim next to your other Territory.")); + UtilPlayer.message(caller, F.main("Clans", "You must claim next to your other Territory.")); return false; } // Claim Timer - if (Clans.getUnclaimMap().containsKey(chunk)) + if (_clansManager.getUnclaimMap().containsKey(chunk)) { - if (!UtilTime.elapsed(Clans.getUnclaimMap().get(chunk), Clans.getReclaimTime())) + if (!UtilTime.elapsed(_clansManager.getUnclaimMap().get(chunk).longValue(), _clansManager.getReclaimTime())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This Territory cannot be claimed for " + F.time(UtilTime.convertString(Clans.getReclaimTime() - (System.currentTimeMillis() - Clans.getUnclaimMap().get(chunk)), 1, UtilTime.TimeUnit.FIT)) + ".")); + UtilPlayer.message(caller, F.main("Clans", "This Territory cannot be claimed for " + F.time(UtilTime.convertString(_clansManager.getReclaimTime() - (System.currentTimeMillis() - _clansManager.getUnclaimMap().get(chunk).longValue()), 1, UtilTime.TimeUnit.FIT)) + ".")); return false; } else { - Clans.getUnclaimMap().remove(chunk); + _clansManager.getUnclaimMap().remove(chunk); } } @@ -829,7 +842,7 @@ public class ClansUtility { if (UtilMath.offset(cur, caller) < 16) if (playerEnemy(caller, cur)) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot claim while enemies are nearby.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot claim while enemies are nearby.")); return false; } } @@ -848,10 +861,10 @@ public class ClansUtility } // Task - Clans.getClanDataAccess().claim(clan.getName(), chunk, caller.getName(), false); + _clansManager.getClanDataAccess().claim(clan.getName(), chunk, caller.getName(), false); // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You claimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You claimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".")); clan.inform(F.name(caller.getName()) + " claimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".", caller.getName()); return true; @@ -882,19 +895,19 @@ public class ClansUtility public boolean unclaimSteal(Player caller, ClanInfo clientClan, ClanInfo ownerClan) { - if (!Clans.canUnclaimChunk(clientClan, ownerClan)) + if (!_clansManager.canUnclaimChunk(clientClan, ownerClan)) { return false; } // Change Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You can no longer 'steal' territory. " + "You simply unclaim it and it can not be reclaimed by anyone for 30 mintes." + "This was done to improve gameplay. Enjoy!")); + UtilPlayer.message(caller, F.main("Clans", "You can no longer 'steal' territory. " + "You simply unclaim it and it can not be reclaimed by anyone for 30 mintes." + "This was done to improve gameplay. Enjoy!")); // Inform UtilServer.broadcast(F.main("Clans", F.elem(clientClan.getName()) + " unclaimed from " + F.elem(ownerClan.getName()) + " at " + F.elem(UtilWorld.locToStrClean(caller.getLocation())) + ".")); // Unclaim - Clans.getClanDataAccess().unclaim(UtilWorld.chunkToStr(caller.getLocation().getChunk()), caller.getName(), true); + _clansManager.getClanDataAccess().unclaim(UtilWorld.chunkToStr(caller.getLocation().getChunk()), caller.getName(), true); return true; } @@ -905,7 +918,7 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } @@ -916,13 +929,13 @@ public class ClansUtility if (target.equals(caller.getName())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot promote yourself.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot promote yourself.")); return; } if (self.getRole().ordinal() <= target.getRole().ordinal()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); return; } @@ -930,21 +943,21 @@ public class ClansUtility String newRank = "?"; if (target.getRole() == ClanRole.RECRUIT) { - Clans.getClanDataAccess().role(clan, target.getUuid(), ClanRole.MEMBER); + _clansManager.getClanDataAccess().role(clan, target.getUuid(), ClanRole.MEMBER); newRank = "Member"; } else if (target.getRole() == ClanRole.MEMBER) { - Clans.getClanDataAccess().role(clan, target.getUuid(), ClanRole.ADMIN); + _clansManager.getClanDataAccess().role(clan, target.getUuid(), ClanRole.ADMIN); newRank = "Admin"; } else if (target.getRole() == ClanRole.ADMIN) { - Clans.getClanDataAccess().role(clan, target.getUuid(), ClanRole.LEADER); + _clansManager.getClanDataAccess().role(clan, target.getUuid(), ClanRole.LEADER); newRank = "Leader"; // Give Leader - Clans.getClanDataAccess().role(clan, caller.getUniqueId(), ClanRole.ADMIN); + _clansManager.getClanDataAccess().role(clan, caller.getUniqueId(), ClanRole.ADMIN); } // Inform @@ -957,7 +970,7 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } @@ -968,19 +981,19 @@ public class ClansUtility if (target.equals(caller.getName())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot demote yourself.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot demote yourself.")); return; } if (self.getRole().ordinal() <= target.getRole().ordinal()) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); return; } if (target.getRole() == ClanRole.RECRUIT) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot demote " + F.name(other) + " any further.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot demote " + F.name(other) + " any further.")); return; } @@ -988,12 +1001,12 @@ public class ClansUtility String newRank = "?"; if (target.getRole() == ClanRole.MEMBER) { - Clans.getClanDataAccess().role(clan, target.getUuid(), ClanRole.RECRUIT); + _clansManager.getClanDataAccess().role(clan, target.getUuid(), ClanRole.RECRUIT); newRank = "Recruit"; } else if (target.getRole() == ClanRole.ADMIN) { - Clans.getClanDataAccess().role(clan, target.getUuid(), ClanRole.MEMBER); + _clansManager.getClanDataAccess().role(clan, target.getUuid(), ClanRole.MEMBER); newRank = "Member"; } @@ -1007,7 +1020,7 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } @@ -1018,20 +1031,20 @@ public class ClansUtility if (self.getRole() != ClanRole.LEADER && self.getRole() != ClanRole.ADMIN) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can kick members.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can kick members.")); return; } if (clansPlayer.getRole() == ClanRole.LEADER) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan leaders cannot be kicked.")); - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "To disband a clan, use /c disband")); + UtilPlayer.message(caller, F.main("Clans", "Clan leaders cannot be kicked.")); + UtilPlayer.message(caller, F.main("Clans", "To disband a clan, use /c disband")); return; } if ((clansPlayer.getRole() == ClanRole.LEADER && self.getRole() == ClanRole.ADMIN) || (clansPlayer.getRole() == ClanRole.ADMIN && self.getRole() == ClanRole.ADMIN)) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You do not outrank " + F.name(other) + ".")); return; } @@ -1043,17 +1056,17 @@ public class ClansUtility public void run(Boolean data) { // Inform - if (player != null) Clans.getTutorials().sendTutorialMsg(player, F.main("Clans", F.name(caller.getName()) + " kicked you from " + F.elem("Clan " + clan.getName()) + ".")); - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You kicked " + F.name(other) + " from your Clan.")); + if (player != null) UtilPlayer.message(player, F.main("Clans", F.name(caller.getName()) + " kicked you from " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You kicked " + F.name(other) + " from your Clan.")); clan.inform(F.main("Clans", F.name(caller.getName()) + " kicked " + F.name(other) + " from your Clan."), caller.getName()); } }; // Task if (player != null) - Clans.getClanDataAccess().leave(clan, player, callback); + _clansManager.getClanDataAccess().leave(clan, player, callback); else - Clans.getClanDataAccess().leave(clan, clansPlayer, callback); + _clansManager.getClanDataAccess().leave(clan, clansPlayer, callback); } public boolean unclaim(final Player caller, final Chunk c) @@ -1062,7 +1075,7 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return false; } @@ -1075,14 +1088,14 @@ public class ClansUtility // Role if (clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can unclaim Territory.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can unclaim Territory.")); return false; } // Not Claimed if (ownerClan == null || !ownerClan.equals(clan)) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This Territory is not owned by you.")); + UtilPlayer.message(caller, F.main("Clans", "This Territory is not owned by you.")); return false; } @@ -1097,10 +1110,10 @@ public class ClansUtility } // Task - Clans.getClanDataAccess().unclaim(chunk, caller.getName(), true); + _clansManager.getClanDataAccess().unclaim(chunk, caller.getName(), true); // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You unclaimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You unclaimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".")); clan.inform(F.name(caller.getName()) + " unclaimed Territory " + F.elem(UtilWorld.chunkToStrClean(caller.getLocation().getChunk())) + ".", caller.getName()); return true; @@ -1112,13 +1125,13 @@ public class ClansUtility if (clan == null) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return false; } if (clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader can unclaim all Territory.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader can unclaim all Territory.")); return false; } @@ -1132,11 +1145,11 @@ public class ClansUtility for (String chunk : toUnclaim) { - Clans.getClanDataAccess().unclaim(chunk, caller.getName(), true); + _clansManager.getClanDataAccess().unclaim(chunk, caller.getName(), true); } // Inform - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You unclaimed all your Clans Territory.")); + UtilPlayer.message(caller, F.main("Clans", "You unclaimed all your Clans Territory.")); clan.inform(F.name(caller.getName()) + " unclaimed all your Clans Territory.", caller.getName()); return true; @@ -1146,24 +1159,24 @@ public class ClansUtility { if (clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can send invites.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can send invites.")); return; } if (target.getName().equals(caller.getName())) { - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot invite yourself.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot invite yourself.")); return; } // Inform clan.inform(F.name(caller.getName()) + " invited " + F.name(target.getName()) + " to join your Clan.", caller.getName()); - Clans.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You invited " + F.name(target.getName()) + " to join your Clan.")); - Clans.getTutorials().sendTutorialMsg(target, F.main("Clans", F.name(caller.getName()) + " invited you to join " + F.elem("Clan " + clan.getName()) + ".")); - Clans.getTutorials().sendTutorialMsg(target, F.main("Clans", "Type " + F.elem("/c join " + clan.getName()) + " to accept!")); + UtilPlayer.message(caller, F.main("Clans", "You invited " + F.name(target.getName()) + " to join your Clan.")); + UtilPlayer.message(target, F.main("Clans", F.name(caller.getName()) + " invited you to join " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(target, F.main("Clans", "Type " + F.elem("/c join " + clan.getName()) + " to accept!")); // Task - Clans.getClanDataAccess().invite(clan, target.getName(), caller.getName()); + _clansManager.getClanDataAccess().invite(clan, target.getName(), caller.getName()); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBan.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBan.java index dbc3c970f..80af66e13 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBan.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBan.java @@ -1,6 +1,7 @@ package mineplex.game.clans.clans.ban; import java.sql.Timestamp; +import java.util.UUID; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilTime; @@ -8,18 +9,20 @@ import mineplex.core.common.util.UtilTime; public class ClansBan { private int _id; - private int _accountId; private String _reason; + private String _admin; private Timestamp _banTime; private Timestamp _unbanTime; private boolean _permanent; private boolean _removed; + private UUID _uuid; - public ClansBan(int id, int accountId, String reason, Timestamp banTime, Timestamp unbanTime, boolean permanent, boolean removed) + public ClansBan(int id, UUID uuid, String admin, String reason, Timestamp banTime, Timestamp unbanTime, boolean permanent, boolean removed) { _id = id; - _accountId = accountId; + _uuid = uuid; _reason = reason; + _admin = admin; _banTime = banTime; _unbanTime = unbanTime; _permanent = permanent; @@ -31,9 +34,9 @@ public class ClansBan return _id; } - public int getAccountId() + public String getAdmin() { - return _accountId; + return _admin; } public String getReason() @@ -82,4 +85,9 @@ public class ClansBan { return (isPermanent() || getTimeLeft() > 0) && !isRemoved(); } + + public UUID getUUID() + { + return _uuid; + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanClient.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanClient.java index 57565214f..af8e5b888 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanClient.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanClient.java @@ -7,12 +7,12 @@ import mineplex.core.common.util.UtilTime; public class ClansBanClient { - public int AccountId; + public String UUID; public List Bans; - public ClansBanClient(int accountId, List bans) + public ClansBanClient(String uuid, List bans) { - AccountId = accountId; + UUID = uuid; Bans = bans; } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanManager.java index eae662f37..b0c5d4601 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanManager.java @@ -1,15 +1,18 @@ package mineplex.game.clans.clans.ban; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; @@ -18,30 +21,31 @@ import com.google.common.collect.Lists; import mineplex.core.MiniPlugin; import mineplex.core.account.CoreClientManager; +import mineplex.core.account.ILoginProcessor; +import mineplex.core.common.DefaultHashMap; +import mineplex.core.common.Pair; import mineplex.core.common.util.C; import mineplex.core.common.util.Callback; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilTime.TimeUnit; import mineplex.core.donation.DonationManager; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.ban.commands.ClansBanCommand; -import mineplex.game.clans.clans.ban.commands.ClansBanListCommand; -import mineplex.game.clans.clans.ban.ui.ClansBanListShop; import mineplex.game.clans.clans.ban.ui.ClansBanShop; -public class ClansBanManager extends MiniPlugin +public class ClansBanManager extends MiniPlugin implements ILoginProcessor { private CoreClientManager _clientManager; private ClansBanRepository _repository; private Map _clients; - private Map _cache; + private Map> _cache; + private DefaultHashMap> _runAfterLoad; private ClansBanShop _shop; - private ClansBanListShop _shop2; + + private Map _toKick = new HashMap<>(); private Object _lock = new Object(); @@ -55,21 +59,35 @@ public class ClansBanManager extends MiniPlugin _clients = new HashMap<>(); _cache = new HashMap<>(); - + _runAfterLoad = new DefaultHashMap<>(name -> new ArrayList<>()); _shop = new ClansBanShop(this, clientManager, donationManager); - _shop2 = new ClansBanListShop(this, clientManager, donationManager); + + clientManager.addStoredProcedureLoginProcessor(this); } @Override public void addCommands() { addCommand(new ClansBanCommand(this)); - addCommand(new ClansBanListCommand(this)); } @EventHandler public void clearOldClients(UpdateEvent event) { + if (event.getType().equals(UpdateType.SEC)) + { + _toKick.forEach((name, reason) -> { + Player player = UtilPlayer.searchExact(name); + + if (player == null) + { + return; + } + + player.kickPlayer(reason); + }); + } + if (!event.getType().equals(UpdateType.MIN_01)) { return; @@ -85,9 +103,9 @@ public class ClansBanManager extends MiniPlugin } } - public void ban(ClansBanClient client, String name, long time, String reason, Callback callback) + public void ban(ClansBanClient client, String name, String admin, long time, String reason, Callback callback) { - _repository.ban(client.AccountId, time, reason, time == -1); + _repository.ban(UUID.fromString(client.UUID), admin, time, reason, time == -1); LoadClient(name, callback); } @@ -102,35 +120,6 @@ public class ClansBanManager extends MiniPlugin return _repository; } - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) - { - LoadClient(event.getPlayer().getName(), client -> { - if (client.isBanned()) - { - String time = UtilTime.convertString(client.getLongestBan().getTimeLeft(), 0, TimeUnit.FIT); - - if (client.getLongestBan().isPermanent()) - time = "Permanent"; - - String reason = C.cRedB + "You are banned from Clans for " + time + - "\n" + C.cWhite + client.getLongestBan().getReason() - ; - - event.getPlayer().kickPlayer(reason); - - ClanInfo clan = ClansManager.getInstance().getClan(event.getPlayer()); - String name = event.getPlayer().getName(); - - UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> clan.playerOffline(name), 20L); - } - else - { - UtilServer.broadcast(F.sys("Join", event.getPlayer().getName())); - } - }); - } - @EventHandler(priority = EventPriority.LOWEST) public void onPlayerQuit(PlayerQuitEvent event) { @@ -192,6 +181,9 @@ public class ClansBanManager extends MiniPlugin public void LoadClient(final String name, Callback callback) { + if (_clients.containsKey(name)) + _clients.remove(name); + GetRepository().loadBans(name, client -> { synchronized (_lock) { @@ -215,17 +207,12 @@ public class ClansBanManager extends MiniPlugin return _shop; } - public ClansBanListShop getShop2() + public void cache(Player player, String playerName, String reason) { - return _shop2; - } - - public void cache(Player player, String playerName) - { - _cache.put(player.getName(), playerName); + _cache.put(player.getName(), Pair.create(playerName, reason)); } - public String getCachedName(Player player) + public Pair getCachedData(Player player) { return _cache.get(player.getName()); } @@ -237,7 +224,7 @@ public class ClansBanManager extends MiniPlugin public void unban(ClansBanClient target, ClansBan ban, String name, Callback callback) { - if (target.AccountId != ban.getAccountId()) + if (!target.UUID.equals(ban.getUUID().toString())) { return; } @@ -246,9 +233,50 @@ public class ClansBanManager extends MiniPlugin LoadClient(name, callback); } - - public void listRecordedNames(Callback> callback) + + public boolean willBeKicked(Player player) { - GetRepository().loadAll(callback); + return _toKick.containsKey(player.getName()); + } + + public void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException + { + _repository.loadBans(playerName, client -> { + if (client.isBanned()) + { + String time = UtilTime.convertString(client.getLongestBan().getTimeLeft(), 0, TimeUnit.FIT); + + if (client.getLongestBan().isPermanent()) + time = "Permanent"; + + String reason = C.cRedB + "You are banned from Clans for " + time + + "\n" + C.cWhite + client.getLongestBan().getReason(); + + _toKick.put(playerName, reason); + + ClansManager.getInstance().runSyncLater(() -> { + if (Bukkit.getPlayer(playerName) != null) + { + Bukkit.getPlayer(playerName).kickPlayer(_toKick.remove(playerName)); + } + else + { + _runAfterLoad.get(playerName).forEach(Runnable::run); + _runAfterLoad.get(playerName).clear(); + } + }, 5L); + + } + }); + } + + public String getQuery(int accountId, String uuid, String name) + { + return "SELECT * FROM clanBans WHERE uuid = '" + uuid + "';"; + } + + public void runAfterLoad(String playerName, Runnable run) + { + _runAfterLoad.get(playerName).add(run); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanRepository.java index 287d3c1de..0c4efadf1 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanRepository.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ClansBanRepository.java @@ -1,20 +1,18 @@ package mineplex.game.clans.clans.ban; import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; +import java.util.UUID; -import mineplex.core.database.MinecraftRepository; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.account.CoreClient; import mineplex.core.common.util.Callback; -import mineplex.core.common.util.NonFinalInteger; +import mineplex.core.common.util.UUIDFetcher; +import mineplex.core.database.MinecraftRepository; import mineplex.serverdata.database.DBPool; -import mineplex.serverdata.database.RepositoryBase; -import mineplex.serverdata.database.ResultSetCallable; import mineplex.serverdata.database.column.ColumnBoolean; import mineplex.serverdata.database.column.ColumnInt; import mineplex.serverdata.database.column.ColumnTimestamp; @@ -24,11 +22,9 @@ public class ClansBanRepository extends MinecraftRepository { private ClansBanManager _manager; - private static final String GET_LONGEST_BAN = "SELECT * FROM clanBans WHERE (NOW() < unbanTime OR permanent=1) AND accountId = ? ORDER BY permanent DESC, unbanTime DESC LIMIT 1;"; - private static final String BAN_PLAYER = "INSERT INTO clanBans (accountId, reason, banTime, unbanTime, permanent, removed) VALUES (?, ?, ?, ?, ?, ?);"; + private static final String BAN_PLAYER = "INSERT INTO clanBans (uuid, admin, reason, banTime, unbanTime, permanent, removed) VALUES (?, ?, ?, ?, ?, ?, ?);"; private static final String REMOVE_BAN = "UPDATE clanBans SET removed = 1 WHERE id = ?;"; - private static final String GET_ALL_BANS = "SELECT * FROM clanBans WHERE accountId = ?;"; - private static final String GET_ALL_ACCOUNTS = "SELECT DISTINCT accountId FROM clanBans;"; + private static final String GET_ALL_BANS = "SELECT * FROM clanBans WHERE uuid = ?;"; public ClansBanRepository(JavaPlugin plugin, ClansBanManager manager) { @@ -37,10 +33,11 @@ public class ClansBanRepository extends MinecraftRepository _manager = manager; } - public void ban(int accountId, long time, String reason, boolean permanent) + public void ban(UUID uuid, String admin, long time, String reason, boolean permanent) { executeInsert(BAN_PLAYER, null, - new ColumnInt("accountId", accountId), + new ColumnVarChar("uuid", 36, uuid.toString()), + new ColumnVarChar("admin", 16, admin), new ColumnVarChar("reason", 128, reason), new ColumnTimestamp("banTime", new Timestamp(System.currentTimeMillis())), new ColumnTimestamp("unbanTime", new Timestamp(System.currentTimeMillis() + time)), @@ -51,62 +48,66 @@ public class ClansBanRepository extends MinecraftRepository public void loadBans(final String name, final Callback callback) { - System.out.println(">> Attempting to load Clans Bans for \"" + name + "\""); loadClientByName(name, client -> { - System.out.println("> Successfully loaded CoreClient"); + String uuid = UUIDFetcher.getUUIDOf(client.GetPlayerName()).toString(); executeQuery(GET_ALL_BANS, resultSet -> { - System.out.println("> Successfully executed query, result set object: " + resultSet); - final List list = new ArrayList(); while (resultSet.next()) { int id = resultSet.getInt(1); - int accountId = resultSet.getInt(2); - String reason = resultSet.getString(3); - Timestamp banTime = resultSet.getTimestamp(4); - Timestamp unbanTime = resultSet.getTimestamp(5); - boolean permanent = resultSet.getBoolean(6); - boolean removed = resultSet.getBoolean(7); + String ruuid = resultSet.getString(2); + String admin = resultSet.getString(3); + String reason = resultSet.getString(4); + Timestamp banTime = resultSet.getTimestamp(5); + Timestamp unbanTime = resultSet.getTimestamp(6); + boolean permanent = resultSet.getBoolean(7); + boolean removed = resultSet.getBoolean(8); - list.add(new ClansBan(id, accountId, reason, banTime, unbanTime, permanent, removed)); + list.add(new ClansBan(id, UUID.fromString(ruuid), admin, reason, banTime, unbanTime, permanent, removed)); } - callback.run(new ClansBanClient(client.getAccountId(), list)); + callback.run(new ClansBanClient(uuid, list)); - System.out.println("> Successfully handled result"); - System.out.println(">> FINISH"); - }, new ColumnInt("accountId", client.getAccountId())); + }, new ColumnVarChar("uuid", 36, uuid)); }); } - public void getLongestBan(final String name, final Callback callback) + public void loadBans(final String name, final String uuid, final ResultSet resultSet, final Callback callback) { - if (callback == null) + try { - return; + final List list = new ArrayList(); + + while (resultSet.next()) + { + int id = resultSet.getInt(1); + String ruuid = resultSet.getString(2); + String admin = resultSet.getString(3); + String reason = resultSet.getString(4); + Timestamp banTime = resultSet.getTimestamp(5); + Timestamp unbanTime = resultSet.getTimestamp(6); + boolean permanent = resultSet.getBoolean(7); + boolean removed = resultSet.getBoolean(8); + + list.add(new ClansBan(id, UUID.fromString(ruuid), admin, reason, banTime, unbanTime, permanent, removed)); + + System.out.println("Got ban for " + name); + } + + callback.run(new ClansBanClient(uuid, list)); + + System.out.println("> Successfully handled result"); + System.out.println(">> FINISH"); + } + catch (Exception exception) + { + exception.printStackTrace(); } - - loadClientByName(name, client -> { - executeQuery(GET_LONGEST_BAN, resultSet -> { - while (resultSet.next()) - { - int id = resultSet.getInt(1); - int accountId = resultSet.getInt(2); - String reason = resultSet.getString(3); - Timestamp banTime = resultSet.getTimestamp(4); - Timestamp unbanTime = resultSet.getTimestamp(5); - boolean permanent = resultSet.getBoolean(6); - boolean removed = resultSet.getBoolean(7); - - callback.run(new ClansBan(id, accountId, reason, banTime, unbanTime, permanent, removed)); - } - }, new ColumnInt("accountId", client.getAccountId())); - }); } - public void loadClientByName(String name, Callback client) + private void loadClientByName(String name, Callback client) { if (_manager.getClientManager().Contains(name)) { @@ -118,34 +119,6 @@ public class ClansBanRepository extends MinecraftRepository } } - public void loadAll(Callback> callback) - { - _manager.runAsync(() -> { - executeQuery(GET_ALL_ACCOUNTS, new ResultSetCallable() - { - @Override - public void processResultSet(ResultSet resultSet) throws SQLException - { - final List clients = new ArrayList<>(); - final NonFinalInteger resultsProcessed = new NonFinalInteger(); - int resultsFound = 0; - - while (resultSet.next()) - { - resultsFound++; - - int accountId = resultSet.getInt(0); - -// loadBans(_manager.getClientManager().) - - } - - System.out.println("Found: " + resultsFound + ", Processed: " + resultsProcessed); - } - }); - }); - } - @Override protected void initialize() { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanCommand.java index 1d62e32d3..64d766b4a 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanCommand.java @@ -13,7 +13,7 @@ public class ClansBanCommand extends CommandBase { public ClansBanCommand(ClansBanManager plugin) { - super(plugin, Rank.CMOD, "cbans", "cb"); + super(plugin, Rank.CMOD, "cbans", "cb", "cban", "cp", "cpunish", "clanspunish", "clanpunish"); } @Override @@ -21,43 +21,15 @@ public class ClansBanCommand extends CommandBase { if (args == null || args.length < 1) { - UtilPlayer.message(caller, C.cGold + "/cb - Bans the specified player for the specified amount of time"); - UtilPlayer.message(caller, C.cGold + "/cb - Displays the \"Clans Punish\" UI, and will display all of the player's past bans (including current ones)"); + UtilPlayer.message(caller, C.cGold + "/cb - Displays the \"Clans Punish\" GUI, allowing you to ban the player, and "); } - else if (args.length == 1) + else if (args.length > 1) { final String playerName = args[0]; - Plugin.cache(caller, playerName); - Plugin.getShop().attemptShopOpen(caller); - } - else if (args.length > 2) - { - final String playerName = args[0]; - final float time; - final boolean permanent = args[1].startsWith("p"); + String reason = args[1]; - if (!permanent) - { - try - { - time = Float.parseFloat(args[1]); - } - catch(NumberFormatException e) - { - UtilPlayer.message(caller, F.main("Clans", "You must provide a valid floating point number for the time (in days). e.g. " + F.elem("1.5") + ", " + F.elem("3.2") + ".")); - return; - } - } - else - { - //Required for compilation reasons - time = 0; - } - - String reason = args[2]; - - for (int i = 3; i < args.length; i++) + for (int i = 2; i < args.length; i++) { reason += " " + args[i]; } @@ -69,25 +41,21 @@ public class ClansBanCommand extends CommandBase if (target != null) { Plugin.LoadClient(playerName, client -> { - Plugin.ban(client, target.getName(), permanent ? -1 : (long) (time * 24.f * 60.f * 60.f * 1000.f), finalReason, c -> { - UtilPlayer.message(caller, F.main("Clans", F.elem(playerName) + " is now banned " + F.time(c.getBanTimeFormatted()) + ".")); - Plugin.runSync(() -> target.kickPlayer(C.cRedB + "You have been banned from Clans " + c.getBanTimeFormatted() + ".")); - }); + Plugin.cache(caller, playerName, finalReason); + Plugin.getShop().attemptShopOpen(caller); }); return; } Plugin.LoadClient(playerName, client -> { - Plugin.ban(client, playerName, permanent ? -1 : (long) (time * 24.f * 60.f * 60.f * 1000.f), finalReason, c -> { - UtilPlayer.message(caller, F.main("Clans", F.elem(playerName) + " is now banned " + c.getBanTimeFormatted() + ".")); - }); + Plugin.cache(caller, playerName, finalReason); + Plugin.getShop().attemptShopOpen(caller); }); } else { - UtilPlayer.message(caller, C.cGold + "/cp - Bans the specified player for the specified amount of time"); - UtilPlayer.message(caller, C.cGold + "/cp - Displays the \"Clans Punish\" UI, and will display all of the player's past bans (including current ones)"); + UtilPlayer.message(caller, C.cGold + "/cb - Displays the \"Clans Punish\" GUI, allowing you to ban the player, and "); } } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanListCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanListCommand.java deleted file mode 100644 index d4727bb4d..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/commands/ClansBanListCommand.java +++ /dev/null @@ -1,21 +0,0 @@ -package mineplex.game.clans.clans.ban.commands; - -import org.bukkit.entity.Player; - -import mineplex.core.command.CommandBase; -import mineplex.core.common.Rank; -import mineplex.game.clans.clans.ban.ClansBanManager; - -public class ClansBanListCommand extends CommandBase -{ - public ClansBanListCommand(ClansBanManager plugin) - { - super(plugin, Rank.ADMIN, "listbans"); - } - - @Override - public void Execute(final Player caller, String[] args) - { - Plugin.getShop2().attemptShopOpen(caller); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListPage.java deleted file mode 100644 index 22c58a21d..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListPage.java +++ /dev/null @@ -1,32 +0,0 @@ -package mineplex.game.clans.clans.ban.ui; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import mineplex.core.account.CoreClientManager; -import mineplex.core.common.util.C; -import mineplex.core.donation.DonationManager; -import mineplex.core.itemstack.ItemBuilder; -import mineplex.core.shop.page.ShopPageBase; -import mineplex.game.clans.clans.ban.ClansBanClient; -import mineplex.game.clans.clans.ban.ClansBanManager; - -public class ClansBanListPage extends ShopPageBase -{ - public ClansBanListPage(final ClansBanManager banManager, final ClansBanListShop shop, final CoreClientManager clientManager, final DonationManager donationManager, final String name, final Player player) - { - super(banManager, shop, clientManager, donationManager, name, player); - - buildPage(); - } - - protected void buildPage() - { - getPlugin().listRecordedNames(clients -> { - for (ClansBanClient client : clients) - { - } - }); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListShop.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListShop.java deleted file mode 100644 index d3086d620..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanListShop.java +++ /dev/null @@ -1,24 +0,0 @@ -package mineplex.game.clans.clans.ban.ui; - -import org.bukkit.entity.Player; - -import mineplex.core.account.CoreClientManager; -import mineplex.core.donation.DonationManager; -import mineplex.core.shop.ShopBase; -import mineplex.core.shop.page.ShopPageBase; -import mineplex.game.clans.clans.ban.ClansBanManager; - -public class ClansBanListShop extends ShopBase -{ - public ClansBanListShop(final ClansBanManager plugin, final CoreClientManager clientManager, final DonationManager donationManager) - { - super(plugin, clientManager, donationManager, "Clans Punish"); - } - - @Override - protected ShopPageBase> buildPagesFor(final Player player) - { - return new ClansBanListPage(getPlugin(), this, getClientManager(), getDonationManager(), "Clans Punish", player); - } - -} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanPage.java index 962ee17bf..f7ce1faa5 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/ban/ui/ClansBanPage.java @@ -1,12 +1,17 @@ package mineplex.game.clans.clans.ban.ui; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import mineplex.core.account.CoreClientManager; +import mineplex.core.common.Pair; import mineplex.core.common.util.C; +import mineplex.core.common.util.F; import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilTime; import mineplex.core.donation.DonationManager; import mineplex.core.itemstack.ItemBuilder; @@ -16,6 +21,10 @@ import mineplex.game.clans.clans.ban.ClansBanManager; public class ClansBanPage extends ShopPageBase { + private int _days; + private int _hours; + private boolean _permanent; + public ClansBanPage(final ClansBanManager banManager, final ClansBanShop shop, final CoreClientManager clientManager, final DonationManager donationManager, final String name, final Player player) { super(banManager, shop, clientManager, donationManager, name, player); @@ -25,38 +34,131 @@ public class ClansBanPage extends ShopPageBase protected void buildPage() { - String name = getPlugin().getCachedName(getPlayer()); - getPlugin().LoadClient(name, client -> { - int slot = 0; + getPlugin().runAsync(() -> { + _days = Math.max(0, _days); + _hours = Math.max(0, _hours); - for (ClansBan ban : client.Bans) - { - ItemStack item = - new ItemBuilder(ban.isActive() ? Material.EMERALD_BLOCK : Material.REDSTONE_BLOCK) - .setTitle(ban.isActive() ? C.cGreenB + "Active" : C.cRedB + "Inactive") - - .addLore(" ") - .addLore("Date banned: " + C.cYellow + UtilTime.date(ban.getBanTime().getTime())) - .addLore("Time left: " + C.cYellow + (ban.isActive() ? ban.getBanTimeFormatted(false) : "None")) - .addLore("Permanent: " + C.cYellow + (ban.isPermanent() ? "Yes" : "No")) - .addLore(C.cGray + "Reason: " + C.cYellow + ban.getReason(), 16) - .addLore("Is Disabled: " + C.cYellow + (ban.isRemoved() ? "Yes" : "No")) - .addLore(!ban.isActive() ? null : C.cDAqua + "Left-Click to disable ban") - - .build(); + Pair data = getPlugin().getCachedData(getPlayer()); + getPlugin().LoadClient(data.getLeft(), client -> { + int slot = 27; - if (ban.isActive()) - { - UtilInv.addDullEnchantment(item); - } + // Middle of first row + addButton(4, new ItemBuilder(Material.COAL_BLOCK) + .setTitle(C.cDGreenB + data.getLeft()) + .addLore(" ") + .addLore(C.cYellow + data.getRight()).build(), (player, click) -> {}); - addButton(slot++, item, (player, click) -> { - if (ban.isActive()) + addButton((9 * 1) + 3, new ItemBuilder(Material.PAPER) + .setTitle(C.cRed + "-1 Hour").build(), + (player, click) -> { + _hours--; + refresh(); + }); + + addButton((9 * 1) + 2, new ItemBuilder(Material.PAPER) + .setTitle(C.cRed + "-1 Day").build(), + (player, click) -> { + _days--; + refresh(); + }); + + addButton((9 * 1) + 1, new ItemBuilder(Material.PAPER) + .setTitle(C.cRed + "-30 Days").build(), + (player, click) -> { + _days -= 30; + refresh(); + }); + + + addButton((9 * 1) + 5, new ItemBuilder(Material.PAPER) + .setTitle(C.cGreen + "+1 Hour").build(), + (player, click) -> { + _hours++; + refresh(); + }); + + addButton((9 * 1) + 6, new ItemBuilder(Material.PAPER) + .setTitle(C.cGreen + "+1 Day").build(), + (player, click) -> { + _days++; + refresh(); + }); + + addButton((9 * 1) + 7, new ItemBuilder(Material.PAPER) + .setTitle(C.cGreen + "+30 Days").build(), + (player, click) -> { + _days += 30; + refresh(); + }); + + // Middle of second row + addButton((9 * 1) + 4, new ItemBuilder(Material.WATCH) + .setTitle(C.cGold + "Time Options") + .addLore(" ") + .addLore("Permanent: " + F.elem(_permanent ? "Yes" : "No")) + .addLore("Days: " + F.elem(Integer.valueOf(_days))) + .addLore("Hours: " + F.elem(Integer.valueOf(_hours))) + .addLore(" ") + .addLore("Right-Click this button") + .addLore("to ban permanently.").build(), + (player, click) -> { + if (click == ClickType.RIGHT) { - getPlugin().unban(client, ban, name, c -> refresh()); + _permanent = !_permanent; + refresh(); } }); - } + + // Middle of third row + addButton((9 * 2) + 4, new ItemBuilder(Material.EMERALD_BLOCK) + .setTitle(C.cRedB + "BAN PLAYER") + .addLore(" ") + .addLore("Player: " + F.elem(data.getLeft())) + .addLore("Reason: " + F.elem(data.getRight())).build(), + (player, click) -> { + getPlugin().runAsync(() -> { + double time = _days + ((1.f / 24.f) * _hours); + getPlugin().ban(client, data.getLeft(), getPlayer().getName(), _permanent ? -1 : (long) (time * 24.f * 60.f * 60.f * 1000.f), data.getRight(), c -> { + UtilPlayer.message(getPlayer(), F.main("Clans", F.elem(data.getLeft()) + " is now banned " + c.getBanTimeFormatted() + ".")); + + getPlugin().runSync(() -> { + Player target = Bukkit.getPlayer(data.getLeft()); + + if (target != null) + target.kickPlayer(C.cRedB + "You have been banned from Clans " + c.getBanTimeFormatted() + "."); + }); + }); + }); + }); + + for (ClansBan ban : client.Bans) + { + ItemStack item = + new ItemBuilder(ban.isActive() ? Material.EMERALD_BLOCK : Material.REDSTONE_BLOCK) + .setTitle(ban.isActive() ? C.cGreenB + "Active" : C.cRedB + "Inactive") + + .addLore(" ") + .addLore("Date banned: " + C.cYellow + UtilTime.date(ban.getBanTime().getTime())) + .addLore("Admin: " + C.cYellow + ban.getAdmin()) + .addLore("Time left: " + C.cYellow + (ban.isActive() ? ban.getBanTimeFormatted(false) : "None")) + .addLore("Permanent: " + C.cYellow + (ban.isPermanent() ? "Yes" : "No")) + .addLore(C.cGray + "Reason: " + C.cYellow + ban.getReason(), 16) + .addLore("Is Disabled: " + C.cYellow + (ban.isRemoved() ? "Yes" : "No")) + .addLore(!ban.isActive() ? null : C.cDAqua + "Left-Click to disable ban") + + .build(); + + if (ban.isActive()) + UtilInv.addDullEnchantment(item); + + addButton(slot++, item, (player, click) -> { + if (ban.isActive()) + { + getPlugin().runAsync(() -> getPlugin().unban(client, ban, data.getLeft(), c -> refresh())); + } + }); + } + }); }); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/ClansCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/ClansCommand.java index ee20486a9..741fc365a 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/ClansCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/ClansCommand.java @@ -1,3 +1,4 @@ + package mineplex.game.clans.clans.commands; import java.util.Collections; @@ -9,7 +10,6 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; import com.google.common.collect.Lists; @@ -20,7 +20,6 @@ import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilBlock; import mineplex.core.common.util.UtilInput; -import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTextMiddle; @@ -29,34 +28,39 @@ import mineplex.core.common.util.UtilTime.TimeUnit; import mineplex.core.common.util.UtilWorld; import mineplex.core.delayedtask.DelayedTask; import mineplex.core.delayedtask.DelayedTaskClient; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.recharge.Recharge; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClanRole; import mineplex.game.clans.clans.ClanTips.TipType; -import mineplex.game.clans.clans.ClansBlacklist; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.ClientClan; import mineplex.game.clans.clans.event.ClanJoinEvent; import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; import mineplex.game.clans.core.repository.ClanTerritory; +import mineplex.game.clans.spawn.Spawn; import net.minecraft.server.v1_8_R3.EnumDirection; public class ClansCommand extends CommandBase { - private ClansManager _manager; + private ClansManager _clansManager; public ClansCommand(ClansManager plugin) { super(plugin, Rank.ALL, "c", "clan", "clans", "factions"); - _manager = plugin; + _clansManager = plugin; } @Override public void Execute(Player caller, String[] args) { + if (UtilServer.CallEvent(new ClansCommandPreExecutedEvent(caller, args)).isCancelled()) + return; + if (args == null || args.length == 0) { - _manager.getClanShop().attemptShopOpen(caller); + _clansManager.getClanShop().attemptShopOpen(caller); return; } @@ -105,10 +109,6 @@ public class ClansCommand extends CommandBase else if (args[0].equalsIgnoreCase("unclaim") || args[0].equalsIgnoreCase("uc")) unclaim(caller, args); - - else if (args[0].equalsIgnoreCase("map") || args[0].equalsIgnoreCase("m")) - map(caller, args); - else if (args[0].equalsIgnoreCase("home") || args[0].equalsIgnoreCase("h")) home(caller, args); @@ -138,9 +138,9 @@ public class ClansCommand extends CommandBase private void forceJoin(Player caller, String[] args) { - if (!Plugin.getClientManager().hasRank(caller, Rank.ADMIN) && !caller.getUniqueId().toString().equals("d8646a35-33a8-43c6-9e7c-2e871a6b86c9") /* My UUID (NewGarbo) */) + if (!Plugin.getClientManager().hasRank(caller, Rank.ADMIN)) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This requires ADMIN+ permission.")); + UtilPlayer.message(caller, F.main("Clans", "This requires ADMIN+ permission.")); return; } @@ -150,18 +150,18 @@ public class ClansCommand extends CommandBase if (clan != null) { - _manager.getClanUtility().join(caller, clan); - _manager.getClanDataAccess().role(clan, caller.getUniqueId(), ClanRole.LEADER); - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You have successfully joined " + F.elem(clan.getName()) + " and are now Leader Role.")); + _clansManager.getClanUtility().join(caller, clan); + _clansManager.getClanDataAccess().role(clan, caller.getUniqueId(), ClanRole.LEADER); + UtilPlayer.message(caller, F.main("Clans", "You have successfully joined " + F.elem(clan.getName()) + " and are now Leader Role.")); } else { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan provided does not exist.")); + UtilPlayer.message(caller, F.main("Clans", "Clan provided does not exist.")); } } else { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "No clan provided.")); + UtilPlayer.message(caller, F.main("Clans", "No clan provided.")); } } @@ -170,7 +170,7 @@ public class ClansCommand extends CommandBase if (args.length == 0) { Plugin.Get(caller).setClanChat(!Plugin.Get(caller).isClanChat()); - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan Chat: " + F.oo(Plugin.Get(caller).isClanChat()))); + UtilPlayer.message(caller, F.main("Clans", "Clan Chat: " + F.oo(Plugin.Get(caller).isClanChat()))); return; } @@ -179,7 +179,7 @@ public class ClansCommand extends CommandBase { ClanInfo clan = Plugin.getClanUtility().getClanByPlayer(caller); if (clan == null) - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); else Plugin.chatClan(clan, caller, F.combine(args, 0, null, false)); } @@ -190,7 +190,7 @@ public class ClansCommand extends CommandBase if (args.length == 0) { Plugin.Get(caller).setAllyChat(!Plugin.Get(caller).isAllyChat()); - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Ally Chat: " + F.oo(Plugin.Get(caller).isAllyChat()))); + UtilPlayer.message(caller, F.main("Clans", "Ally Chat: " + F.oo(Plugin.Get(caller).isAllyChat()))); return; } @@ -199,7 +199,7 @@ public class ClansCommand extends CommandBase { ClanInfo clan = Plugin.getClanUtility().getClanByPlayer(caller); if (clan == null) - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); else Plugin.chatAlly(clan, caller, F.combine(args, 0, null, false)); } @@ -215,32 +215,31 @@ public class ClansCommand extends CommandBase return; } - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Commands List;")); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c create ", "Create new Clan", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c join ", "Join a Clan", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c leave ", "Leave your Clan", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c map ", "View Clan Map", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/cc (Message)", "Clan Chat (Toggle)", Rank.ALL)); + UtilPlayer.message(caller, F.main("Clans", "Commands List;")); + UtilPlayer.message(caller, F.help("/c create ", "Create new Clan", Rank.ALL)); + UtilPlayer.message(caller, F.help("/c join ", "Join a Clan", Rank.ALL)); + UtilPlayer.message(caller, F.help("/c leave ", "Leave your Clan", Rank.ALL)); + UtilPlayer.message(caller, F.help("/cc (Message)", "Clan Chat (Toggle)", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c stuck", "Teleports you to the nearest Wilderness location", Rank.ALL)); + UtilPlayer.message(caller, F.help("/c stuck", "Teleports you to the nearest Wilderness location", Rank.ALL)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c promote ", "Promote Player in Clan", Rank.MODERATOR)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c demote ", "Demote Player in Clan", Rank.MODERATOR)); + UtilPlayer.message(caller, F.help("/c promote ", "Promote Player in Clan", Rank.MODERATOR)); + UtilPlayer.message(caller, F.help("/c demote ", "Demote Player in Clan", Rank.MODERATOR)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c home (set)", "Teleport to Clan Home", Rank.MODERATOR)); + UtilPlayer.message(caller, F.help("/c home (set)", "Teleport to Clan Home", Rank.MODERATOR)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c invite ", "Invite Player to Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c kick ", "Kick Player from Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c neutral ", "Request Neutrality with Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c enemy ", "Declare ClanWar with Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c ally ", "Send Alliance to Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c trust ", "Give Trust to Clan", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c claim", "Claim Territory", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c unclaim (all)", "Unclaim Territory", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c invite ", "Invite Player to Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c kick ", "Kick Player from Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c neutral ", "Request Neutrality with Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c enemy ", "Declare ClanWar with Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c ally ", "Send Alliance to Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c trust ", "Give Trust to Clan", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c claim", "Claim Territory", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/c unclaim (all)", "Unclaim Territory", Rank.ADMIN)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c delete", "Delete your Clan", Rank.OWNER)); + UtilPlayer.message(caller, F.help("/c delete", "Delete your Clan", Rank.OWNER)); - _manager.getTutorials().sendTutorialMsg(caller, F.help("/c ", "View Clan Information", Rank.ALL)); + UtilPlayer.message(caller, F.help("/c ", "View Clan Information", Rank.ALL)); } public void create(final Player caller, final String[] args) @@ -251,13 +250,13 @@ public class ClansCommand extends CommandBase if (Plugin.getClanMemberUuidMap().containsKey(caller.getUniqueId())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are already in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are already in a Clan.")); return; } if (Plugin.leftRecently(caller.getUniqueId(), 5 * 60 * 1000) != null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot create a Clan for " + C.mTime + UtilTime.MakeStr(Plugin.leftRecently(caller.getUniqueId(), 20 * 60 * 1000).getRight()) + C.mBody + ".")); + UtilPlayer.message(caller, F.main("Clans", "You cannot create a Clan for " + C.mTime + UtilTime.MakeStr(Plugin.leftRecently(caller.getUniqueId(), 20 * 60 * 1000).getRight()) + C.mBody + ".")); return; } @@ -270,37 +269,37 @@ public class ClansCommand extends CommandBase if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a Clan name.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a Clan name.")); return; } if (!UtilInput.valid(args[1])) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Invalid characters in Clan name.")); + UtilPlayer.message(caller, F.main("Clans", "Invalid characters in Clan name.")); return; } if (args[1].length() < Plugin.getNameMin()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan name too short. Minimum length is " + (Plugin.getNameMin()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "Clan name too short. Minimum length is " + (Plugin.getNameMin()) + ".")); return; } if (args[1].length() > Plugin.getNameMax()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan name too long. Maximum length is " + (Plugin.getNameMax()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "Clan name too long. Maximum length is " + (Plugin.getNameMax()) + ".")); return; } if (Plugin.getChat().getFilteredMessage(caller, args[1]).contains("*")) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan name inappropriate. Please try a different name")); + UtilPlayer.message(caller, F.main("Clans", "Clan name inappropriate. Please try a different name")); return; } - if (!ClansBlacklist.isValidClanName(args[1])) + if (!Plugin.getBlacklist().allowed(args[1])) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan name is blacklisted! Please try a different name.")); + UtilPlayer.message(caller, F.main("Clans", "Clan name is blacklisted! Please try a different name.")); return; } @@ -311,7 +310,7 @@ public class ClansCommand extends CommandBase { if (clanExists) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan name is already in use by another Clan.")); + UtilPlayer.message(caller, F.main("Clans", "Clan name is already in use by another Clan.")); } else { @@ -323,11 +322,11 @@ public class ClansCommand extends CommandBase if (data == null) { // Hopefully shouldn't happen! - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "There was an error creating the clan. Please try again")); + UtilPlayer.message(caller, F.main("Clans", "There was an error creating the clan. Please try again")); } else { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You created Clan " + C.cYellow + data.getName() + C.cGray + ".")); + UtilPlayer.message(caller, F.main("Clans", "You created Clan " + C.cYellow + data.getName() + C.cGray + ".")); } } }); @@ -347,31 +346,45 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input an invitee.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input an invitee.")); return; } Player target = UtilPlayer.searchOnline(caller, args[1], true); - if (target == null) return; + if (target == null || _clansManager.getIncognitoManager().Get(target).Status) return; Plugin.getClanUtility().invite(caller, clan, target); } public void stuck(final Player caller) { +// if (_clansManager.getNetherManager().isInNether(caller)) +// { +// _clansManager.message(caller, "You are not allowed to free yourself in " + F.clansNether("The Nether") + "."); +// +// return; +// } + + if (DelayedTask.Instance.HasTask(caller, "Spawn Teleport")) + { + _clansManager.message(caller, "You are already unsticking yourself."); + + return; + } + ClanTerritory territory = Plugin.getClanUtility().getClaim(caller.getLocation()); String clanName = Plugin.getClanUtility().getClanByPlayer(caller) == null ? null : Plugin.getClanUtility().getClanByPlayer(caller).getName(); if (territory == null || territory.Safe || territory.Owner.equals(clanName)) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must be in another Clan's territory to use this.")); + UtilPlayer.message(caller, F.main("Clans", "You must be in another Clan's territory to use this.")); return; } @@ -384,19 +397,19 @@ public class ClansCommand extends CommandBase if (loc == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Error whilst finding location to teleport to.")); + UtilPlayer.message(caller, F.main("Clans", "Error whilst finding location to teleport to.")); return; } player.getPlayer().teleport(loc); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You have been teleported to the Wilderness.")); + UtilPlayer.message(caller, F.main("Clans", "You have been teleported to the Wilderness.")); } }, new Callback() { public void run(DelayedTaskClient client) { - UtilTextMiddle.display("", "Teleporting to Wilderness in " + F.elem(UtilTime.MakeStr(Math.max(0, client.getTimeLeft("Wilderness Teleport")))), 0, 5, 0, client.getPlayer()); + UtilTextMiddle.display("", "Teleporting to Wilderness in " + F.time(UtilTime.MakeStr(Math.max(0, client.getTimeLeft("Wilderness Teleport")))), 0, 5, 0, client.getPlayer()); } }, new Callback() { public void run(DelayedTaskClient client) @@ -444,31 +457,31 @@ public class ClansCommand extends CommandBase { if (Plugin.getClanMemberUuidMap().containsKey(caller.getUniqueId())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are already in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are already in a Clan.")); return; } if (Plugin.leftRecently(caller.getUniqueId(), 20 * 60 * 1000) != null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.MakeStr(Plugin.leftRecently(caller.getUniqueId(), 20 * 60 * 1000).getRight()) + C.mBody + ".")); + UtilPlayer.message(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.MakeStr(Plugin.leftRecently(caller.getUniqueId(), 20 * 60 * 1000).getRight()) + C.mBody + ".")); return; } if (!Plugin.Get(caller).canJoin()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.convertString(System.currentTimeMillis() - Plugin.Get(caller).getDelay(), 1, TimeUnit.FIT) + C.mBody + ".")); + UtilPlayer.message(caller, F.main("Clans", "You cannot join a Clan for " + C.mTime + UtilTime.convertString(System.currentTimeMillis() - Plugin.Get(caller).getDelay(), 1, TimeUnit.FIT) + C.mBody + ".")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a Clan name.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a Clan name.")); return; } if (!UtilInput.valid(args[1])) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Invalid characters in Clan name.")); + UtilPlayer.message(caller, F.main("Clans", "Invalid characters in Clan name.")); return; } @@ -477,13 +490,13 @@ public class ClansCommand extends CommandBase if (!clan.isInvited(caller.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not invited to " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You are not invited to " + F.elem("Clan " + clan.getName()) + ".")); return; } if (clan.getSize() >= clan.getMaxSize()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "The clan " + F.elem("Clan " + clan.getName()) + " is full and cannot be joined!")); + UtilPlayer.message(caller, F.main("Clans", "The clan " + F.elem("Clan " + clan.getName()) + " is full and cannot be joined!")); return; } @@ -500,12 +513,12 @@ public class ClansCommand extends CommandBase if (data) { // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You joined " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You joined " + F.elem("Clan " + clan.getName()) + ".")); clan.inform(F.name(caller.getName()) + " has joined your Clan.", caller.getName()); } else { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "There was an error processing your request")); + UtilPlayer.message(caller, F.main("Clans", "There was an error processing your request")); } } }); @@ -518,13 +531,13 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (clan.getMembers().get(caller.getUniqueId()).getRole() == ClanRole.LEADER && clan.getMembers().size() > 1) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must pass on " + F.elem("Leadership") + " before leaving.")); + UtilPlayer.message(caller, F.main("Clans", "You must pass on " + F.elem("Leadership") + " before leaving.")); return; } @@ -538,7 +551,7 @@ public class ClansCommand extends CommandBase public void run(Boolean data) { // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You left " + F.elem("Clan " + clan.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You left " + F.elem("Clan " + clan.getName()) + ".")); clan.inform(F.name(caller.getName()) + " has left your Clan.", null); } }); @@ -555,19 +568,19 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a Player to kick.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a Player to kick.")); return; } final String target = UtilPlayer.searchCollection(caller, args[1], clan.getMemberNameSet(), "Clan Member", true); - _manager.getClanUtility().kick(caller, target); + _clansManager.getClanUtility().kick(caller, target); } public void promote(Player caller, String[] args) @@ -576,19 +589,19 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input player to promote.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input player to promote.")); return; } final String targetName = UtilPlayer.searchCollection(caller, args[1], clan.getMemberNameSet(), "Clan Member", true); - _manager.getClanUtility().promote(caller, targetName); + _clansManager.getClanUtility().promote(caller, targetName); } public void demote(Player caller, String[] args) @@ -597,19 +610,19 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input player to demote.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input player to demote.")); return; } final String targetName = UtilPlayer.searchCollection(caller, args[1], clan.getMemberNameSet(), "Clan Member", true); - _manager.getClanUtility().demote(caller, targetName); + _clansManager.getClanUtility().demote(caller, targetName); } public void ally(Player caller, String[] args) @@ -618,19 +631,19 @@ public class ClansCommand extends CommandBase if (cA == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (cA.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && cA.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can manage Alliances.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can manage Alliances.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a Clan to ally.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a Clan to ally.")); return; } @@ -640,31 +653,31 @@ public class ClansCommand extends CommandBase if (cA.isSelf(cB.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot ally with yourself.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot ally with yourself.")); return; } if (cA.isAlly(cB.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are already allies with Clan" + F.elem(cB.getName())) + "."); + UtilPlayer.message(caller, F.main("Clans", "You are already allies with Clan" + F.elem(cB.getName())) + "."); return; } if (cA.getAllies() >= cA.getAlliesMax()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You cannot have any more allies.")); + UtilPlayer.message(caller, F.main("Clans", "You cannot have any more allies.")); return; } if (cB.getAllies() >= cB.getAlliesMax()) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Clan " + F.elem(cB.getName()) + " cannot have any more allies.")); + UtilPlayer.message(caller, F.main("Clans", "Clan " + F.elem(cB.getName()) + " cannot have any more allies.")); return; } if (!Recharge.Instance.usable(caller, "AllyReq" + cB.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Please do not spam alliance requests.")); + UtilPlayer.message(caller, F.main("Clans", "Please do not spam alliance requests.")); return; } @@ -674,7 +687,7 @@ public class ClansCommand extends CommandBase Plugin.getClanDataAccess().ally(cA, cB, caller.getName()); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You accepted alliance with Clan " + F.elem(cB.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You accepted alliance with Clan " + F.elem(cB.getName()) + ".")); cA.inform(F.name(caller.getName()) + " accepted alliance with Clan " + F.elem(cB.getName()) + ".", caller.getName()); cB.inform("Clan " + F.elem(cA.getName()) + " has accepted alliance with you.", null); } @@ -684,7 +697,7 @@ public class ClansCommand extends CommandBase Plugin.getClanDataAccess().requestAlly(cA, cB, caller.getName()); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You requested alliance with Clan " + F.elem(cB.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You requested alliance with Clan " + F.elem(cB.getName()) + ".")); cA.inform(F.name(caller.getName()) + " has requested alliance with Clan " + F.elem(cB.getName()) + ".", caller.getName()); cB.inform("Clan " + F.elem(cA.getName()) + " has requested alliance with you.", null); @@ -747,19 +760,19 @@ public class ClansCommand extends CommandBase if (cA == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } if (cA.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && cA.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can manage relationships.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can manage relationships.")); return; } if (args.length < 2) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a Clan to set neutrality with.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a Clan to set neutrality with.")); return; } @@ -769,11 +782,11 @@ public class ClansCommand extends CommandBase if (cB.isSelf(cA.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You prefer to think of yourself positively...")); + UtilPlayer.message(caller, F.main("Clans", "You prefer to think of yourself positively...")); } else if (cB.isNeutral(cA.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are already neutral with " + F.elem("Clan " + cB.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You are already neutral with " + F.elem("Clan " + cB.getName()) + ".")); } else if (cB.isAlly(cA.getName())) { @@ -781,7 +794,7 @@ public class ClansCommand extends CommandBase Plugin.getClanDataAccess().neutral(cA, cB, caller.getName(), true); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You revoked alliance with " + F.elem("Clan " + cB.getName()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You revoked alliance with " + F.elem("Clan " + cB.getName()) + ".")); cA.inform(F.name(caller.getName()) + " revoked alliance with " + F.elem("Clan " + cB.getName()) + ".", caller.getName()); cB.inform(F.elem("Clan " + cA.getName()) + " has revoked alliance with you.", null); } @@ -797,11 +810,25 @@ public class ClansCommand extends CommandBase return; } +// if (_clansManager.getNetherManager().isInNether(caller)) +// { +// _clansManager.message(caller, "You are not allowed to claim territory in " + F.clansNether("The Nether") + "."); +// +// return; +// } + Plugin.getClanUtility().claim(caller); } public void unclaim(Player caller, String[] args) { +// if (_clansManager.getNetherManager().isInNether(caller)) +// { +// _clansManager.message(caller, "You are not allowed to unclaim territory in " + F.clansNether("The Nether") + "."); +// +// return; +// } + if (args.length > 1) { if (args[1].equalsIgnoreCase("all") || args[1].equalsIgnoreCase("a")) @@ -816,13 +843,13 @@ public class ClansCommand extends CommandBase public boolean unclaimSteal(Player caller, ClanInfo clientClan, ClanInfo ownerClan) { - if (!_manager.canUnclaimChunk(clientClan, ownerClan)) + if (!_clansManager.canUnclaimChunk(clientClan, ownerClan)) { return false; } // Change Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You can no longer 'steal' territory. " + "You simply unclaim it and it can not be reclaimed by anyone for 30 mintes." + "This was done to improve gameplay. Enjoy!")); + UtilPlayer.message(caller, F.main("Clans", "You can no longer 'steal' territory. " + "You simply unclaim it and it can not be reclaimed by anyone for 30 mintes." + "This was done to improve gameplay. Enjoy!")); // Inform UtilServer.broadcast(F.main("Clans", F.elem(clientClan.getName()) + " unclaimed from " + F.elem(ownerClan.getName()) + " at " + F.elem(UtilWorld.locToStrClean(caller.getLocation())) + ".")); @@ -858,19 +885,21 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + //teleport to spawn point + Spawn.getInstance().getSpawnLocation(); UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); + return; } if (clan.getHome() == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Your Clan has not set a Home")); + UtilPlayer.message(caller, F.main("Clans", "Your Clan has not set a Home")); return; } if (!clan.getClaimSet().contains(UtilWorld.chunkToStr(clan.getHome().getChunk()))) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Your Clan has lost its Home Territory.")); + UtilPlayer.message(caller, F.main("Clans", "Your Clan has lost its Home Territory.")); return; } @@ -878,7 +907,7 @@ public class ClansCommand extends CommandBase if (!(home.getBlock().getType().equals(Material.BED_BLOCK) && home.add(0, 1, 0).getBlock().getType().equals(Material.AIR)) && home.add(0, 2, 0).getBlock().getType().equals(Material.AIR)) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Your Clan's bed has been destroyed, or is obstructed.")); + UtilPlayer.message(caller, F.main("Clans", "Your Clan's bed has been destroyed, or is obstructed.")); return; } @@ -892,7 +921,16 @@ public class ClansCommand extends CommandBase * } */ - if (!Recharge.Instance.use(caller, "Home Teleport", 5 * 60 * 1000, true, false)) + if (!Recharge.Instance.usable(caller, "Home Teleport", true)) + { + return; + } + + // Event + ClansCommandExecutedEvent event = new ClansCommandExecutedEvent(caller, "tphome"); + UtilServer.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { return; } @@ -900,23 +938,25 @@ public class ClansCommand extends CommandBase DelayedTask.Instance.doDelay(caller, "Home Teleport", new Callback() { public void run(DelayedTaskClient player) { + Recharge.Instance.use(caller, "Home Teleport", 30 * 60 * 1000, true, false); + // Do Plugin.getTeleport().TP(caller, clan.getHome().add(0, 1, 0)); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You teleported to your Clan Home " + UtilWorld.locToStrClean(caller.getLocation()) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You teleported to your Clan Home " + UtilWorld.locToStrClean(caller.getLocation()) + ".")); } }, new Callback() { public void run(DelayedTaskClient client) { - UtilTextMiddle.display("", "Teleporting to Clan Home in " + F.elem(UtilTime.MakeStr(Math.max(0, client.getTimeLeft("Home Teleport")))), 0, 5, 0, client.getPlayer()); + UtilTextMiddle.display("", "Teleporting to Clan Home in " + F.time(UtilTime.MakeStr(Math.max(0, client.getTimeLeft("Home Teleport")))), 0, 5, 0, client.getPlayer()); } }, new Callback() { public void run(DelayedTaskClient client) { UtilPlayer.message(client.getPlayer(), F.main("Clans", "Teleport has been cancelled due to movement.")); } - }, (Plugin.getClanUtility().getClaim(caller.getLocation()) != null ? 30 : 20) * 1000, false); + }, 15 * 1000, false); } public void homeSet(Player caller) @@ -934,31 +974,38 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } +// if (_clansManager.getNetherManager().isInNether(caller)) +// { +// _clansManager.message(caller, "You are not allowed to set your Clan Home in " + F.clansNether("The Nether") + "."); +// +// return; +// } + if (clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.LEADER && clan.getMembers().get(caller.getUniqueId()).getRole() != ClanRole.ADMIN) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "Only the Clan Leader and Admins can manage Clan Home.")); + UtilPlayer.message(caller, F.main("Clans", "Only the Clan Leader and Admins can manage Clan Home.")); return; } if (Plugin.getClanUtility().getOwner(caller.getLocation()) == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must set your Clan Home in your own Territory.")); + UtilPlayer.message(caller, F.main("Clans", "You must set your Clan Home in your own Territory.")); return; } if (!Plugin.getClanUtility().getOwner(caller.getLocation()).isSelf(clan.getName())) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You must set your Clan Home in your own Territory.")); + UtilPlayer.message(caller, F.main("Clans", "You must set your Clan Home in your own Territory.")); return; } if (!(caller.getLocation().add(0, 1, 0).getBlock().getType().equals(Material.AIR) && caller.getLocation().add(0, 2, 0).getBlock().getType().equals(Material.AIR))) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This is not a suitable place for a bed.")); + UtilPlayer.message(caller, F.main("Clans", "This is not a suitable place for a bed.")); return; } @@ -967,7 +1014,7 @@ public class ClansCommand extends CommandBase if (!bedPlaced) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "This is not a suitable place for a bed.")); + UtilPlayer.message(caller, F.main("Clans", "This is not a suitable place for a bed.")); return; } @@ -983,7 +1030,7 @@ public class ClansCommand extends CommandBase Plugin.ClanTips.displayTip(TipType.SETHOME, caller); // Inform - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You set Clan Home to " + F.elem(UtilWorld.locToStrClean(caller.getLocation())) + ".")); + UtilPlayer.message(caller, F.main("Clans", "You set Clan Home to " + F.elem(UtilWorld.locToStrClean(caller.getLocation())) + ".")); clan.inform(caller.getName() + " set Clan Home to " + F.elem(UtilWorld.locToStrClean(caller.getLocation())) + ".", caller.getName()); } @@ -993,7 +1040,7 @@ public class ClansCommand extends CommandBase if (search == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a search parameter.")); + UtilPlayer.message(caller, F.main("Clans", "You did not input a search parameter.")); return; } @@ -1008,39 +1055,9 @@ public class ClansCommand extends CommandBase ClanInfo clan = Plugin.getClanUtility().searchClanPlayer(caller, search, true); if (clan == null) return; - _manager.getClanShop().openClanWho(caller, clan); + _clansManager.getClanShop().openClanWho(caller, clan); } - public void forceJoinClan(Player caller, String search) - { - if (_manager.getClientManager().hasRank(caller, Rank.ADMIN)) - { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "No no no, this command is not for you ;-)")); - return; - } - - if (search == null) - { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You did not input a search parameter.")); - return; - } - - ClansCommandExecutedEvent event = new ClansCommandExecutedEvent(caller, "info", search); - UtilServer.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) - { - return; - } - - ClanInfo clan = Plugin.getClanUtility().searchClanPlayer(caller, search, true); - if (clan == null) return; - - _manager.getClanUtility().join(caller, clan); - _manager.getClanDataAccess().role(clan, caller.getUniqueId(), ClanRole.LEADER); - } - - public void infoTerritory(Player caller, String[] args) { ClanInfo clan; @@ -1050,7 +1067,7 @@ public class ClansCommand extends CommandBase if (clan == null) { - _manager.getTutorials().sendTutorialMsg(caller, F.main("Clans", "You are not in a Clan.")); + UtilPlayer.message(caller, F.main("Clans", "You are not in a Clan.")); return; } } @@ -1060,6 +1077,13 @@ public class ClansCommand extends CommandBase if (clan == null) return; - _manager.getTutorials().sendTutorialMsg(caller, clan.mTerritory()); +// if (_clansManager.getNetherManager().isInNether(caller)) +// { +// _clansManager.message(caller, "You are currently in " + F.clansNether("The Nether") + "."); +// +// return; +// } + + UtilPlayer.message(caller, clan.mTerritory()); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/KillCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/KillCommand.java index 258902f29..151567dbd 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/KillCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/KillCommand.java @@ -1,5 +1,6 @@ package mineplex.game.clans.clans.commands; +import mineplex.game.clans.clans.ClansManager; import org.bukkit.entity.Player; import mineplex.core.command.CommandBase; @@ -18,6 +19,17 @@ public class KillCommand extends CommandBase @Override public void Execute(Player caller, String[] args) { + if ((System.currentTimeMillis() - Plugin.GetCombatManager().Get(caller).GetLastCombat()) <= 20000) + { + UtilPlayer.message(caller, F.main("Clans", "You cannot use this command whilst in combat.")); + return; + } + if(ClansManager.getInstance().getTutorial().inTutorial(caller)) + { + UtilPlayer.message(caller, F.main("Clans", "You cannot use this command whilst in the tutorial.")); + return; + } + UtilPlayer.message(caller, F.main("Clans", "You have imploded.")); caller.setHealth(0D); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/Meow.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/Meow.java deleted file mode 100644 index b6bc54b64..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/Meow.java +++ /dev/null @@ -1,22 +0,0 @@ -package mineplex.game.clans.clans.commands; - -import org.bukkit.entity.Player; - -import mineplex.core.command.CommandBase; -import mineplex.core.common.Rank; -import mineplex.game.clans.clans.outpost.Outpost; -import mineplex.game.clans.clans.outpost.OutpostManager; - -public class Meow extends CommandBase -{ - public Meow(OutpostManager plugin) - { - super(plugin, Rank.ALL, "meow"); - } - - @Override - public void Execute(Player caller, String[] args) - { - caller.getInventory().addItem(Outpost.OUTPOST_ITEM); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/QueryCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/QueryCommand.java new file mode 100644 index 000000000..8e95c06e0 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/QueryCommand.java @@ -0,0 +1,53 @@ +package mineplex.game.clans.clans.commands; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.database.MinecraftRepository; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.RepositoryBase; + +public class QueryCommand extends CommandBase +{ + private ClansManager _clansManager; + + public QueryCommand(ClansManager plugin) + { + super(plugin, Rank.JNR_DEV, "query"); + _clansManager = plugin; + } + + @Override + public void Execute(final Player caller, String[] args) + { + if (args.length == 0) + { + UtilPlayer.message(caller, F.main(Plugin.getName(), "Query missing.")); + return; + } + + final String query = F.combine(args, 0, null, false); + + new MinecraftRepository(Plugin.getPlugin(), DBPool.getAccount()) { + protected void initialize() + { + executeUpdate(query); + } + + protected void update() + { + } + }; + } + + public static void message(Player player, String message) + { + UtilPlayer.message(player, F.main("Clans", message)); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/RestartTutCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/RestartTutCommand.java index a37102d7b..9910889d0 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/RestartTutCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/commands/RestartTutCommand.java @@ -10,9 +10,9 @@ import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; import mineplex.core.task.TaskManager; import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.tutorials.Tutorial; -import mineplex.game.clans.tutorials.TutorialManager; -import mineplex.game.clans.tutorials.gettingstarted.TutorialGettingStarted; +import mineplex.game.clans.legacytutorial.Tutorial; +import mineplex.game.clans.legacytutorial.TutorialManager; +import mineplex.game.clans.legacytutorial.gettingstarted.TutorialGettingStarted; public class RestartTutCommand extends CommandBase { @@ -51,7 +51,7 @@ public class RestartTutCommand extends CommandBase } else { - TutorialManager.Instance.sendTutorialMsg(caller, F.main("Clans", "You must be in a Safe Zone to restart the tutorial.")); + UtilPlayer.message(caller, F.main("Clans", "You must be in a Safe Zone to restart the tutorial.")); } } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClanCreationCompleteEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClanCreationCompleteEvent.java new file mode 100644 index 000000000..789e55d21 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClanCreationCompleteEvent.java @@ -0,0 +1,194 @@ +package mineplex.game.clans.clans.event; + +import java.sql.Timestamp; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import mineplex.game.clans.core.repository.tokens.ClanToken; + +public class ClanCreationCompleteEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _founder; + private int _id; + private String _name; + private String _description; + private String _home; + private boolean _admin; + private int _energy; + private int _kills; + private int _murders; + private int _deaths; + private int _warWins; + private int _warLosses; + private Timestamp _dateCreated; + private Timestamp _lastOnline; + + public ClanCreationCompleteEvent(ClanToken token, Player founder) + { + _founder = founder; + + _id = token.Id; + _name = token.Name; + _description = token.Description; + _home = token.Home; + _admin = token.Admin; + _energy = token.Energy; + _kills = token.Kills; + _murders = token.Murder; + _deaths = token.Deaths; + _warWins = token.WarWins; + _warLosses = token.WarLosses; + _dateCreated = token.DateCreated; + _lastOnline = token.LastOnline; + } + + public Player getFounder() + { + return _founder; + } + + public int getId() + { + return _id; + } + + public void setId(int id) + { + _id = id; + } + + public String getName() + { + return _name; + } + + public void setName(String name) + { + _name = name; + } + + public String getDescription() + { + return _description; + } + + public void setDescription(String description) + { + _description = description; + } + + public String getHome() + { + return _home; + } + + public void setHome(String home) + { + _home = home; + } + + public boolean isAdmin() + { + return _admin; + } + + public void setAdmin(boolean admin) + { + _admin = admin; + } + + public int getEnergy() + { + return _energy; + } + + public void setEnergy(int energy) + { + _energy = energy; + } + + public int getKills() + { + return _kills; + } + + public void setKills(int kills) + { + _kills = kills; + } + + public int getMurders() + { + return _murders; + } + + public void setMurders(int murders) + { + _murders = murders; + } + + public int getDeaths() + { + return _deaths; + } + + public void setDeaths(int deaths) + { + _deaths = deaths; + } + + public int getWarWins() + { + return _warWins; + } + + public void setWarWins(int warWins) + { + _warWins = warWins; + } + + public int getWarLosses() + { + return _warLosses; + } + + public void setWarLosses(int warLosses) + { + _warLosses = warLosses; + } + + public Timestamp getDateCreated() + { + return _dateCreated; + } + + public void setDateCreated(Timestamp dateCreated) + { + _dateCreated = dateCreated; + } + + public Timestamp getLastOnline() + { + return _lastOnline; + } + + public void setLastOnline(Timestamp lastOnline) + { + _lastOnline = lastOnline; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansCommandPreExecutedEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansCommandPreExecutedEvent.java new file mode 100644 index 000000000..5c8695c35 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansCommandPreExecutedEvent.java @@ -0,0 +1,68 @@ +package mineplex.game.clans.clans.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ClansCommandPreExecutedEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private String[] _args; + + private boolean _cancelled; + + public ClansCommandPreExecutedEvent(Player player, String... args) + { + _player = player; + _args = args; + } + + public ClansCommandPreExecutedEvent(Player player, Object... args) + { + _player = player; + + String[] strArgs = new String[args != null ? args.length : 0]; + + int index = 0; + for (Object obj : args) + { + strArgs[index] = obj.toString(); + + index++; + } + + _args = strArgs; + } + + public Player getPlayer() + { + return _player; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public String[] getArguments() + { + return _args; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansWaterPlaceEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansWaterPlaceEvent.java new file mode 100644 index 000000000..c6826eeef --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/ClansWaterPlaceEvent.java @@ -0,0 +1,53 @@ +package mineplex.game.clans.clans.event; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ClansWaterPlaceEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private Block _block; + + private boolean _cancelled; + + public ClansWaterPlaceEvent(Player player, Block block) + { + _player = player; + _block = block; + } + + public Player getPlayer() + { + return _player; + } + + public Block getBlock() + { + return _block; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/IronDoorOpenEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/IronDoorOpenEvent.java new file mode 100644 index 000000000..5c22c5229 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/IronDoorOpenEvent.java @@ -0,0 +1,58 @@ +package mineplex.game.clans.clans.event; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called before an iron door is opened by right clicking. + * + * (Custom mechanic in Clans) + */ +public class IronDoorOpenEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private Block _block; + + private boolean _cancelled; + + public IronDoorOpenEvent(Player player, Block block) + { + _player = player; + _block = block; + } + + public Player getPlayer() + { + return _player; + } + + public Block getBlock() + { + return _block; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PlayerEnterTerritoryEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PlayerEnterTerritoryEvent.java index 80e9a4a4d..ef243563e 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PlayerEnterTerritoryEvent.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PlayerEnterTerritoryEvent.java @@ -22,6 +22,7 @@ public class PlayerEnterTerritoryEvent extends Event _lastTerritory = lastTerritory; _newTerritory = newTerritory; _safe = safe; + _sendMessage = sendMessage; } public Player getPlayer() diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PreEnergyShopBuyEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PreEnergyShopBuyEvent.java new file mode 100644 index 000000000..6c0af3913 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/event/PreEnergyShopBuyEvent.java @@ -0,0 +1,58 @@ +package mineplex.game.clans.clans.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PreEnergyShopBuyEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private boolean _cancelled; + + private Player _player; + private int _energy; + private int _cost; + + public PreEnergyShopBuyEvent(Player player, int energy, int cost) + { + _player = player; + _energy = energy; + _cost = cost; + } + + public Player getPlayer() + { + return _player; + } + + public int getCost() + { + return _cost; + } + + public int getEnergy() + { + return _energy; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddAllyButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddAllyButton.java index 58b7d88c3..0ffc86737 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddAllyButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddAllyButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -13,8 +15,10 @@ public class ClanAddAllyButton implements IButton @Override public void onClick(Player player, ClickType clickType) { - player.closeInventory(); + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.AddAlly)).isCancelled()) + return; + player.closeInventory(); JsonMessage message = new JsonMessage(C.cRed + C.Bold + "Click here to add an Ally").click(ClickEvent.SUGGEST_COMMAND, "/c ally "); message.sendToPlayer(player); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddTrustedButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddTrustedButton.java index 505eb674b..6a8d8a552 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddTrustedButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddTrustedButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -13,6 +15,9 @@ public class ClanAddTrustedButton implements IButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.AddTrusted)).isCancelled()) + return; + player.closeInventory(); JsonMessage message = new JsonMessage(C.cRed + C.Bold + "Click here to trust a clan").click(ClickEvent.SUGGEST_COMMAND, "/c trust "); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddWarButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddWarButton.java index 22e4ce7ef..d0faaa721 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddWarButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanAddWarButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -13,6 +15,8 @@ public class ClanAddWarButton implements IButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.AddWar)).isCancelled()) + return; player.closeInventory(); JsonMessage message = new JsonMessage(C.cRed + C.Bold + "Click here to war a clan").click(ClickEvent.SUGGEST_COMMAND, "/war "); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanButton.java index 1abdda431..055a4eed2 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanButton.java @@ -12,7 +12,7 @@ import mineplex.game.clans.clans.gui.ClanShop; public abstract class ClanButton implements IButton { private ClanShop _shop; - private ClansManager _clansManager; + protected ClansManager _clansManager; private Player _player; private ClanInfo _clanInfo; private ClanRole _clanRole; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanCreateButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanCreateButton.java index 5776f58b0..39815a0f8 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanCreateButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanCreateButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -18,9 +20,6 @@ public class ClanCreateButton implements IButton @Override public void onClick(Player player, ClickType clickType) { - player.closeInventory(); - - JsonMessage message = new JsonMessage(C.cRed + C.Bold + "Click here to create a clan").click(ClickEvent.SUGGEST_COMMAND, "/c create "); - message.sendToPlayer(player); + UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Create)); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanDisbandButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanDisbandButton.java index 5450e21a8..6165d054b 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanDisbandButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanDisbandButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -18,6 +20,8 @@ public class ClanDisbandButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Disband)).isCancelled()) + return; getPlayer().closeInventory(); getClansManager().getClanUtility().delete(getPlayer()); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanEnergyButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanEnergyButton.java index ae2d56236..20038637d 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanEnergyButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanEnergyButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -18,6 +20,6 @@ public class ClanEnergyButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { - + UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Energy)); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanInviteButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanInviteButton.java index afd3eff2b..f32e20b19 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanInviteButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanInviteButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -23,6 +25,8 @@ public class ClanInviteButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Invite)).isCancelled()) + return; getShop().openPageForPlayer(getPlayer(), new ClanInvitePage(getClansManager(), getShop(), getClansManager().getClientManager(), _donationManager, player)); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanJoinButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanJoinButton.java index f3e451d0a..fb8c78623 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanJoinButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanJoinButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -21,6 +23,8 @@ public class ClanJoinButton implements IButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Join)).isCancelled()) + return; player.closeInventory(); _clansManager.getClanUtility().join(player, _clanInfo); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanLeaveButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanLeaveButton.java index 114f3eb79..fbf261c8e 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanLeaveButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanLeaveButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -18,7 +20,22 @@ public class ClanLeaveButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { - getPlayer().closeInventory(); - getClansManager().getClanUtility().leave(getPlayer()); + if(clickType.equals(ClickType.SHIFT_RIGHT)) //disband + { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Disband)).isCancelled()) + return; + + getPlayer().closeInventory(); + getClansManager().getClanUtility().delete(getPlayer()); + + }else if(clickType.equals(ClickType.SHIFT_LEFT)) //leave + { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Leave)).isCancelled()) + return; + + getPlayer().closeInventory(); + getClansManager().getClanUtility().leave(getPlayer()); + } + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanMemeberButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanMemeberButton.java index da1194fe2..0570693d2 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanMemeberButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanMemeberButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -24,6 +26,8 @@ public class ClanMemeberButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Member)).isCancelled()) + return; if (clickType == ClickType.LEFT) { // Promote diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanTerritoryButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanTerritoryButton.java index b718a5132..363c78f01 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanTerritoryButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanTerritoryButton.java @@ -1,11 +1,14 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import mineplex.core.common.util.C; +import mineplex.core.common.util.F; import mineplex.core.common.util.UtilWorld; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClanRole; @@ -22,6 +25,15 @@ public class ClanTerritoryButton extends ClanButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Territory)).isCancelled()) + return; +// if (_clansManager.getNetherManager().isInNether(player)) +// { +// _clansManager.message(player, "You are not allowed to do anything with Territory while in " + F.clansNether("The Nether") + "."); +// player.closeInventory(); +// return; +// } + if (clickType == ClickType.LEFT) { player.closeInventory(); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanWhoButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanWhoButton.java index 20385402b..ce482aeed 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanWhoButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/button/ClanWhoButton.java @@ -1,5 +1,7 @@ package mineplex.game.clans.clans.gui.button; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -13,6 +15,8 @@ public class ClanWhoButton implements IButton @Override public void onClick(Player player, ClickType clickType) { + if (UtilServer.CallEvent(new ClansButtonClickEvent(player, ClansButtonClickEvent.ButtonType.Who)).isCancelled()) + return; player.closeInventory(); JsonMessage message = new JsonMessage(C.cRed + C.Bold + "Click here to lookup a clan").click(ClickEvent.SUGGEST_COMMAND, "/c who "); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/events/ClansButtonClickEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/events/ClansButtonClickEvent.java new file mode 100644 index 000000000..844a1159b --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/events/ClansButtonClickEvent.java @@ -0,0 +1,67 @@ +package mineplex.game.clans.clans.gui.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class ClansButtonClickEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private ButtonType _type; + + private boolean _cancelled; + + public ClansButtonClickEvent(Player player, ButtonType type) + { + _player = player; + _type = type; + } + + public Player getPlayer() + { + return _player; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public ButtonType getButtonType() { + return _type; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + + public enum ButtonType + { + AddAlly, + AddTrusted, + AddWar, + Create, + Disband, + Energy, + Invite, + Join, + Leave, + Member, + Territory, + Who; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanMainPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanMainPage.java index e9738de3f..a1cde46af 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanMainPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanMainPage.java @@ -44,7 +44,7 @@ public class ClanMainPage extends ClanPageBase public ClanMainPage(ClansManager plugin, ClanShop shop, CoreClientManager clientManager, DonationManager donationManager, Player player) { super(plugin, shop, clientManager, donationManager, "Manage Clan", player, 54); - + buildPage(); } @@ -52,7 +52,7 @@ public class ClanMainPage extends ClanPageBase public void buildNoClan() { // Clan Create - ShopItem clanCreate = new ShopItem(Material.BOOK_AND_QUILL, "Create Clan", new String[] {}, 1, false, false); + ShopItem clanCreate = new ShopItem(Material.BOOK_AND_QUILL, "Create Clan", new String[] {C.cGray + "To create a clan type", C.cRed + "/c create "}, 1, false, false); addButton(21, clanCreate, new ClanCreateButton()); // Clan Join diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanWhoPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanWhoPage.java index dd417956c..6fe27d3ad 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanWhoPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/gui/page/ClanWhoPage.java @@ -99,7 +99,7 @@ public class ClanWhoPage extends ClanPageBase if (_lookupClan.equals(clanInfo)) { String clanHome = _lookupClan.getHome() == null ? "None" : UtilWorld.locToStrClean(_lookupClan.getHome()); - String generator = _lookupClan.getGenerator() == null ? "None" : UtilWorld.blockToStrClean(_lookupClan.getGenerator().getBlock()); + String generator = _lookupClan.getGenerator() == null ? "None" : "Yes"; lore.add(C.Reset + C.cYellow + "Clan Home " + C.cWhite + clanHome); lore.add(C.Reset + C.cYellow + "TNT Generator " + C.cWhite + generator); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/Invsee.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/Invsee.java new file mode 100644 index 000000000..3409089ea --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/Invsee.java @@ -0,0 +1,23 @@ +package mineplex.game.clans.clans.invsee; + +import mineplex.core.MiniPlugin; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.invsee.commands.InvseeCommand; + +public class Invsee extends MiniPlugin +{ + private ClansManager _clansManager; + + public Invsee(ClansManager clansManager) + { + super("Inventory Viewer", clansManager.getPlugin()); + + _clansManager = clansManager; + } + + public void addCommands() + { + addCommand(new InvseeCommand(this)); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/commands/InvseeCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/commands/InvseeCommand.java new file mode 100644 index 000000000..a4fd436bd --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/commands/InvseeCommand.java @@ -0,0 +1,54 @@ +package mineplex.game.clans.clans.invsee.commands; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.game.clans.clans.invsee.Invsee; +import mineplex.game.clans.clans.invsee.ui.InvseeInventory; + +public class InvseeCommand extends CommandBase +{ + public InvseeCommand(Invsee plugin) + { + super(plugin, Rank.ADMIN, "invsee"); + } + + @Override + public void Execute(Player caller, String[] args) + { + if (args.length == 0) + { + + } + else + { + String name = args[0]; + + OfflinePlayer player; + + if (UtilServer.IsOnline(name)) + { + player = UtilServer.GetPlayer(name); + } + else + { + player = UtilServer.GetOffline(name); + } + + if (player == null) + { + UtilPlayer.message(caller, F.main("Clans", "Specified player is neither online nor is offline. Perhaps they changed their name?")); + return; + } + + new InvseeInventory(player).ShowTo(caller); + } + } + + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/ui/InvseeInventory.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/ui/InvseeInventory.java new file mode 100644 index 000000000..eb605e17b --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/invsee/ui/InvseeInventory.java @@ -0,0 +1,99 @@ +package mineplex.game.clans.clans.invsee.ui; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + +public class InvseeInventory implements Listener +{ + private OfflinePlayer _player; + private Inventory _inventory; + + private boolean _online; + + private Player _admin; + + public InvseeInventory(OfflinePlayer player) + { + _online = (_player = player) instanceof Player; + + _inventory = UtilServer.getServer().createInventory(null, 54, player.getName() + " " + (_online ? C.cGreen + "ONLINE" : C.cRed + "OFFLINE")); + + UtilServer.RegisterEvents(this); + } + + public void ShowTo(Player admin) + { + _admin = admin; + admin.openInventory(_inventory); + } + + @EventHandler + public void quit(PlayerQuitEvent event) + { + if (_online && event.getPlayer().equals(_player)) + { + _admin.closeInventory(); + } + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + if (_online) + { + if (!UtilCollections.equal(_inventory.getContents(), ((Player) _player).getInventory().getContents())) + { + _inventory.setContents(((Player) _player).getInventory().getContents()); + } + } + } + + @EventHandler + public void inventoryClick(InventoryClickEvent event) + { + if (event.getClickedInventory().equals(((Player) _player).getInventory())) + { + _inventory.setContents(((Player) _player).getInventory().getContents()); + } + else if (event.getClickedInventory().equals(_inventory)) + { + if (_online) + { + ((Player) _player).getInventory().setContents(_inventory.getContents()); + } + } + } + + @EventHandler + public void closeInventory(InventoryCloseEvent event) + { + if (event.getInventory().equals(_inventory)) + { + UtilServer.Unregister(this); + + if (!_online) + { + // save offline inv + } + } + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/loot/LootManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/loot/LootManager.java index 0ce0bc9e1..a322d8041 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/loot/LootManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/loot/LootManager.java @@ -87,7 +87,7 @@ public class LootManager private void populateRare() { // Gear - _rareSet.add(100, new GearLoot(_gearManager)); + _rareSet.add(90, new GearLoot(_gearManager)); _rareSet.add(10, new GoldTokenLoot(50000, 100000)); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapManager.java index 1a6268a76..76c2cc1ba 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapManager.java @@ -10,10 +10,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; -import java.util.List; -import java.util.Map; import java.util.Map.Entry; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.map.TutorialMapManager; import org.apache.commons.io.FileUtils; import org.bukkit.Bukkit; import org.bukkit.Chunk; @@ -34,6 +34,7 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.map.MapRenderer; @@ -55,11 +56,11 @@ import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilTime.TimeUnit; import mineplex.core.itemstack.ItemBuilder; import mineplex.core.portal.ServerTransferEvent; -import mineplex.core.timing.TimingManager; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.ClansUtility; +import mineplex.game.clans.clans.map.events.PlayerGetMapEvent; import mineplex.game.clans.clans.worldevent.WorldEventManager; import net.minecraft.server.v1_8_R3.Block; import net.minecraft.server.v1_8_R3.BlockPosition; @@ -83,13 +84,15 @@ public class ItemMapManager extends MiniPlugin private ArrayList> _scanList = new ArrayList>(); private World _world; private WorldEventManager _eventManager; + private TutorialManager _tutorial; - public ItemMapManager(ClansManager clansManager, WorldEventManager eventManager) + public ItemMapManager(ClansManager clansManager, TutorialManager tutorial, WorldEventManager eventManager) { super("ItemMapManager", clansManager.getPlugin()); _clansUtility = clansManager.getClanUtility(); _eventManager = eventManager; + _tutorial = tutorial; _comparator = new Comparator>() { @@ -244,7 +247,7 @@ public class ItemMapManager extends MiniPlugin view.removeRenderer(renderer); } - view.addRenderer(new ItemMapRenderer(this, _eventManager)); + view.addRenderer(new ItemMapRenderer(this, _eventManager, _tutorial)); } @EventHandler @@ -438,6 +441,19 @@ public class ItemMapManager extends MiniPlugin event.getEntity().remove(); } } + + public void removeMap(Player player) + { + for (int slot = 0; slot < player.getInventory().getSize(); slot++) + { + ItemStack item = player.getInventory().getItem(slot); + + if (item != null && item.getType() == Material.MAP && item.getDurability() >= _mapId && item.getDurability() <= _mapId + 100) + { + player.getInventory().setItem(slot, null); + } + } + } public ClansUtility getClansUtility() { @@ -603,9 +619,25 @@ public class ItemMapManager extends MiniPlugin info.setInfo(1, calcMapCenter(zoom, loc.getBlockX()), calcMapCenter(zoom, loc.getBlockZ())); _mapInfo.put(player.getName(), info); - if (UtilInv.getItems(player).isEmpty()) +// if (UtilInv.getItems(player).isEmpty()) +// { +// setMap(player); +// } + } + + @EventHandler + public void onWorldChange(PlayerTeleportEvent event) + { + if (event.getFrom().getWorld() != event.getTo().getWorld() && event.getTo().getWorld().equals("world")) { - setMap(player); + runSyncLater(new Runnable() + { + @Override + public void run() + { + setMap(event.getPlayer()); + } + }, 20); } } @@ -732,6 +764,9 @@ public class ItemMapManager extends MiniPlugin { Collections.sort(_scanList, _comparator); } + + if (_scanList.isEmpty()) + return; Entry entry = _scanList.remove(0); @@ -853,6 +888,10 @@ public class ItemMapManager extends MiniPlugin public void setMap(Player player) { + PlayerGetMapEvent event = UtilServer.CallEvent(new PlayerGetMapEvent(player)); + if (event.isCancelled()) + return; + for (ItemStack item : UtilInv.getItems(player)) { if (item.getType() == Material.MAP && (item.getDurability() >= _mapId && item.getDurability() <= _mapId + 100)) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapRenderer.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapRenderer.java index bf85c900d..746f48e7e 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapRenderer.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/ItemMapRenderer.java @@ -1,11 +1,18 @@ package mineplex.game.clans.clans.map; import java.awt.Color; +import java.util.List; import mineplex.core.common.util.UtilTime; +import mineplex.core.recharge.Recharge; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansUtility; import mineplex.game.clans.clans.worldevent.WorldEventManager; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialType; +import mineplex.game.clans.tutorial.map.TutorialMapManager; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; import mineplex.minecraft.game.core.boss.EventState; import mineplex.minecraft.game.core.boss.WorldEvent; @@ -22,18 +29,38 @@ import org.bukkit.map.MapView; public class ItemMapRenderer extends MapRenderer { private ItemMapManager _manager; + private TutorialManager _tutorial; private WorldEventManager _eventManager; - public ItemMapRenderer(ItemMapManager itemMapManager, WorldEventManager eventManager) + public ItemMapRenderer(ItemMapManager itemMapManager, WorldEventManager eventManager, TutorialManager tutorial) { super(true); _manager = itemMapManager; + _tutorial = tutorial; _eventManager = eventManager; } @Override public void render(MapView mapView, MapCanvas canvas, Player player) + { +// if (_tutorial.inTutorial(player)) +// { +// renderTutorialMap(mapView, canvas, player); +// } +// else +// { + renderNormalMap(mapView, canvas, player); +// } + } + + private void renderTutorialMap(MapView mapView, MapCanvas canvas, Player player) + { + + } + + + private void renderNormalMap(MapView mapView, MapCanvas canvas, Player player) { MapInfo info = _manager.getMap(player); @@ -87,7 +114,7 @@ public class ItemMapRenderer extends MapRenderer boolean colorAll = scale > 0; Color clanColor = null; Color clanColor2 = null; - + if (owningClan == clan) { clanColor = Color.CYAN; @@ -95,16 +122,16 @@ public class ItemMapRenderer extends MapRenderer else { ClansUtility.ClanRelation relation = _manager.getClansUtility().rel(clan, owningClan); - + if (owningClan.isAdmin()) { colorAll = false; - + if (owningClan.getName().equals("Shops")) { clanColor = Color.WHITE; clanColor2 = new Color(50, 150, 255); - + if (_manager.getClansUtility().relPT(player, chunk) == ClansUtility.ClanRelation.SAFE) clanColor2 = new Color(50, 150, 255); } @@ -157,25 +184,25 @@ public class ItemMapRenderer extends MapRenderer //Border if (colorAll || - ((chunkBX == 0 || zoom == 13) && - - owningClan != _manager.getClansUtility().getOwner("world," + (chunkX1 - 1) + "," + chunkZ1)) - - || ((chunkBZ == 0 || zoom == 13) && - - owningClan != _manager.getClansUtility().getOwner("world," + chunkX1 + "," + (chunkZ1 - 1))) - - || ((chunkBX + zoom > 15 || zoom == 13) && - - owningClan != _manager.getClansUtility().getOwner("world," + (chunkX1 + 1) + "," + chunkZ1)) - - || ((chunkBZ + zoom > 15 || zoom == 13) && - - owningClan != _manager.getClansUtility().getOwner("world," + chunkX1 + "," + (chunkZ1 + 1)))) + ((chunkBX == 0 || zoom == 13) && + + owningClan != _manager.getClansUtility().getOwner("world," + (chunkX1 - 1) + "," + chunkZ1)) + + || ((chunkBZ == 0 || zoom == 13) && + + owningClan != _manager.getClansUtility().getOwner("world," + chunkX1 + "," + (chunkZ1 - 1))) + + || ((chunkBX + zoom > 15 || zoom == 13) && + + owningClan != _manager.getClansUtility().getOwner("world," + (chunkX1 + 1) + "," + chunkZ1)) + + || ((chunkBZ + zoom > 15 || zoom == 13) && + + owningClan != _manager.getClansUtility().getOwner("world," + chunkX1 + "," + (chunkZ1 + 1)))) { Color cColor = MapPalette.getColor(color); double clans = colorAll ? 1 : 0.8;// 0.65; - + //Use clanColor2 no matter what for admins Color drawColor = clanColor; if (owningClan.isAdmin() && clanColor2 != null) @@ -183,16 +210,15 @@ public class ItemMapRenderer extends MapRenderer drawColor = clanColor2; clans = 1; } - + double base = 1 - clans; - + int r = (int) ((cColor.getRed() * base) + (drawColor.getRed() * clans)); int b = (int) ((cColor.getBlue() * base) + (drawColor.getBlue() * clans)); int g = (int) ((cColor.getGreen() * base) + (drawColor.getGreen() * clans)); color = MapPalette.matchColor(r, g, b); } - //Inside @@ -201,7 +227,7 @@ public class ItemMapRenderer extends MapRenderer Color cColor = MapPalette.getColor(color); double clans = 0.065; - + //Stripes boolean checker = (mapX + (mapZ % 4)) % 4 == 0; Color drawColor = clanColor; @@ -210,7 +236,7 @@ public class ItemMapRenderer extends MapRenderer drawColor = clanColor2; clans = 1; } - + double base = 1 - clans; int r = (int) ((cColor.getRed() * base) + (drawColor.getRed() * clans)); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/events/PlayerGetMapEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/events/PlayerGetMapEvent.java new file mode 100644 index 000000000..5e5bccc4a --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/map/events/PlayerGetMapEvent.java @@ -0,0 +1,44 @@ +package mineplex.game.clans.clans.map.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PlayerGetMapEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + + private boolean _cancelled; + + public PlayerGetMapEvent(Player player) + { + _player = player; + } + + public Player getPlayer() + { + return _player; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/ClansBlacklist.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/ClansBlacklist.java new file mode 100644 index 000000000..3cdc005f9 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/ClansBlacklist.java @@ -0,0 +1,62 @@ +package mineplex.game.clans.clans.nameblacklist; + +import java.util.List; + +import org.bukkit.event.EventHandler; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniPlugin; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.nameblacklist.commands.AddBlacklistCommand; +import mineplex.game.clans.clans.nameblacklist.repository.ClanNameBlacklistRepository; + +public class ClansBlacklist extends MiniPlugin +{ + private List _blacklist; + private ClanNameBlacklistRepository _repository; + + public ClansBlacklist(JavaPlugin plugin) + { + super("Clan Name Blacklist", plugin); + + _repository = new ClanNameBlacklistRepository(plugin, this); + + runAsync(() -> _repository.loadNames(this::setBlacklist)); + } + + // Fetch new blacklisted clans every 16 seconds (in case someone blacklists a clan name on a different server) + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() == UpdateType.SLOWER) + { + runAsync(() -> _repository.loadNames(this::setBlacklist)); + } + } + + private void setBlacklist(List blacklist) + { + _blacklist = blacklist; + } + + public boolean allowed(String name) + { + return !_blacklist.contains(name.toLowerCase()); + } + + public void add(String name) + { + _blacklist.add(name); + } + + public void addCommands() + { + addCommand(new AddBlacklistCommand(this)); + } + + public ClanNameBlacklistRepository getRepository() + { + return _repository; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/commands/AddBlacklistCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/commands/AddBlacklistCommand.java new file mode 100644 index 000000000..e05417ff5 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/commands/AddBlacklistCommand.java @@ -0,0 +1,40 @@ +package mineplex.game.clans.clans.nameblacklist.commands; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.nameblacklist.ClansBlacklist; + +public class AddBlacklistCommand extends CommandBase +{ + public AddBlacklistCommand(ClansBlacklist plugin) + { + super(plugin, Rank.CMOD, "blacklistname"); + } + + @Override + public void Execute(final Player caller, String[] args) + { + if (args == null || args.length < 1) + { + UtilPlayer.message(caller, C.cGold + "/blacklistname - Blacklists a clan name."); + } + else if (args.length >= 1) + { + final String blacklist = args[0]; + + Plugin.runAsync(() -> { + Plugin.getRepository().add(blacklist, caller.getName()); + UtilPlayer.message(caller, F.main("Clans", "Successfully added " + F.elem(blacklist) + " to the clan name blacklist.")); + }); + } + else + { + UtilPlayer.message(caller, C.cGold + "/blacklistname - Blacklists a clan name."); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/repository/ClanNameBlacklistRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/repository/ClanNameBlacklistRepository.java new file mode 100644 index 000000000..2b011adc7 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nameblacklist/repository/ClanNameBlacklistRepository.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.clans.nameblacklist.repository; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.Callback; +import mineplex.core.database.MinecraftRepository; +import mineplex.game.clans.clans.nameblacklist.ClansBlacklist; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnTimestamp; +import mineplex.serverdata.database.column.ColumnVarChar; + +public class ClanNameBlacklistRepository extends MinecraftRepository +{ + private static final String CREATE = "CREATE TABLE IF NOT EXISTS clanNameBlacklist (" + + "clanName VARCHAR(20) NOT NULL, " + + "admin VARCHAR(16) NOT NULL, " + + "added TIMESTAMP," + + "PRIMARY KEY (clanName));"; + + private static final String GET = "SELECT * FROM clanNameBlacklist;"; + private static final String ADD = "INSERT INTO clanNameBlacklist (clanName, admin, added) VALUES (?, ?, ?);"; + private static final String REMOVE = "DELETE FROM clanNameBlacklist WHERE clanName=?;"; + + private ClansBlacklist _blacklist; + + public ClanNameBlacklistRepository(JavaPlugin plugin, ClansBlacklist blacklist) + { + super(plugin, DBPool.getAccount()); + + _blacklist = blacklist; + } + + public void add(String name, String mod) + { + _blacklist.add(name.toLowerCase()); + executeInsert(ADD, null, + new ColumnVarChar("clanName", 20, name.toLowerCase()), + new ColumnVarChar("admin", 16, mod), + new ColumnTimestamp("added", new Timestamp(System.currentTimeMillis())) + ); + } + + public void loadNames(final Callback> callback) + { + executeQuery(GET, resultSet -> { + final List list = new ArrayList<>(); + + while (resultSet.next()) + { + String clanName = resultSet.getString("clanName"); + String mod = resultSet.getString("admin"); + + list.add(clanName); + } + + callback.run(list); + }); + } + + @Override + protected void initialize() + { + } + + @Override + protected void update() + { + executeUpdate(CREATE); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/NetherManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/NetherManager.java new file mode 100644 index 000000000..b17121c43 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/NetherManager.java @@ -0,0 +1,277 @@ +package mineplex.game.clans.clans.nether; + +import java.io.File; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.WorldBorder; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.inventory.ItemStack; + +import com.google.common.collect.Lists; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilFile; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilWorld; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanTips.TipType; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.core.repository.ClanTerritory; + +public class NetherManager extends MiniPlugin +{ + private ClansManager _clansManager; + + private World _netherWorld; + + private List _portals = Lists.newArrayList(); + + private File _portalCfg; + + public NetherManager(ClansManager clansManager) + { + super("Nether Manager", clansManager.getPlugin()); + _clansManager = clansManager; + + _portalCfg = new File(UtilServer.getServer().getWorlds().get(0).getWorldFolder().getPath() + File.separator + ".." + File.separator + "nether.cfg"); + + begin(); + } + + public void begin() + { + _netherWorld = Bukkit.getWorld("world_nether"); + + WorldBorder worldBorder = _netherWorld.getWorldBorder(); + worldBorder.setCenter(0, 0); + worldBorder.setSize(200 * 2); + + parsePortals(); + } + + private void parsePortals() + { + String data = UtilFile.read(_portalCfg); + + if (data.length() < 5) + { + return; + } + + UtilCollections.forEach(data.split("\n"), string -> string.trim(), sPortal -> { + + String[] destinations = sPortal.split(">>"); + + Location from = UtilWorld.strToLoc(destinations[0]); + Location to = UtilWorld.strToLoc(destinations[1].split(":")[0]); + + Portal portal = Portal.create(from, to, UtilWorld.strToLoc(to.getWorld().getName() + "," + destinations[1].split(":")[1])); + + if (portal == null) + { + log("FAILED TO LOAD PORTAL [" + sPortal + "]"); + } + else + { + _portals.add(portal); + } + }); + } + + + @EventHandler + public void cmd(PlayerCommandPreprocessEvent event) + { + if (!_clansManager.getClientManager().hasRank(event.getPlayer(), Rank.JNR_DEV)) + { + return; + } + + if (event.getMessage().startsWith("/nether")) + { + event.getPlayer().teleport(new Location(_netherWorld, 0, 90, 0)); + event.setCancelled(true); + } + } + + @EventHandler + public void breakBlock(BlockBreakEvent event) + { + Block block = event.getBlock(); + Player player = event.getPlayer(); + ItemStack item = player.getItemInHand(); + + if (player.getGameMode() == GameMode.CREATIVE) + { + return; + } + + if (!block.getWorld().equals(_netherWorld)) + { + return; + } + + _portals + .stream() + .filter(portal -> UtilAlg.getAverageBlockLocation(portal.getToBlocks()).distance(block.getLocation()) < 15) + .limit(1) + .forEach(portal -> { + UtilPlayer.message(player, F.main("Clans", "You are not allowed to break this block.")); + event.setCancelled(true); + }); + + if (!item.getType().equals(Material.GOLD_PICKAXE)) + { + UtilPlayer.message(player, F.main("Clans", "You can only break blocks in the Nether with a " + F.elem("Golden Pickaxe") + ".")); + event.setCancelled(true); + return; + } + + if (block.getType().equals(Material.OBSIDIAN) || block.getType().equals(Material.PORTAL)) + { + UtilPlayer.message(player, F.main("Clans", "You are not allowed to break this block.")); + event.setCancelled(true); + return; + } + } + + @EventHandler + public void placeBlock(BlockPlaceEvent event) + { + Block block = event.getBlock(); + Player player = event.getPlayer(); + ItemStack item = player.getItemInHand(); + + if (player.getGameMode() == GameMode.CREATIVE) + { + return; + } + + if (!block.getWorld().equals(_netherWorld)) + { + return; + } + + if (!UtilItem.isFromNether(item)) + { + UtilPlayer.message(player, F.main("Clans", "You can only place blocks here that come from " + F.clansNether("The Nether") + ".")); + event.setCancelled(true); + return; + } + + _portals + .stream() + .filter(portal -> UtilAlg.getAverageBlockLocation(portal.getToBlocks()).distance(block.getLocation()) < 15) + .limit(1) + .forEach(portal -> { + UtilPlayer.message(player, F.main("Clans", "You are not allowed to place blocks here.")); + event.setCancelled(true); + }); + + if (block.getType().equals(Material.OBSIDIAN) || block.getType().equals(Material.PORTAL)) + { + UtilPlayer.message(player, F.main("Clans", "You are not allowed to place blocks here.")); + event.setCancelled(true); + return; + } + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() == UpdateType.FAST) + { + UtilServer.getPlayersCollection() + .stream() + .filter(player -> player.getWorld().equals(_netherWorld)) + .forEach(player -> { + player.setCompassTarget(new Location(_netherWorld, -200.d + UtilMath.r(400), player.getLocation().getY(), -200.d + UtilMath.r(400))); + _clansManager.getItemMapManager().removeMap(player); + }); + } + + if (event.getType() == UpdateType.SLOW) + { + _portals.forEach(portal -> { + portal.getFromObsidianBlocks().forEach(block -> UtilBlock.setSilent(block, Material.OBSIDIAN)); + portal.getFromPortalBlocks().forEach(block -> UtilBlock.setSilent(block, Material.PORTAL)); + + portal.getToObsidianBlocks().forEach(block -> UtilBlock.setSilent(block, Material.OBSIDIAN)); + portal.getToPortalBlocks().forEach(block -> UtilBlock.setSilent(block, Material.PORTAL)); + }); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPortal(PlayerPortalEvent event) + { + Player player = event.getPlayer(); + Location location = player.getLocation(); + + ClanTerritory territory = _clansManager.getClanUtility().getClaim(location); + + if (event.getTo().getWorld().equals(_netherWorld)) + { + if (territory != null && territory.Owner.equals("Borderlands")) + { + _portals + .stream() + .filter(portal -> + portal.getFromPortalBlocks() + .stream() + .filter(block -> player.getLocation().distance(block.getLocation()) <= 2) + .iterator().hasNext() + ).limit(1) + .forEach(portal -> { + event.setTo(portal.getToOut()); + _clansManager.ClanTips.displayTip(TipType.ENTER_NETHER, player); + }); + } + } + else + { + _portals + .stream() + .filter(portal -> + portal.getToPortalBlocks() + .stream() + .filter(block -> player.getLocation().distance(block.getLocation()) <= 2) + .iterator().hasNext() + ).limit(1) + .forEach(portal -> { + event.setTo(UtilAlg.getAverageBlockLocation(portal.getFromPortalBlocks())); + }); + } + } + + public World getNetherWorld() + { + return _netherWorld; + } + + public boolean isInNether(Player player) + { + return player.getWorld().equals(_netherWorld); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/Portal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/Portal.java new file mode 100644 index 000000000..362599881 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/nether/Portal.java @@ -0,0 +1,143 @@ +package mineplex.game.clans.clans.nether; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; + +import com.google.common.collect.Lists; + +import mineplex.core.common.util.UtilBlock; + +public class Portal +{ + private List _fromPortalBlocks; + private List _fromObsidianBlocks; + + private List _toPortalBlocks; + private List _toObsidianBlocks; + + private List _fromBlocks; + private List _toBlocks; + + private Location _toOut; + + public final boolean Success; + + public Portal(Location from, Location to, Location toOut) + { + _fromPortalBlocks = Lists.newArrayList(); + _fromObsidianBlocks = Lists.newArrayList(); + + _toPortalBlocks = Lists.newArrayList(); + _toObsidianBlocks = Lists.newArrayList(); + + _toOut = toOut; + + if (!isValidPortalBlock(from.getBlock()) || !isValidPortalBlock(to.getBlock())) + { + if (!isValidPortalBlock(from.getBlock())) + from = UtilBlock.getInRadius(from.getBlock(), 4).keySet().stream().filter(this::isValidPortalBlock).limit(1).iterator().next().getLocation(); + + if (!isValidPortalBlock(to.getBlock())) + to = UtilBlock.getInRadius(to.getBlock(), 4).keySet().stream().filter(this::isValidPortalBlock).limit(1).iterator().next().getLocation(); + + if (to == null || from == null) + { + System.out.println("[PORTAL] INVALID PORTAL PROVIDED (" + from + " --> " + to + ")"); + + Success = false; + + return; + } + } + + for (Block other : UtilBlock.getInRadius(from, 25).keySet()) + { + if (other.getType() == Material.OBSIDIAN) + { + _fromObsidianBlocks.add(other); + } + else if (other.getType() == Material.PORTAL) + { + _fromPortalBlocks.add(other); + } + } + + for (Block other : UtilBlock.getInRadius(to, 7.5d).keySet()) + { + if (other.getType() == Material.OBSIDIAN) + { + _toObsidianBlocks.add(other); + } + else if (other.getType() == Material.PORTAL) + { + _toPortalBlocks.add(other); + } + } + + _fromBlocks = new ArrayList<>(); + _toBlocks = new ArrayList<>(); + + _fromBlocks.addAll(_fromObsidianBlocks); + _fromBlocks.addAll(_fromPortalBlocks); + _toBlocks.addAll(_toObsidianBlocks); + _toBlocks.addAll(_toPortalBlocks); + + Success = true; + } + + public Location getToOut() + { + return _toOut; + } + + public List getFromPortalBlocks() + { + return _fromPortalBlocks; + } + + public List getFromObsidianBlocks() + { + return _fromObsidianBlocks; + } + + public List getToPortalBlocks() + { + return _toPortalBlocks; + } + + public List getToObsidianBlocks() + { + return _toObsidianBlocks; + } + + public List getFromBlocks() + { + return _fromBlocks; + } + + public List getToBlocks() + { + return _toBlocks; + } + + private boolean isValidPortalBlock(Block block) + { + return block.getType() == Material.OBSIDIAN || block.getType() == Material.PORTAL; + } + + public static Portal create(Location from, Location to, Location toOut) + { + Portal portal = new Portal(from, to, toOut); + + if (!portal.Success) + { + return null; + } + + return portal; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/observer/ObserverManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/observer/ObserverManager.java index 3c9b12958..b5e97bdbc 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/observer/ObserverManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/observer/ObserverManager.java @@ -19,6 +19,7 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.MiniPlugin; +import mineplex.core.common.Rank; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; import mineplex.game.clans.clans.ClansManager; @@ -165,6 +166,11 @@ public class ObserverManager extends MiniPlugin public boolean canEnterObserverMode(Player player, boolean notify) { + if (_clansManager.getClientManager().hasRank(player, Rank.CMOD)) + { + return true; + } + ClanTerritory territory = _clansManager.getClanUtility().getClaim(player.getLocation()); if (territory == null || !territory.isSafe(player.getLocation())) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/Outpost.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/Outpost.java deleted file mode 100644 index 94f61dfe4..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/Outpost.java +++ /dev/null @@ -1,483 +0,0 @@ -package mineplex.game.clans.clans.outpost; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.FallingBlock; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.util.Vector; - -import mineplex.core.common.util.C; -import mineplex.core.common.util.ColorFader; -import mineplex.core.common.util.F; -import mineplex.core.common.util.LoopIterator; -import mineplex.core.common.util.NonFinalInteger; -import mineplex.core.common.util.RGBData; -import mineplex.core.common.util.UtilAction; -import mineplex.core.common.util.UtilAlg; -import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilColor; -import mineplex.core.common.util.UtilEvent; -import mineplex.core.common.util.UtilEvent.ActionType; -import mineplex.core.common.util.UtilItem; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilParticle; -import mineplex.core.common.util.UtilParticle.ParticleType; -import mineplex.core.common.util.UtilParticle.ViewDist; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilText; -import mineplex.core.common.util.UtilTextMiddle; -import mineplex.core.hologram.Hologram; -import mineplex.core.itemstack.ItemBuilder; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.clans.ClanInfo; -import mineplex.game.clans.clans.ClansBlacklist; -import mineplex.game.clans.core.repository.ClanTerritory; -import net.minecraft.server.v1_8_R3.AxisAlignedBB; - -public class Outpost implements Listener -{ - protected static final long MAX_LIFETIME = 5 * 60 * 1000; // 30 minutes - public static final ItemStack OUTPOST_ITEM = new ItemBuilder(Material.NETHERRACK, 1).setRawTitle(C.cBlue + "Outpost").setLore(C.cWhite + "It appears to be a contraption of some sort!").build(); - public static final byte OUTPOST_BLOCK_DATA = (byte) 137; - - private OutpostManager _host; - - private ClanInfo _clan; - - private Location _startCorner; - private Location _origin; - private Location _endCorner; - - private Location _forceFieldStart; - private Location _forceFieldEnd; - - private Location _core; - - private LinkedHashMap _blocks; - private LinkedHashMap _buildQueue; - - protected OutpostType _type; - private OutpostState _state; - - private Hologram _preHologram; - private Hologram _preHologram2; - - private LoopIterator _circleStages; - private LoopIterator _reverseCircleStages; - - private List _builders; - - private List _removalQueue; - - private ColorFader _fader = new ColorFader(30, UtilColor.hexToRgb(0x00A296), UtilColor.hexToRgb(0x29E6B6)); - - private long _spawnTime; - - public Outpost(OutpostManager host, ClanInfo clan, Location location, OutpostType type) - { - _host = host; - - _clan = clan; - - _startCorner = location.clone().subtract(type._size, 1, type._size); - _endCorner = location.clone().add(type._size + .9, type._ySize - 1, type._size + .9); - - _builders = new ArrayList<>(); - _removalQueue = new ArrayList<>(); - - _forceFieldStart = _startCorner.clone().subtract(3, 0, 3); - _forceFieldEnd = _endCorner.clone().add(3, 0, 3); - - _origin = location.clone(); - - _type = type; - - _spawnTime = System.currentTimeMillis(); - - _core = _type.getCoreLocation(_origin); - - _preHologram = new Hologram(_clan.Clans.getHologramManager(), _origin.clone().add(0.5, 2.3, 0.5), F.elem(_clan.getName()) + C.cWhite + "'s Outpost block"); - _preHologram2 = new Hologram(_clan.Clans.getHologramManager(), _origin.clone().add(0.5, 3, 0.5), "Despawning: " + UtilText.getProgress(null, 0, null, true)); - - _preHologram.start(); - _preHologram2.start(); - - _state = OutpostState.AWAITING; - } - - private void cleanup() - { - _blocks = null; - - if (_preHologram != null) _preHologram.stop(); - if (_preHologram2 != null) _preHologram2.stop(); - - _preHologram = null; - _preHologram2 = null; - - _state = OutpostState.DEAD; - - _host.queueForRemoval(_clan.getName()); - } - - @EventHandler - public void onInteract(PlayerInteractEvent event) - { - if (getState() != OutpostState.AWAITING) - { - return; - } - - if (!UtilEvent.isAction(event, ActionType.R_BLOCK)) - { - return; - } - - if (getLifetime() <= 2000) - { - return; - } - - if (!_clan.equals(_clan.Clans.getClanUtility().getClanByPlayer(event.getPlayer()))) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "This is not yours to activate!")); - return; - } - - if (event.getClickedBlock() != null && _origin.equals(event.getClickedBlock().getLocation())) - { - if (event.getClickedBlock().getType().equals(Material.NETHERRACK)) - { - _origin.getBlock().setType(Material.AIR); - beginConstruction(); - } - } - } - - @EventHandler - public void onBlockDamage(BlockDamageEvent event) - { - if (event.getBlock().getLocation().equals(_core) && getState() == OutpostState.LIVE) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "You have destroyed " + F.elem(_clan.getName()) + "'s Outpost!")); - - _core.getBlock().setType(Material.AIR); - - _clan.inform("Your Outpost has been destroyed!", null); - UtilTextMiddle.display("Siege", "Your Outpost has been destroyed", 20, 100, 20, _clan.getOnlinePlayersArray()); - - if (getState() == OutpostState.AWAITING) - { - cleanup(); - } - else - { - kill(); - } - - event.setCancelled(true); - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent event) - { - if (getState() == OutpostState.AWAITING && event.getBlock().getLocation().equals(_origin)) - { - _origin.getBlock().setType(Material.AIR); - _origin.getWorld().dropItem(_origin, OUTPOST_ITEM); - _clan.inform("Your Outpost block has been destroyed.", null); - cleanup(); - event.setCancelled(true); - return; - } - - System.out.println(_blocks); - _blocks.values().stream().filter(event.getBlock().getLocation()::equals).forEach(block -> { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not break blocks in Outposts.")); - event.setCancelled(true); - }); - } - - @EventHandler - public void onBlockPlace(BlockPlaceEvent event) - { - if (UtilAlg.inBoundingBox(event.getBlock().getLocation(), _startCorner, _endCorner)) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not place blocks in Outposts.")); - event.setCancelled(true); - } - } - - protected void update() - { - if (_state == OutpostState.AWAITING) - { - if (getLifetime() > 60000) - { - _origin.getBlock().setType(Material.AIR); - _clan.inform("You have lost your Outpost block, as no one activated it fast enough!", null); - cleanup(); - return; - } - - _preHologram2.setText(UtilText.getProgress(null, UtilMath.clamp(getLifetime(), 0., 60000.) / 60000., null, true)); - - RGBData color = UtilColor.RgbLightBlue; - - for (int x = -_type._size; x <= _type._size; x++) - { - for (int z = -_type._size; z <= _type._size; z++) - { - if (x == -_type._size || x == _type._size || z == -_type._size || z == _type._size) - { - UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, UtilBlock.getHighest(_origin.getWorld(), _origin.clone().add(x + .5, .1, z + .5).getBlockX(), _origin.clone().add(x + .5, .1, z + .5).getBlockZ()).getLocation().add(0.5, 0, 0.5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1f, 0, ViewDist.NORMAL); - } - } - } - - return; - } - - if (_state == OutpostState.CONSTRUCTING) - { - if (_buildQueue.isEmpty()) - { - _state = OutpostState.LIVE; - - return; - } - else - { - Iterator iterator = _buildQueue.keySet().iterator(); - - if (iterator.hasNext()) - { - _buildQueue.remove(iterator.next()).set(); - } - } - - // Forcefield - RGBData color = UtilColor.RgbLightBlue; - - for (int x = -_type._size; x <= _type._size; x++) - { - for (int z = -_type._size; z <= _type._size; z++) - { - if (x == -_type._size || x == _type._size || z == -_type._size || z == _type._size) - { - UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, _origin.clone().add(x + .5, .1, z + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1f, 0, ViewDist.NORMAL); - } - } - } - } - - RGBData next = _fader.next(); - - { - RGBData color = _state == OutpostState.LIVE ? next : UtilColor.RgbRed; - - Vector nextCircleStage = _circleStages.next(); - - double circleX = nextCircleStage.getX(); - double circleZ = nextCircleStage.getZ(); - - UtilParticle.PlayParticleToAll(ParticleType.MOB_SPELL, _core.clone().add(circleX + .5, 1.1d, circleZ + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 5.f, 0, ViewDist.NORMAL); - } - - { - RGBData color = _state == OutpostState.LIVE ? next : UtilColor.RgbRed; - - Vector nextCircleStage = _reverseCircleStages.next(); - - double circleX = nextCircleStage.getX(); - double circleZ = nextCircleStage.getZ(); - - UtilParticle.PlayParticleToAll(ParticleType.MOB_SPELL, _core.clone().add(circleX + .5, 1.1d, circleZ + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 5.f, 0, ViewDist.NORMAL); - } - } - - @EventHandler - public void forcefield(UpdateEvent event) - { - if (!_removalQueue.isEmpty()) - { - _builders.remove(_removalQueue.remove(0)); - } - - if (event.getType() == UpdateType.TICK && getState() == OutpostState.CONSTRUCTING) - { - for (OutpostBuilder builder : _builders) - { - builder.tick(); - } - } - - if (event.getType() != UpdateType.FAST && getState() == OutpostState.CONSTRUCTING) - { - return; - } - - UtilServer.getPlayersCollection().stream() - .filter(player -> !_clan.isMember(player)) - .filter(player -> UtilAlg.inBoundingBox(player.getLocation(), _forceFieldStart, _forceFieldEnd)) - .forEach(player -> { - UtilAction.velocity(player, UtilAlg.getTrajectory2d(_core, player.getLocation()), 1, true, 0.8, 0, 1.1, true); - UtilPlayer.message(player, F.main("Clans", "This Outpost is still under construction!")); - player.playSound(player.getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); - }); - } - - public void beginConstruction() - { - // Cleanup pre-Outpost stuff - _preHologram.stop(); - _preHologram2.stop(); - - _preHologram = null; - _preHologram = null; - - _state = OutpostState.CONSTRUCTING; - _blocks = new LinkedHashMap<>(_buildQueue = _type.createBuildQueue(_origin, _clan.Clans)); - - { - Location pos = UtilBlock.getHighest(_startCorner.getWorld(), _startCorner.clone().subtract(1, 0, 1).getBlockX(), _startCorner.clone().subtract(1, 0, 1).getBlockZ()).getLocation(); - - _builders.add(new OutpostBuilder(pos, "Peasant", _type.getWallLocations(_origin), this)); - } - - _clan.inform("Siege", "Your Outpost is now being constructed.", null); - - _circleStages = new LoopIterator(circleAround(new Vector(0., 0., 0.), 40, .6d)); - - List reverse = circleAround(new Vector(0., 0., 0.), 40, .6d); - Collections.reverse(reverse); - _reverseCircleStages = new LoopIterator(reverse); - - //Inform nearby Clans - for (int chunkX = -3; chunkX < 3; chunkX++) - { - for (int chunkZ = -3; chunkZ < 3; chunkZ++) - { - ClanTerritory territory = _clan.Clans.getClanUtility().getClaim(_origin.getWorld().getChunkAt(_origin.getChunk().getX() + chunkX, _origin.getChunk().getZ() + chunkZ)); - - if (territory != null && ClansBlacklist.isValidClanName(territory.Owner)) - { - ClanInfo clan = _clan.Clans.getClanUtility().getClanByClanName(territory.Owner); - - clan.inform("A siege has begun near your territory!", null); - UtilTextMiddle.display("Siege", "A Siege has been declared on your Clan!", 20, 100, 20, clan.getOnlinePlayersArray()); - } - } - } - } - - private List circleAround(Vector origin, int points, double radius) - { - List list = new LinkedList<>(); - - double slice = 2 * Math.PI / points; - - for (int point = 0; point < points; point++) - { - double angle = slice * point; - list.add(new Vector(origin.getX() + radius * Math.cos(angle), 0, origin.getZ() + radius * Math.sin(angle))); - } - - return list; - } - - public void instakill() - { - _blocks.values().forEach(OutpostBlock::restore); - - cleanup(); - } - - public void kill() - { - _state = OutpostState.DESTRUCTING; - - NonFinalInteger wait = new NonFinalInteger(0); - - _blocks.values().stream().filter(block -> UtilMath.random.nextBoolean() && UtilMath.random.nextBoolean() && UtilMath.random.nextBoolean() && UtilMath.random.nextBoolean()).forEach(block -> - _host.runSyncLater(() -> { - UtilParticle.PlayParticle(ParticleType.LARGE_EXPLODE, block._loc, new Vector(0,0,0), 1f, 1, ViewDist.NORMAL); - _origin.getWorld().playSound(block._loc, Sound.EXPLODE, 1.0f, 1.0f); - }, wait.add(4 + UtilMath.random.nextInt(4)).get()) - ); - - _host.runSyncLater(() -> { - _blocks.values().forEach(block -> { - Material mat = Material.getMaterial(block._id); - - if (UtilItem.isTranslucent(mat)) - { - block.restore(); - return; - } - - FallingBlock fall = block._loc.getWorld().spawnFallingBlock(block._loc, block._id, block._data); - fall.setDropItem(false); - Vector vec = UtilAlg.getTrajectory(fall.getLocation(), getExactMiddle()); - - UtilAction.velocity(fall, vec, 1, false, 0, 0.6, 10, false); - - fall.setMetadata("ClansOutpost", new FixedMetadataValue(_clan.Clans.getPlugin(), _clan.getName())); - - block.restore(); - }); - - cleanup(); - }, wait.get() + 5L); - - _clan.inform("Your Clan's Outpost has been destroyed.", null); - } - - public ClanInfo getClan() - { - return _clan; - } - - public long getLifetime() - { - return System.currentTimeMillis() - _spawnTime; - } - - public AxisAlignedBB getBounds() - { - return UtilAlg.toBoundingBox(_startCorner, _endCorner); - } - - public Location getExactMiddle() - { - return UtilAlg.getMidpoint(_startCorner, _endCorner); - } - - public OutpostState getState() - { - return _state; - } - - public void queueForRemoval(OutpostBuilder builder) - { - _removalQueue.add(builder); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBlock.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBlock.java deleted file mode 100644 index cf5b4dac9..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBlock.java +++ /dev/null @@ -1,57 +0,0 @@ -package mineplex.game.clans.clans.outpost; - -import java.util.Map; - -import org.bukkit.Effect; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.BlockState; - -import mineplex.core.common.util.UtilWorld; - -public class OutpostBlock -{ - protected Location _loc; - protected int _id; - protected byte _data; - - protected int _originalId; - protected byte _originalData; - - public OutpostBlock(Map blocks, Location loc, int id, byte data) - { - _loc = loc; - _id = id; - _data = data; - - String locStr = UtilWorld.locToStr(loc); - - if (blocks.containsKey(locStr)) - { - _originalId = blocks.get(locStr)._originalId; - _originalData = blocks.get(locStr)._originalData; - } - else - { - _originalId = _loc.getBlock().getTypeId(); - _originalData = _loc.getBlock().getData(); - } - } - - public void set() - { - _loc.getBlock().setTypeIdAndData(_id, _data, false); - if (_id != 0) - { - _loc.getWorld().playEffect(_loc, Effect.STEP_SOUND, Material.getMaterial(_id), 10); - } - } - - public void restore() - { - BlockState state = _loc.getBlock().getState(); - state.setTypeId(_originalId); - state.setRawData(_originalData); - state.update(true, false); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBuilder.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBuilder.java deleted file mode 100644 index 51b0724ad..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostBuilder.java +++ /dev/null @@ -1,130 +0,0 @@ -package mineplex.game.clans.clans.outpost; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.entity.Skeleton; -import org.bukkit.inventory.ItemStack; - -import com.mojang.authlib.GameProfile; - -import mineplex.core.common.util.UtilEnt; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.disguise.disguises.DisguisePlayer; -import mineplex.game.clans.clans.outpost.pathing.AStar; -import mineplex.game.clans.clans.outpost.pathing.AStar.InvalidPathException; -import mineplex.game.clans.clans.outpost.pathing.PathingResult; -import mineplex.game.clans.clans.outpost.pathing.Tile; - -public class OutpostBuilder -{ - private Skeleton _entity; - - private List _path; - private int _pathPos; - private List _moveLocations; - private int _nextLocation; - private long _arrivedTime; - private long _lastMovement; - - private Outpost _host; - - public OutpostBuilder(Location pos, String name, List locations, Outpost host) - { - _host = host; - - Location spawnLoc = pos; - Skeleton skel = pos.getWorld().spawn(spawnLoc, Skeleton.class); - skel.teleport(spawnLoc); - skel.setHealth(20); - UtilEnt.Vegetate(skel); - UtilEnt.silence(skel, true); - - skel.getEquipment().setHelmet(new ItemStack(Material.NETHER_BRICK_ITEM, 1)); - skel.getEquipment().setItemInHand(new ItemStack(Material.IRON_PICKAXE, 1)); - - // Get in range - List inRange = UtilPlayer.getNearby(spawnLoc, 75d); - - // Disguise - DisguisePlayer disguise = new DisguisePlayer(skel, new GameProfile(Bukkit.getOfflinePlayer("Chiss").getUniqueId(), "Chiss")); - host.getClan().Clans.getDisguiseManager().disguise(disguise, inRange.toArray(new Player[inRange.size()])); - - _entity = skel; - - _moveLocations = locations; - } - - public void tick() - { - if (_path == null || _arrivedTime != -1) - { - _nextLocation = UtilMath.random.nextInt(_moveLocations.size()); - _path = calculatePath(); - _pathPos = 0; - return; - } - - if (System.currentTimeMillis() - _lastMovement >= 500) - { - if (_pathPos == _path.size() - 1) - { - _arrivedTime = 1; - } - else - { - _entity.teleport(_path.get(++_pathPos)); - _arrivedTime = -1; - } - - _lastMovement = System.currentTimeMillis(); - } - } - - private List calculatePath() - { - Location start = _entity.getLocation(); - Location end = _moveLocations.get(_nextLocation); - int range = _host._type._size * 2; - - try - { - AStar pathFinder = new AStar(start, end, range); - ArrayList route = pathFinder.iterate(); - PathingResult res = pathFinder.getPathingResult(); - - if (res == PathingResult.NO_PATH) - { - return Arrays.asList(_moveLocations.get(_nextLocation)); - } - - List list = new ArrayList<>(); - - for (Tile tile : route) - { - list.add(tile.getLocation(start)); - } - - return list; - } - catch (InvalidPathException e) - { - cleanup(); - - return null; - } - } - - private void cleanup() - { - _entity.remove(); - _host.queueForRemoval(this); - } - -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostManager.java deleted file mode 100644 index 355baa093..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostManager.java +++ /dev/null @@ -1,212 +0,0 @@ -package mineplex.game.clans.clans.outpost; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; - -import mineplex.core.MiniPlugin; -import mineplex.core.common.events.ServerShutdownEvent; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilAlg; -import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilItem; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.recharge.Recharge; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.clans.ClanInfo; -import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.event.PlayerClaimTerritoryEvent; - -public class OutpostManager extends MiniPlugin -{ - private ClansManager _clansManager; - - private Map _outposts = new HashMap<>(); - - private List _removalQueue; - - public OutpostManager(ClansManager clansManager) - { - super("Outpost Manager", clansManager.getPlugin()); - - _clansManager = clansManager; - - _removalQueue = new ArrayList<>(); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlaceBlock(BlockPlaceEvent event) - { - if (event.getItemInHand().isSimilar(Outpost.OUTPOST_ITEM)) - { - if (Spawn(event.getPlayer(), event.getBlock().getLocation(), OutpostType.MK2)) - { - event.getBlock().setData((byte) Outpost.OUTPOST_BLOCK_DATA); - } - else - { - event.setCancelled(true); - } - } - } - - public boolean Spawn(Player player, Location location, OutpostType type) - { - if (!_clansManager.isInClan(player)) - { - UtilPlayer.message(player, F.main("Clans", "You must be in a Clan to place an Outpost.")); - return false; - } - - if (location.getBlockY() < 10) - { - UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost this deep.")); - return false; - } - - ClanInfo clan = _clansManager.getClan(player); - - if (UtilItem.isBoundless(location.clone().subtract(0, 1, 0).getBlock().getType())) - { - UtilPlayer.message(player, F.main("Clans", "An Outpost must not be placed floating.")); - return false; - } - - if (Get(clan) != null) - { - UtilPlayer.message(player, F.main("Clans", "Your clan already has an outpost")); - return false; - } - - if (_clansManager.getClanUtility().getClaim(location) != null) - { - UtilPlayer.message(player, F.main("Clans", "An Outpost must be placed in the Wilderness.")); - return false; - } - - for (Outpost outpost : _outposts.values()) - { - if (UtilMath.offset(location, outpost.getExactMiddle()) < 14) - { - UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost near other Outposts.")); - return false; - } - } - - for (int x = -type._size; x < type._size; x++) - { - for (int y = -1; y < type._ySize; y++) - { - for (int z = -type._size; z < type._size; z++) - { - Location loc = location.clone().add(x, y, z); - - if (_clansManager.getClanUtility().isClaimed(loc)) - { - UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost where it may intersect with claimed territory.")); - return false; - } - - if (UtilBlock.airFoliage(location.clone().add(x, -1, z).getBlock())) - { - UtilPlayer.message(player, F.main("Clans", "An Outpost cannot be placed floating.")); - return false; - } - } - } - } - - _outposts.put(clan.getName(), new Outpost(this, clan, location, type)); - - _plugin.getServer().getPluginManager().registerEvents(_outposts.get(clan.getName()), _plugin); - - return true; - } - - @EventHandler - public void onBlockFall(EntityChangeBlockEvent event) - { - if (event.getEntity().hasMetadata("ClansOutpost")) - { - event.setCancelled(true); - } - } - - @EventHandler - public void onServerShutdown(ServerShutdownEvent event) - { - for (Outpost outpost : _outposts.values()) - { - outpost.instakill(); - } - } - - @EventHandler - public void onClaim(PlayerClaimTerritoryEvent event) - { - for (Outpost outpost : _outposts.values()) - { - if (outpost.getBounds().b(UtilAlg.toBoundingBox(event.getClaimedChunk().getBlock(0, 0, 0).getLocation(), event.getClaimedChunk().getBlock(15, 254, 15).getLocation()))) - { - event.setCancelled(true); - UtilPlayer.message(event.getClaimer(), F.main("Clans", "You cannot claim this territory as it overlaps with " + F.elem(outpost.getClan().getName()) + "'s Outpost.")); - break; - } - } - } - - @EventHandler - public void update(UpdateEvent event) - { - for (Outpost outpost : _outposts.values()) - { - if (outpost.getState() != OutpostState.DEAD) - { - if (outpost.getState() == OutpostState.CONSTRUCTING ? event.getType() == UpdateType.TICK : event.getType() == UpdateType.TICK) - { - outpost.update(); - } - } - } - - if (event.getType() == UpdateType.FASTER) - { - if (!_removalQueue.isEmpty()) - { - HandlerList.unregisterAll(_outposts.remove(_removalQueue.remove(0))); - } - } - - if (event.getType() == UpdateType.TWOSEC) - { - for (Outpost outpost : _outposts.values()) - { - if (outpost.getState() == OutpostState.LIVE && outpost.getLifetime() > Outpost.MAX_LIFETIME) - { - outpost.kill(); - } - } - } - } - - public Outpost Get(ClanInfo clan) - { - return _outposts.get(clan.getName().toLowerCase()); - } - - public void queueForRemoval(String name) - { - _removalQueue.add(name); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostState.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostState.java deleted file mode 100644 index 310e9bb59..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostState.java +++ /dev/null @@ -1,10 +0,0 @@ -package mineplex.game.clans.clans.outpost; - -public enum OutpostState -{ - AWAITING, - CONSTRUCTING, - LIVE, - DESTRUCTING, - DEAD; -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/AStar.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/AStar.java deleted file mode 100644 index b3da829eb..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/AStar.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * By @Adamki11s - */ - -package mineplex.game.clans.clans.outpost.pathing; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.material.Gate; - -/** - * Not made by meee (NewGarbo) - * https://bukkit.org/threads/lib-a-pathfinding-algorithm.129786/ - */ -public class AStar -{ - private final int _sx; - private final int _sy; - private final int _sz; - private final int _ex; - private final int _ey; - private final int _ez; - private final World _world; - - private PathingResult _result; - - private HashMap _open = new HashMap(); - private HashMap _closed = new HashMap(); - - private void addToOpenList(Tile t, boolean modify) - { - if (_open.containsKey(t.getUID())) - { - if (modify) - { - _open.put(t.getUID(), t); - } - } - else - { - _open.put(t.getUID(), t); - } - } - - private void addToClosedList(Tile t) - { - if (!_closed.containsKey(t.getUID())) - { - _closed.put(t.getUID(), t); - } - } - - private final int _range; - private final String _endUID; - - public AStar(Location start, Location end, int range) throws InvalidPathException - { - boolean s = true, e = true; - - if (!(s = isLocationWalkable(start)) || !(e = isLocationWalkable(end))) - { - throw new InvalidPathException(s, e); - } - - _world = start.getWorld(); - _sx = start.getBlockX(); - _sy = start.getBlockY(); - _sz = start.getBlockZ(); - _ex = end.getBlockX(); - _ey = end.getBlockY(); - _ez = end.getBlockZ(); - - _range = range; - - short sh = 0; - Tile t = new Tile(sh, sh, sh, null); - t.calculateBoth(_sx, _sy, _sz, _ex, _ey, _ez, true); - _open.put(t.getUID(), t); - processAdjacentTiles(t); - - StringBuilder b = new StringBuilder(); - b.append(_ex - _sx).append(_ey - _sy).append(_ez - _sz); - _endUID = b.toString(); - } - - public Location getEndLocation() - { - return new Location(_world, _ex, _ey, _ez); - } - - public PathingResult getPathingResult() - { - return _result; - } - - protected boolean _checkOnce = false; - - private int abs(int i) - { - return (i < 0 ? -i : i); - } - - public ArrayList iterate() - { - if (!_checkOnce) - { - // invert the boolean flag - _checkOnce ^= true; - if ((abs(_sx - _ex) > _range) || (abs(_sy - _ey) > _range) || (abs(_sz - _ez) > _range)) - { - _result = PathingResult.NO_PATH; - return null;// jump out - } - } - // while not at end - Tile current = null; - - while (canContinue()) - { - - // get lowest F cost square on open list - current = getLowestFTile(); - - // process tiles - processAdjacentTiles(current); - } - - if (_result != PathingResult.SUCCESS) - { - return null; - } - else - { - // path found - LinkedList routeTrace = new LinkedList(); - Tile parent; - - routeTrace.add(current); - - while ((parent = current.getParent()) != null) - { - routeTrace.add(parent); - current = parent; - } - - Collections.reverse(routeTrace); - - return new ArrayList(routeTrace); - } - } - - private boolean canContinue() - { - // check if open list is empty, if it is no path has been found - if (_open.size() == 0) - { - _result = PathingResult.NO_PATH; - return false; - } - else - { - if (_closed.containsKey(_endUID)) - { - _result = PathingResult.SUCCESS; - return false; - } - else - { - return true; - } - } - } - - private Tile getLowestFTile() - { - double f = 0; - Tile drop = null; - - // get lowest F cost square - for (Tile t : _open.values()) - { - if (f == 0) - { - t.calculateBoth(_sx, _sy, _sz, _ex, _ey, _ez, true); - f = t.getF(); - drop = t; - } - else - { - t.calculateBoth(_sx, _sy, _sz, _ex, _ey, _ez, true); - double posF = t.getF(); - if (posF < f) - { - f = posF; - drop = t; - } - } - } - - // drop from open list and add to closed - - _open.remove(drop.getUID()); - addToClosedList(drop); - - return drop; - } - - private boolean isOnClosedList(Tile t) - { - return _closed.containsKey(t.getUID()); - } - - // pass in the current tile as the parent - private void processAdjacentTiles(Tile current) - { - - // set of possible walk to locations adjacent to current tile - HashSet possible = new HashSet(26); - - for (byte x = -1; x <= 1; x++) - { - for (byte y = -1; y <= 1; y++) - { - for (byte z = -1; z <= 1; z++) - { - - if (x == 0 && y == 0 && z == 0) - { - continue;// don't check current square - } - - Tile t = new Tile((short) (current.getX() + x), (short) (current.getY() + y), (short) (current.getZ() + z), current); - - if (!t.isInRange(_range)) - { - // if block is out of bounds continue - continue; - } - - if (x != 0 && z != 0 && (y == 0 || y == 1)) - { - // check to stop jumping through diagonal blocks - Tile xOff = new Tile((short) (current.getX() + x), (short) (current.getY() + y), (short) (current.getZ()), current), zOff = new Tile((short) (current.getX()), (short) (current.getY() + y), (short) (current.getZ() + z), current); - if (!isTileWalkable(xOff) && !isTileWalkable(zOff)) - { - continue; - } - } - - if (isOnClosedList(t)) - { - // ignore tile - continue; - } - - // only process the tile if it can be walked on - if (isTileWalkable(t)) - { - t.calculateBoth(_sx, _sy, _sz, _ex, _ey, _ez, true); - possible.add(t); - } - - } - } - } - - for (Tile t : possible) - { - // get the reference of the object in the array - Tile openRef = null; - if ((openRef = isOnOpenList(t)) == null) - { - // not on open list, so add - addToOpenList(t, false); - } - else - { - // is on open list, check if path to that square is better using - // G cost - if (t.getG() < openRef.getG()) - { - // if current path is better, change parent - openRef.setParent(current); - // force updates of F, G and H values. - openRef.calculateBoth(_sx, _sy, _sz, _ex, _ey, _ez, true); - } - - } - } - - } - - private Tile isOnOpenList(Tile t) - { - return (_open.containsKey(t.getUID()) ? _open.get(t.getUID()) : null); - /* - * for (Tile o : open) { if (o.equals(t)) { return o; } } return null; - */ - } - - private boolean isTileWalkable(Tile t) - { - Location l = new Location(_world, (_sx + t.getX()), (_sy + t.getY()), (_sz + t.getZ())); - Block b = l.getBlock(); - int i = b.getTypeId(); - - // lava, fire, wheat and ladders cannot be walked on, and of course air - // 85, 107 and 113 stops npcs climbing fences and fence gates - if (i != 10 && i != 11 && i != 51 && i != 59 && i != 65 && i != 0 && i != 85 && i != 107 && i != 113 && !canBlockBeWalkedThrough(i)) - { - // make sure the blocks above are air - - if (b.getRelative(0, 1, 0).getTypeId() == 107) - { - // fench gate check, if closed continue - Gate g = new Gate(b.getRelative(0, 1, 0).getData()); - return (g.isOpen() ? (b.getRelative(0, 2, 0).getTypeId() == 0) : false); - } - return (canBlockBeWalkedThrough(b.getRelative(0, 1, 0).getTypeId()) && b.getRelative(0, 2, 0).getTypeId() == 0); - - } - else - { - return false; - } - } - - private boolean isLocationWalkable(Location l) - { - Block b = l.getBlock(); - int i = b.getTypeId(); - - if (i != 10 && i != 11 && i != 51 && i != 59 && i != 65 && i != 0 && !canBlockBeWalkedThrough(i)) - { - // make sure the blocks above are air or can be walked through - return (canBlockBeWalkedThrough(b.getRelative(0, 1, 0).getTypeId()) && b.getRelative(0, 2, 0).getTypeId() == 0); - } - else - { - return false; - } - } - - private boolean canBlockBeWalkedThrough(int id) - { - return (id == 0 || id == 6 || id == 50 || id == 63 || id == 30 || id == 31 || id == 32 || id == 37 || id == 38 || id == 39 || id == 40 || id == 55 || id == 66 || id == 75 || id == 76 || id == 78); - } - - @SuppressWarnings("serial") - public class InvalidPathException extends Exception - { - private final boolean _s, _e; - - public InvalidPathException(boolean s, boolean e) - { - _s = s; - _e = e; - } - - public String getErrorReason() - { - StringBuilder sb = new StringBuilder(); - if (!_s) - { - sb.append("Start Location was air. "); - } - if (!_e) - { - sb.append("End Location was air."); - } - return sb.toString(); - } - - public boolean isStartNotSolid() - { - return (!_s); - } - - public boolean isEndNotSolid() - { - return (!_e); - } - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/PathingResult.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/PathingResult.java deleted file mode 100644 index 06e0084dc..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/PathingResult.java +++ /dev/null @@ -1,23 +0,0 @@ -package mineplex.game.clans.clans.outpost.pathing; - -/** - * Not made by meee (NewGarbo) - * https://bukkit.org/threads/lib-a-pathfinding-algorithm.129786/ - */ -public enum PathingResult -{ - SUCCESS(0), - NO_PATH(-1); - - private final int _ec; - - PathingResult(int ec) - { - _ec = ec; - } - - public int getEndCode() - { - return _ec; - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/Tile.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/Tile.java deleted file mode 100644 index 133d67278..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/pathing/Tile.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * By @Adamki11s - */ - -package mineplex.game.clans.clans.outpost.pathing; - -import org.bukkit.Location; - -/** - * Not made by meee (NewGarbo) - * https://bukkit.org/threads/lib-a-pathfinding-algorithm.129786/ - */ -public class Tile -{ - // as offset from starting point - private final short _x; - private final short _y; - private final short _z; - - private double _g = -1; - private double _h = -1; - - private Tile _parent = null; - - private final String _uid; - - public Tile(short x, short y, short z, Tile parent) - { - _x = x; - _y = y; - _z = z; - _parent = parent; - - StringBuilder b = new StringBuilder(); - b.append(x); - b.append(y); - b.append(z); - _uid = b.toString(); - - } - - public boolean isInRange(int range) - { - return ((range - abs(_x) >= 0) && (range - abs(_y) >= 0) && (range - abs(_z) >= 0)); - } - - public void setParent(Tile parent) - { - _parent = parent; - } - - public Location getLocation(Location start) - { - return new Location(start.getWorld(), start.getBlockX() + _x, start.getBlockY() + _y, start.getBlockZ() + _z); - } - - public Tile getParent() - { - return _parent; - } - - public short getX() - { - return _x; - } - - public int getX(Location i) - { - return (i.getBlockX() + _x); - } - - public short getY() - { - return _y; - } - - public int getY(Location i) - { - return (i.getBlockY() + _y); - } - - public short getZ() - { - return _z; - } - - public int getZ(Location i) - { - return (i.getBlockZ() + _z); - } - - public String getUID() - { - return _uid; - } - - public boolean equals(Tile t) - { - return (t.getX() == _x && t.getY() == _y && t.getZ() == _z); - } - - public void calculateBoth(int sx, int sy, int sz, int ex, int ey, int ez, boolean update) - { - calculateG(sx, sy, sz, update); - calculateH(sx, sy, sz, ex, ey, ez, update); - } - - public void calculateH(int sx, int sy, int sz, int ex, int ey, int ez, boolean update) - { - // only update if h hasn't been calculated or if forced - if ((!update && _h == -1) || update) - { - int hx = sx + _x, hy = sy + _y, hz = sz + _z; - _h = getEuclideanDistance(hx, hy, hz, ex, ey, ez); - } - } - - // G = the movement cost to move from the starting point A to a given square - // on the grid, following the path generated to get there. - public void calculateG(int sx, int sy, int sz, boolean update) - { - if ((!update && _g == -1) || update) - { - // only update if g hasn't been calculated or if forced - Tile currentParent = getParent(), currentTile = this; - int gCost = 0; - // follow path back to start - while ((currentParent = currentTile.getParent()) != null) - { - int dx = currentTile.getX() - currentParent.getX(), dy = currentTile.getY() - currentParent.getY(), dz = currentTile.getZ() - currentParent.getZ(); - - dx = abs(dx); - dy = abs(dy); - dz = abs(dz); - - if (dx == 1 && dy == 1 && dz == 1) - { - gCost += 1.7; - } else if (((dx == 1 || dz == 1) && dy == 1) || ((dx == 1 || dz == 1) && dy == 0)) - { - gCost += 1.4; - } - else - { - gCost += 1.0; - } - - // move backwards a tile - currentTile = currentParent; - } - _g = gCost; - } - - } - - public double getG() - { - return _g; - } - - public double getH() - { - return _h; - } - - public double getF() - { - // f = h + g - return (_h + _g); - } - - private double getEuclideanDistance(int sx, int sy, int sz, int ex, int ey, int ez) - { - double dx = sx - ex, dy = sy - ey, dz = sz - ez; - return Math.sqrt((dx * dx) + (dy * dy) + (dz * dz)); - } - - private int abs(int i) - { - return (i < 0 ? -i : i); - } - -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/Playtime.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/Playtime.java index 806a00fa1..52c3dfeba 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/Playtime.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/Playtime.java @@ -13,7 +13,6 @@ import mineplex.core.task.TaskManager; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.ClansPlayerStats; import mineplex.game.clans.clans.playtime.command.PlayTimeCommand; -import mineplex.game.clans.clans.playtime.command.cemde; public class Playtime extends MiniClientPlugin { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/command/cemde.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/command/cemde.java deleted file mode 100644 index d170200be..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/playtime/command/cemde.java +++ /dev/null @@ -1,30 +0,0 @@ -package mineplex.game.clans.clans.playtime.command; - -import org.bukkit.entity.Player; - -import mineplex.core.command.CommandBase; -import mineplex.core.common.Rank; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.stats.StatsManager; -import mineplex.game.clans.clans.ClansPlayerStats; -import mineplex.game.clans.clans.pvptimer.PvpTimer; - -public class cemde extends CommandBase -{ - PvpTimer _timer; - public cemde(StatsManager plugin, PvpTimer timer) - { - super(plugin, Rank.ALL, "rstime"); - _timer = timer; - } - - @Override - public void Execute(final Player caller, final String[] args) - { - Plugin.Get(caller).setStat(ClansPlayerStats.PLAY_TIME.id(), args.length == 0 ? 0 : Integer.parseInt(args[0])); - _timer.Get(caller).Skipped = false; - _timer.Get(caller).InformedTimes.clear(); - - UtilPlayer.message(caller, "Reset time."); - } -} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimer.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimer.java deleted file mode 100644 index 6e9150c54..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimer.java +++ /dev/null @@ -1,280 +0,0 @@ -package mineplex.game.clans.clans.pvptimer; - -import java.util.Iterator; - -import org.bukkit.Bukkit; -import org.bukkit.Sound; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerJoinEvent; - -import mineplex.core.MiniClientPlugin; -import mineplex.core.common.jsonchat.ClickEvent; -import mineplex.core.common.jsonchat.JsonMessage; -import mineplex.core.common.util.C; -import mineplex.core.common.util.Callback; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilAction; -import mineplex.core.common.util.UtilAlg; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTextMiddle; -import mineplex.core.common.util.UtilTime; -import mineplex.core.stats.StatsManager; -import mineplex.core.task.TaskManager; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.clans.ClanTips.TipType; -import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.event.ClanTipEvent; -import mineplex.game.clans.clans.event.PlayerEnterTerritoryEvent; -import mineplex.game.clans.clans.playtime.Playtime; -import mineplex.game.clans.clans.playtime.command.cemde; -import mineplex.game.clans.clans.pvptimer.command.PvPTimerCommand; -import mineplex.game.clans.core.repository.ClanTerritory; -import mineplex.game.clans.spawn.Spawn; -import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; -import mineplex.minecraft.game.classcombat.event.FireballHitEntityEvent; -import mineplex.minecraft.game.core.damage.CustomDamageEvent; - -public class PvpTimer extends MiniClientPlugin -{ - public static final String SKIPPED_TASK = "PvpTimer.Skipped"; - private final int[] DISPLAY_TIMES = { 5, 10, 30, 1 * 60, 2 * 60, 5 * 60, 10 * 60, 20 * 60 }; - - private ClansManager _clansManager; - private Playtime _tracker; - - private static long TIMER_LENGTH = 30 * 60; - - public PvpTimer(ClansManager clans, Playtime playtime, StatsManager statsManager) - { - super("PvP Timer", clans.getPlugin()); - _tracker = playtime; - _clansManager = clans; - - addCommand(new cemde(statsManager, this)); - } - - @Override - public void addCommands() - { - addCommand(new PvPTimerCommand(this)); - } - - public void disableFor(final Player caller) - { - TaskManager.Instance.completedTask(new Callback() { - @Override - public void run(Boolean data) - { - Get(caller).Skipped = true; - caller.playSound(caller.getLocation(), Sound.ENDERDRAGON_GROWL, 1f, 0.75f); - } - }, caller, "PvpTimer.Skipped"); - } - - @EventHandler - public void outYouGo(UpdateEvent event) - { - if (event.getType() == UpdateType.SEC) - { - for (Player player : Bukkit.getOnlinePlayers()) - { - if (!hasTimer(player)) continue; - - ClanTerritory territory = _clansManager.getClanUtility().getClaim(player.getLocation()); - - if (territory != null && territory.Owner.equals("Borderlands")) - { - UtilAction.velocity(player, UtilAlg.getTrajectory2d(player.getLocation(), Spawn.ORIGIN), 2.6, true, 0.5, 1, 1.35, true); - player.playSound(player.getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); - - UtilPlayer.message(player, " "); - - UtilPlayer.message(player, C.cDRedB + ">>" + C.cRed + " You are not permitted to enter the Borderlands while under PvP Safety."); - - new JsonMessage(C.cGoldB + "> " + C.cGold + "To permanently disable PvP Safety, click ") - .extra("here") - .color("yellow") - .click(ClickEvent.RUN_COMMAND, "/pvptimer yesiconfirmthatiwouldliketodisablemypvptimerforever") - .extra(".") - .color("gray") - .sendToPlayer(player); - - UtilPlayer.message(player, " "); - } - } - } - } - - @EventHandler - public void territoryEnter(PlayerEnterTerritoryEvent event) - { - String from = event.getLastTerritory(); - String to = event.getNewTerritory(); - - if (from == null && "Borderlands".equals(to) - || to == null && "Borderlands".equals(from)) - { - event.setSendMessage(false); - } - } - - @EventHandler - public void clanTip(ClanTipEvent event) - { - event.setCancelled(hasTimer(event.getPlayer()) && event.getTip() == TipType.ENTER_BORDERLANDS); - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) - { - final Player player = event.getPlayer(); - - if (hasTimer(player)) - { - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { - public void run() - { - UtilTextMiddle.display(C.cGreen + "PvP Safety", C.cGray + "will end in " + UtilTime.MakeStr(getPvPTimerLeft(player) * 1000), 40, 70, 40, player); - } - }, 10); - - UtilPlayer.message(player, F.main("Clans", "You are currently safe from PvP because you are a new player. This safety will end in " + F.elem(UtilTime.MakeStr(getPvPTimerLeft(player) * 1000)))); - UtilPlayer.message(player, F.main("Clans", "Until it ends, you are immune to, and unable to deal PvP damage.")); - UtilPlayer.message(player, F.main("Clans", "If you would like to disable the PvP safety permanently, then type " + F.elem("/pvp") + ".")); - } - } - - @EventHandler - public void inform(UpdateEvent event) - { - if (event.getType() == UpdateType.TWOSEC) - { - for (Player player : Bukkit.getOnlinePlayers()) - { - if (hasTimer(player)) - { - long time = getPvPTimerLeft(player); - PvpTimerClient client = Get(player); - - if (time <= 2) - { - UtilPlayer.message(player, F.main("Clans", "PvP Safety has ended!")); - UtilPlayer.message(player, F.main("Clans", "You are now completely open to attacks, and you can also attack others.")); - player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 1f, 0.75f); - continue; - } - - for (int unit : DISPLAY_TIMES) - { - if (time <= unit && !client.InformedTimes.contains(unit)) - { - UtilPlayer.message(player, F.main("Clans", "PvP Safety will end in " + F.time(UtilTime.MakeStr(unit * 1000)))); - UtilTextMiddle.display(C.cGreen + "Pvp Safety", C.cGray + "ending in " + UtilTime.MakeStr(unit * 1000), 20, 80, 20, player); - client.InformedTimes.add(unit); - } - } - } - } - } - } - - @EventHandler - public void onSkill(SkillTriggerEvent event) - { - if (event.GetTargets() == null) - { - return; - } - - if (event.GetTargets().size() == 1 - && event.GetTargets().get(0) instanceof Player - && hasTimer((Player) event.GetTargets().get(0))) - { - event.SetCancelled(true); - } - - for (Iterator iterator = event.GetTargets().iterator(); iterator.hasNext();) - { - Entity entity = iterator.next(); - - if (entity instanceof Player && hasTimer((Player) entity)) - { - iterator.remove(); - } - } - } - - @EventHandler - public void onFireballHit(FireballHitEntityEvent event) - { - event.setCancelled(event.getHitEntity() instanceof Player && hasTimer((Player) event.getHitEntity())); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerAttack(CustomDamageEvent event) - { - if (event.GetDamageePlayer() == null || event.GetDamagerEntity(true) == null) - { - return; - } - - Player victim = event.GetDamageePlayer(); - Player damager = event.GetDamagerPlayer(true); - - boolean victimTimer = victim != null && hasTimer(victim); - boolean damagerTimer = damager != null && hasTimer(damager); - boolean bothMsg = false; - - if (victimTimer) - { - if (damagerTimer) - { - UtilPlayer.message(damager, F.main("Clans", "You and " + F.name(victim.getName()) + " are still protected from PvP. Type " + F.elem("/pvp") + " to disable.")); - bothMsg = true; - } - else if (damager != null) - { - UtilPlayer.message(damager, F.main("Clans", F.name(victim.getName()) + " is still protected from PvP.")); - } - - event.SetCancelled("Pvp Timer"); - } - - if (damagerTimer) - { - if (victimTimer) - { - if (!bothMsg) UtilPlayer.message(damager, F.main("Clans", "You and " + F.name(victim.getName()) + " are still under PvP Safety. Type " + F.elem("/pvp") + " to disable.")); - } - else if (damager != null) - { - UtilPlayer.message(damager, F.main("Clans", "You are still under PvP Safety.")); - } - - event.SetCancelled("PvP Timer"); - } - - } - - public long getPvPTimerLeft(Player player) - { - long time = (_tracker.getPlaytime(player) + _tracker.getUnsavedPlaytime(player)); - - return (TIMER_LENGTH <= time ? 0 : TIMER_LENGTH - time); - } - - private boolean hasTimer(Player victim) - { - return victim != null && getPvPTimerLeft(victim) > 0 && !Get(victim).Skipped; - } - - @Override - protected PvpTimerClient AddPlayer(String player) - { - return new PvpTimerClient(Bukkit.getPlayer(player)); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimerClient.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimerClient.java deleted file mode 100644 index 82df2bd55..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/PvpTimerClient.java +++ /dev/null @@ -1,20 +0,0 @@ -package mineplex.game.clans.clans.pvptimer; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.entity.Player; - -import mineplex.core.task.TaskManager; - -public class PvpTimerClient -{ - public boolean Skipped; - public List InformedTimes; - - public PvpTimerClient(Player player) - { - Skipped = TaskManager.Instance.hasCompletedTask(player, PvpTimer.SKIPPED_TASK); - InformedTimes = new ArrayList<>(); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/command/PvPTimerCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/command/PvPTimerCommand.java deleted file mode 100644 index 104c4155d..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/pvptimer/command/PvPTimerCommand.java +++ /dev/null @@ -1,63 +0,0 @@ -package mineplex.game.clans.clans.pvptimer.command; - -import org.bukkit.entity.Player; - -import mineplex.core.command.CommandBase; -import mineplex.core.common.Rank; -import mineplex.core.common.jsonchat.ClickEvent; -import mineplex.core.common.jsonchat.JsonMessage; -import mineplex.core.common.util.C; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTime; -import mineplex.game.clans.clans.pvptimer.PvpTimer; - -public class PvPTimerCommand extends CommandBase -{ - public PvPTimerCommand(PvpTimer plugin) - { - super(plugin, Rank.ALL, "pvptimer", "timer", "pvp"); - } - - @Override - public void Execute(Player caller, String[] args) - { - if (args.length == 0) - { - if (Plugin.Get(caller).Skipped) - { - UtilPlayer.message(caller, F.main("Clans", "You have permanently disabled PvP Safety.")); - return; - } - - long pvpTimerLeft = Plugin.getPvPTimerLeft(caller); - - if (pvpTimerLeft == 0) - { - UtilPlayer.message(caller, F.main("Clans", "PvP Safety has already ended.")); - } - else - { - UtilPlayer.message(caller, F.main("Clans", "You have " + F.elem(UtilTime.MakeStr(pvpTimerLeft * 1000)) + " before PvP Safety runs out for you.")); - new JsonMessage(F.main("Clans", "If you would like to permanently disable " + C.mBody + "PvP Safety, click ")) - .extra("here") - .color("green") - .click(ClickEvent.RUN_COMMAND, "/pvptimer yesiconfirmthatiwouldliketodisablemypvptimerforever") - .extra(".") - .color("gray") - - .sendToPlayer(caller); - } - } - else - { - if (args[0].equalsIgnoreCase("yesiconfirmthatiwouldliketodisablemypvptimerforever")) - { - Plugin.disableFor(caller); - UtilPlayer.message(caller, F.main("Clans", "You have disabled PvP Safety.")); - UtilPlayer.message(caller, F.main("Clans", "You are now completely open to attacks, and you can also attack others.")); - } - } - } - -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/regions/ClansRegions.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/regions/ClansRegions.java index bb80a711e..ee09e4677 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/regions/ClansRegions.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/regions/ClansRegions.java @@ -42,8 +42,8 @@ public class ClansRegions extends MiniPlugin public final static int SPAWN_RADIUS = 3; // Radius of spawn claim area (measured in chunks) public final static int SHOP_RADIUS = 5; // Radius of shop claim area (measured in chunks) public final static int FIELDS_RADIUS = 7; // Radius of fields claim area (measured in chunks) - public final static int BORDERLANDS_RADIUS = 50; // Radius of borderlands claim area (measured in chunks) - public static final int BORDER_RADIUS = 768; + public final static int BORDERLANDS_RADIUS = 85; // Radius of borderlands claim area (measured in chunks) + public static final int BORDER_RADIUS = 1319; private ClansManager _manager; private World _world; @@ -66,19 +66,19 @@ public class ClansRegions extends MiniPlugin Location worldCenter = new Location(_world, 0, 0, 0); // Initialize Spawn faction and claims - claimArea("Spawn", SPAWN_RADIUS, 0, false, true, new Location[]{Spawn.getEastSpawn(), Spawn.getWestSpawn()}); + claimArea("Spawn", SPAWN_RADIUS, 0, false, true, new Location[] { Spawn.getNorthSpawn(), Spawn.getSouthSpawn() }); - claimArea("Shops", 2, 0, true, false, new Location[]{Spawn.getNorthTownCenter(), Spawn.getSouthTownCenter()}); - claimArea("Shops", SHOP_RADIUS, 2, false, false, new Location[]{Spawn.getNorthTownCenter(), Spawn.getSouthTownCenter()}); + claimArea("Shops", 2, 0, true, false, new Location[]{Spawn.getWestTownCenter(), Spawn.getEastTownCenter()}); + claimArea("Shops", SHOP_RADIUS, 3, false, false, new Location[]{Spawn.getWestTownCenter(), Spawn.getEastTownCenter()}); // Initialize Fields and Borderlands factions and claims claimArea("Fields", FIELDS_RADIUS, 0, false, true, worldCenter); - claimArea("Borderlands", BORDERLANDS_RADIUS, 32, false, true, worldCenter); + claimArea("Borderlands", BORDERLANDS_RADIUS, 48, false, true, worldCenter); - //debugClan("Spawn"); - //debugClan("Shops"); - //debugClan("Fields"); - //debugClan("Borderlands"); + debugClan("Spawn"); + debugClan("Shops"); + debugClan("Fields"); + debugClan("Borderlands"); } public void initializeBorder() @@ -114,18 +114,21 @@ public class ClansRegions extends MiniPlugin private void clearClaims(String name) { ClanInfo clan = _manager.getClan(name); - System.out.println("Clearing claims for " + name + " with clan id " + clan.getId() + "!"); - if (clan != null) + if (clan == null) { - for (String chunk : clan.getClaimSet()) - { - _manager.getClaimMap().remove(chunk); - } - - clan.getClaimSet().clear(); - _manager.getClanDataAccess().getRepository().removeTerritoryClaims(clan.getId()); + return; } + + System.out.println("Clearing claims for " + name + " with clan id " + clan + "!"); + + for (String chunk : clan.getClaimSet()) + { + _manager.getClaimMap().remove(chunk); + } + + clan.getClaimSet().clear(); + _manager.getClanDataAccess().getRepository().removeTerritoryClaims(clan.getId()); } /** @@ -137,11 +140,11 @@ public class ClansRegions extends MiniPlugin * @param claimOffset - the initial offset in claim (creating a 'hole' with chunk offset radius) * @param safe - whether the chunk claimed is considered a 'safe' (pvp-free) region. */ - private void claimArea(final String clanName, final int chunkRadius, final int claimOffset, final boolean safe, final boolean addNegative, final Location... locations) + public void claimArea(final String clanName, final int chunkRadius, final int claimOffset, final boolean safe, final boolean addNegative, final Location... locations) { final ClanInfo clan = _manager.getClan(clanName); - - if (clan == null ) + + if (clan == null) { _manager.getClanDataAccess().create("ClansRegions", clanName, true, new Callback() { @@ -155,7 +158,7 @@ public class ClansRegions extends MiniPlugin claimArea(data, location, chunkRadius, claimOffset, addNegative, safe); log(String.format("Initialized %s faction territory and creation!", clanName)); } - + debugClan(clanName); } else diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansPlayerScoreboard.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansPlayerScoreboard.java index 4fc9e80ab..c3e213da9 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansPlayerScoreboard.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansPlayerScoreboard.java @@ -9,8 +9,6 @@ import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; -import net.minecraft.server.v1_8_R3.ScoreboardTeam; - import mineplex.core.common.util.C; import mineplex.core.common.util.UtilText; import mineplex.core.scoreboard.PlayerScoreboard; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansScoreboardManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansScoreboardManager.java index 47457a05b..3794ba5fe 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansScoreboardManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/ClansScoreboardManager.java @@ -8,7 +8,6 @@ import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.account.CoreClientManager; import mineplex.core.account.event.OnlineRankUpdateEvent; -import mineplex.core.common.util.C; import mineplex.core.donation.DonationManager; import mineplex.core.scoreboard.PlayerScoreboard; import mineplex.core.scoreboard.ScoreboardData; @@ -20,32 +19,32 @@ import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.scoreboard.elements.ScoreboardElementClan; import mineplex.game.clans.clans.scoreboard.elements.ScoreboardElementPlayer; -import mineplex.game.clans.clans.scoreboard.elements.ScoreboardElementPlayerCount; import mineplex.game.clans.clans.war.WarManager; import mineplex.game.clans.clans.worldevent.WorldEventManager; -import mineplex.game.clans.tutorials.Tutorial; -import mineplex.game.clans.tutorials.TutorialManager; +import mineplex.game.clans.tutorial.TutorialManager; public class ClansScoreboardManager extends ScoreboardManager { private ClansManager _clansManager; private WarManager _warManager; private WorldEventManager _worldEvent; + private TutorialManager _tutorial; - public ClansScoreboardManager(JavaPlugin plugin, ClansManager clansManager, WarManager warManager, WorldEventManager worldEvent, CoreClientManager clientManager, DonationManager donationManager) + public ClansScoreboardManager(JavaPlugin plugin, ClansManager clansManager, WarManager warManager, WorldEventManager worldEvent, TutorialManager tutorial, CoreClientManager clientManager, DonationManager donationManager) { super(plugin, clientManager, donationManager); _clansManager = clansManager; _warManager = warManager; _worldEvent = worldEvent; + _tutorial = tutorial; init(); } private void init() { - setTitle("Clans Alpha " + Clans.VERSION); + setTitle("Clans " + Clans.VERSION); ScoreboardData data = getData("default", true); @@ -55,11 +54,12 @@ public class ClansScoreboardManager extends ScoreboardManager data.writeElement(_warManager); data.writeElement(_worldEvent); + data.writeElement(_tutorial); - for (Tutorial tutorial : TutorialManager.Instance.getTutorials().values()) - { - data.writeElement(tutorial); - } +// for (Tutorial tutorial : TutorialManager.Instance.getTutorials().values()) +// { +// data.writeElement(tutorial); +// } } @EventHandler diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/elements/ScoreboardElementPlayer.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/elements/ScoreboardElementPlayer.java index d0d710721..e110c98eb 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/elements/ScoreboardElementPlayer.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/scoreboard/elements/ScoreboardElementPlayer.java @@ -44,6 +44,12 @@ public class ScoreboardElementPlayer implements ScoreboardElement regionString += C.mBody + "(" + C.mElem + "Trusted" + C.mBody + ")"; } + +// if (_clansManager.getNetherManager().isInNether(player)) +// { +// regionString = C.cRed + "The Nether"; +// } + output.add(regionString); return output; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/SiegeManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/SiegeManager.java new file mode 100644 index 000000000..1c26486b8 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/SiegeManager.java @@ -0,0 +1,308 @@ +package mineplex.game.clans.clans.siege; + +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Slime; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockPlaceEvent; + +import com.google.gson.Gson; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.F; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.siege.outpost.OutpostManager; +import mineplex.game.clans.clans.siege.repository.SiegeWeaponRepository; +import mineplex.game.clans.clans.siege.repository.tokens.SiegeWeaponToken; +import mineplex.game.clans.clans.siege.weapon.Cannon; +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; +import mineplex.game.clans.core.repository.ClanTerritory; +import mineplex.game.clans.spawn.Spawn; +import net.minecraft.server.v1_8_R3.Material; + +public class SiegeManager extends MiniPlugin +{ + private ClansManager _clansManager; + private OutpostManager _outpostManager; + + public NautHashMap LiveSiegeWeapons = new NautHashMap<>(); + public NautHashMap UnsyncedSiegeWeapons = new NautHashMap<>(); + + private Gson _gson; + + private SiegeWeaponRepository _repository; + + public SiegeManager(ClansManager clans) + { + super("Siege Manager", clans.getPlugin()); + + _gson = new Gson(); + + _clansManager = clans; + + _outpostManager = new OutpostManager(clans, this); + + _repository = new SiegeWeaponRepository(clans.getPlugin(), this); + + _outpostManager.loadOutposts(); + + getRepository().getWeaponsByServer(getClansManager().getServerId(), tokens -> + tokens.forEach(token -> + runSync(() -> { + final SiegeWeapon weapon; + + token.Location.getChunk().load(); + + switch(token.WeaponType) + { + case 2: + weapon = new Cannon(SiegeManager.this, token); + break; + default: + System.out.println("[WEAPONS] ERROR WHILST LOADING WEAPON: INVALID WEAPON TYPE"); + return; + } + + System.out.println("[WEAPONS] LOADED SIEGE WEAPON " + weapon.getClass().getSimpleName() + " [" + token.UniqueId + "]"); + + LiveSiegeWeapons.put(Integer.valueOf(token.UniqueId), weapon); + }) + ) + ); + } + + @EventHandler + public void CleanupWeirdos(UpdateEvent event) + { + if (event.getType() == UpdateType.SEC && UtilServer.getPlayers().length != 0) + { + Spawn.getSpawnWorld().getEntitiesByClass(Slime.class).stream().filter(slime -> slime.getSize() != -1).forEach(slime -> { + + boolean part = false; + + for (SiegeWeapon weapon : LiveSiegeWeapons.values()) + { + if (weapon.isPartOf(slime.getUniqueId())) + { + part = true; + break; + } + } + + + if (!part) + for (SiegeWeapon weapon : UnsyncedSiegeWeapons.values()) + { + if (weapon.isPartOf(slime.getUniqueId())) + { + part = true; + break; + } + } + + if (!part) + { + System.out.println("Removing slime..."); + slime.remove(); + } + else + { + slime.setSize(-1); + } + }); + } + } + + @EventHandler + public void save(UpdateEvent event) + { + if (!UtilTime.elapsed(_initializedTime, 5500) || UtilServer.getPlayers().length == 0) + { + return; + } + + if (event.getType() == UpdateType.SLOW) + { + _outpostManager.saveOutposts(); + saveSiegeWeapons(); + + for (Entity entity : Spawn.getSpawnWorld().getEntitiesByClass(ArmorStand.class)) + { + boolean part = false; + + for (SiegeWeapon weapon : LiveSiegeWeapons.values()) + { + if (weapon.isPartOf(entity.getUniqueId())) + { + part = true; + break; + } + } + + if (!part) + for (SiegeWeapon weapon : UnsyncedSiegeWeapons.values()) + { + if (weapon.isPartOf(entity.getUniqueId())) + { + part = true; + break; + } + } + + if (!part) + { + if (((ArmorStand) entity).getHelmet() != null && ((ArmorStand) entity).getHelmet().getType().equals(Material.SPONGE)) + { + System.out.println("Removing armor stand"); + entity.remove(); + } + + if (entity.getPassenger() != null && entity.getPassenger() instanceof Slime && entity.getPassenger().getPassenger() instanceof Slime) + { + System.out.println("Removing armostand + children"); + entity.getPassenger().getPassenger().remove(); + entity.getPassenger().remove(); + entity.remove(); + } + } + } + } + } + + private void saveSiegeWeapons() + { + for (final SiegeWeapon weapon : LiveSiegeWeapons.values()) + { + final SiegeWeaponToken token = weapon.toToken(); + + if (UnsyncedSiegeWeapons.containsKey(Integer.valueOf(token.UniqueId))) + continue; + + runAsync(() -> { + _repository.updateWeapon(token); + }); + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) + { + if (event.getItemInHand().isSimilar(Cannon.CANNON_ITEM)) + { + event.setCancelled(true); + + if (trySpawnCannon(event.getPlayer(), event.getBlock().getLocation())) + { + event.getPlayer().setItemInHand(UtilInv.decrement(event.getPlayer().getItemInHand())); + return; + } + } + +// if (event.getItemInHand().isSimilar(Catapult.CATAPULT_ITEM)) +// { +// event.setCancelled(true); +// +// if (trySpawnCatapult(event.getPlayer(), event.getBlock().getLocation())) +// { +// event.getPlayer().setItemInHand(UtilInv.decrement(event.getPlayer().getItemInHand())); +// return; +// } +// } + } + + public boolean trySpawnCannon(Player player, Location location) + { +// if (_clansManager.getNetherManager().isInNether(player)) +// { +// _clansManager.message(player, "You are not allowed to place this in " + F.clansNether("The Nether") + "."); +// +// return false; +// } + + if (!_clansManager.isInClan(player)) + { + UtilPlayer.message(player, F.main("Clans", "You must be in a Clan to place a Cannon.")); + return false; + } + + if (_clansManager.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot place a Cannon whilst protected from pvp.")); + return false; + } + + ClanTerritory claim = _clansManager.getClanUtility().getClaim(location); + + if (claim != null && !claim.Owner.equals(_clansManager.getClan(player).getName())) + { + UtilPlayer.message(player, F.main("Clans", "You must place a Cannon in the Wilderness or your own Territory.")); + return false; + } + + spawnCannon(player, location); + + return true; + } + + public Cannon spawnCannon(Player player, Location location) + { + return spawnCannon(player, location, true); + } + + public Cannon spawnCannon(Player player, Location location, boolean syncWithDb) + { + Cannon cannon = new Cannon(location, _clansManager.getClan(player), this, syncWithDb); + + UnsyncedSiegeWeapons.put(Integer.valueOf(cannon.getUniqueId()), cannon); + + return cannon; + } + + public void dead(SiegeWeapon weapon) + { + LiveSiegeWeapons.remove(Integer.valueOf(weapon.getUniqueId())); + SiegeWeapon unsynced = UnsyncedSiegeWeapons.remove(Integer.valueOf(weapon.getUniqueId())); + + if (unsynced == null) + _repository.deleteWeapon(weapon.getUniqueId()); + } + + public OutpostManager getOutpostManager() + { + return _outpostManager; + } + + public Gson getGson() + { + return _gson; + } + + public ClansManager getClansManager() + { + return _clansManager; + } + + public int randomId() + { + /** + * prevents id from ever being 0 (which is used internally as NULL) + */ + return 1 + UtilMath.random.nextInt(Integer.MAX_VALUE - 1); + } + + public SiegeWeaponRepository getRepository() + { + return _repository; + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/LoadSiegeWeaponEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/LoadSiegeWeaponEvent.java new file mode 100644 index 000000000..92fd2d1e5 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/LoadSiegeWeaponEvent.java @@ -0,0 +1,53 @@ +package mineplex.game.clans.clans.siege.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; + +public class LoadSiegeWeaponEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private SiegeWeapon _weapon; + + private boolean _cancelled; + + public LoadSiegeWeaponEvent(Player player, SiegeWeapon weapon) + { + _player = player; + _weapon = weapon; + } + + public SiegeWeapon getWeapon() + { + return _weapon; + } + + public Player getPlayer() + { + return _player; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/MountSiegeWeaponEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/MountSiegeWeaponEvent.java new file mode 100644 index 000000000..bf6d46166 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/MountSiegeWeaponEvent.java @@ -0,0 +1,53 @@ +package mineplex.game.clans.clans.siege.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; + +public class MountSiegeWeaponEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private Player _player; + private SiegeWeapon _weapon; + + private boolean _cancelled; + + public MountSiegeWeaponEvent(Player player, SiegeWeapon weapon) + { + _player = player; + _weapon = weapon; + } + + public SiegeWeapon getWeapon() + { + return _weapon; + } + + public Player getPlayer() + { + return _player; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/SiegeWeaponExplodeEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/SiegeWeaponExplodeEvent.java new file mode 100644 index 000000000..c0bec7a14 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/events/SiegeWeaponExplodeEvent.java @@ -0,0 +1,53 @@ +package mineplex.game.clans.clans.siege.events; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; +import mineplex.game.clans.clans.siege.weapon.projectile.WeaponProjectile; + +public class SiegeWeaponExplodeEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private SiegeWeapon _weapon; + private WeaponProjectile _projectile; + + private boolean _cancelled; + + public SiegeWeaponExplodeEvent(SiegeWeapon weapon, WeaponProjectile projectile) + { + _weapon = weapon; + _projectile = projectile; + } + + public SiegeWeapon getWeapon() + { + return _weapon; + } + + public WeaponProjectile getProjectile() + { + return _projectile; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/Outpost.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/Outpost.java new file mode 100644 index 000000000..6f2a19718 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/Outpost.java @@ -0,0 +1,646 @@ +package mineplex.game.clans.clans.siege.outpost; + +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.ColorFader; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.common.util.F; +import mineplex.core.common.util.LoopIterator; +import mineplex.core.common.util.RGBData; +import mineplex.core.common.util.UtilAction; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilColor; +import mineplex.core.common.util.UtilEvent; +import mineplex.core.common.util.UtilEvent.ActionType; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTrig; +import mineplex.core.hologram.Hologram; +import mineplex.core.hologram.HologramInteraction; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.event.ClansWaterPlaceEvent; +import mineplex.game.clans.clans.event.IronDoorOpenEvent; +import mineplex.game.clans.clans.event.PlayerClaimTerritoryEvent; +import mineplex.game.clans.clans.siege.events.SiegeWeaponExplodeEvent; +import mineplex.game.clans.clans.siege.outpost.build.OutpostBlock; +import mineplex.game.clans.clans.siege.repository.tokens.OutpostToken; +import mineplex.game.clans.core.repository.ClanTerritory; +import net.minecraft.server.v1_8_R3.AxisAlignedBB; + +public class Outpost implements Listener +{ + protected static final long MAX_LIFETIME = 30 * 60 * 1000; // 30 minutes + public static final ItemStack OUTPOST_ITEM = new ItemBuilder(Material.BEACON, 1).setRawTitle(C.Reset + C.cBlue + "Outpost").build(); + + public static final long PREP_TIME = 2 * 60 * 1000; + + private OutpostManager _outpostManager; + + private final int _uniqueId; + + private ClanInfo _ownerClan; + + private Location _startCorner; + private Location _origin; + private Location _endCorner; + + private Location _forceFieldStart; + private Location _forceFieldEnd; + + private Location _core; + + private LinkedHashMap _blocks; + private LinkedHashMap _buildQueue = new LinkedHashMap<>(); + + protected OutpostType _type; + private OutpostState _state; + + private Hologram _preHologram; + private Hologram _preHologram2; + + private LoopIterator _circleStages; + private LoopIterator _reverseCircleStages; + + private ColorFader _fader = new ColorFader(30, UtilColor.hexToRgb(0x00A296), UtilColor.hexToRgb(0x29E6B6)); + + private long _timeSpawned; + + public ClanInfo _againstClan; + + private Hologram _lifetimeLeft; + + public Outpost(OutpostManager outpostManager, OutpostToken token) + { + _outpostManager = outpostManager; + + _uniqueId = token.UniqueId; + + _ownerClan = token.OwnerClan; + + _startCorner = token.Origin.clone().subtract(token.Type._size, 1.1, token.Type._size); + _endCorner = token.Origin.clone().add(token.Type._size + .9, token.Type._ySize - 1, token.Type._size + .9); + + _forceFieldStart = _startCorner.clone().subtract(4, 0, 4); + _forceFieldEnd = _endCorner.clone().add(4.5, 0, 4.5); + + _origin = token.Origin.clone(); + + _type = token.Type; + + _timeSpawned = token.TimeSpawned; + + _core = _type.getCoreLocation(_origin); + + _preHologram = new Hologram(outpostManager.getClansManager().getHologramManager(), _origin.clone().add(0.5, 2.3, 0.5), F.elem(_ownerClan.getName()) + C.cWhite + "'s Outpost block (Right-Click to activate)"); + _preHologram2 = new Hologram(outpostManager.getClansManager().getHologramManager(), _origin.clone().add(0.5, 3, 0.5), "Despawning: " + UtilText.getProgress(null, 0, null, true)); + + _lifetimeLeft = new Hologram(outpostManager.getClansManager().getHologramManager(), _origin.clone().add(0.5, 1.5, 0.5), "Despawning in " + F.time(UtilTime.MakeStr(MAX_LIFETIME))); + _lifetimeLeft.setInteraction(new HologramInteraction() + { + public void onClick(Player player, ClickType clickType) + { + if (_ownerClan.isMember(player) || _state != OutpostState.LIVE) + return; + + if (clickType == ClickType.LEFT || clickType == ClickType.SHIFT_LEFT) + kill(); + } + + }); + + + if (token.OutpostState == OutpostState.AWAITING) + { + _preHologram.start(); + _preHologram2.start(); + } + + _blocks = _type.createBuildQueue(_origin, _ownerClan.Clans); + + _state = token.OutpostState; + + _circleStages = new LoopIterator(UtilTrig.GetCirclePoints(new Vector(0., 0., 0.), 40, .6d)); + + List reverse = UtilTrig.GetCirclePoints(new Vector(0., 0., 0.), 40, .6d); + Collections.reverse(reverse); + _reverseCircleStages = new LoopIterator(reverse); + + } + + public Outpost(OutpostManager outpostManager, ClanInfo clan, Location location, OutpostType type) + { + _outpostManager = outpostManager; + + _uniqueId = outpostManager.getSiegeManager().randomId(); + + _ownerClan = clan; + + _startCorner = location.clone().subtract(type._size, 1.1, type._size); + _endCorner = location.clone().add(type._size + .9, type._ySize - 1, type._size + .9); + + _forceFieldStart = _startCorner.clone().subtract(4, 0, 4); + _forceFieldEnd = _endCorner.clone().add(4.5, 0, 4.5); + + _origin = location.clone(); + + _type = type; + + _timeSpawned = System.currentTimeMillis(); + + _core = _type.getCoreLocation(_origin); + + _preHologram = new Hologram(_ownerClan.Clans.getHologramManager(), _origin.clone().add(0.5, 2.3, 0.5), F.elem(_ownerClan.getName()) + C.cWhite + "'s Outpost block (Right-Click to activate)"); + _preHologram2 = new Hologram(_ownerClan.Clans.getHologramManager(), _origin.clone().add(0.5, 3, 0.5), "Despawning: " + UtilText.getProgress(null, 0, null, true)); + + _preHologram.start(); + _preHologram2.start(); + + _state = OutpostState.AWAITING; + + _outpostManager.getRepository().insertOutpost(toToken()); + + _circleStages = new LoopIterator(UtilTrig.GetCirclePoints(new Vector(0., 0., 0.), 40, .6d)); + + List reverse = UtilTrig.GetCirclePoints(new Vector(0., 0., 0.), 40, .6d); + Collections.reverse(reverse); + _reverseCircleStages = new LoopIterator(reverse); + + UtilServer.RegisterEvents(this); + + _lifetimeLeft = new Hologram(outpostManager.getClansManager().getHologramManager(), _origin.clone().add(0.5, 1.5, 0.5), "Despawning in " + F.time(UtilTime.MakeStr(MAX_LIFETIME))); + _lifetimeLeft.setInteraction(new HologramInteraction() + { + public void onClick(Player player, ClickType clickType) + { + if (_ownerClan.isMember(player) || _state != OutpostState.LIVE) + return; + + if (clickType == ClickType.LEFT || clickType == ClickType.SHIFT_LEFT) + kill(); + } + }); + } + + private void cleanup() + { + _blocks = null; + + if (_preHologram != null) _preHologram.stop(); + if (_preHologram2 != null) _preHologram2.stop(); + + _preHologram = null; + _preHologram2 = null; + + _state = OutpostState.DEAD; + + _outpostManager.queueForRemoval(_ownerClan.getName()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInteract(PlayerInteractEvent event) + { + if (getState() == OutpostState.LIVE) + { + do + { + if (event.getClickedBlock() == null) + break; + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + break; + + if (!UtilItem.isDoor(event.getClickedBlock().getType())) + break; + + if (_ownerClan.isMember(event.getPlayer())) + break; + + if (UtilAlg.inBoundingBox(event.getClickedBlock().getLocation(), _startCorner.clone().subtract(.5, 0, .5), _endCorner)) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You cannot open the doors of this Outpost.")); + event.setCancelled(true); + return; + } + } while(false); + } + + if (getState() != OutpostState.AWAITING) + return; + + if (!UtilEvent.isAction(event, ActionType.R_BLOCK)) + return; + + if (getLifetime() <= 2000) + return; + + + if(_outpostManager.getClansManager().hasTimer(event.getPlayer())) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You cannot activate an Outpost whilst protected from PvP.")); + return; + } + + if (!_ownerClan.equals(_ownerClan.Clans.getClanUtility().getClanByPlayer(event.getPlayer()))) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "This is not yours to activate!")); + return; + } + + if (event.getClickedBlock() != null && _origin.equals(event.getClickedBlock().getLocation())) + { + if (event.getClickedBlock().getType().equals(Material.BEACON)) + { + _origin.getBlock().setType(Material.AIR); + beginConstruction(); + } + } + } + + @EventHandler + public void onBlockDamage(BlockDamageEvent event) + { + if (event.getBlock().getLocation().equals(_core) && getState() == OutpostState.LIVE) + { + + if(_outpostManager.getClansManager().hasTimer(event.getPlayer())) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You cannot destroy an Outpost whilst protected from PvP.")); + event.setCancelled(true); + return; + } + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You have destroyed " + F.elem(_ownerClan.getName()) + "'s Outpost!")); + + _core.getBlock().setType(Material.AIR); + + _ownerClan.inform("Your Outpost has been destroyed!", null); + UtilTextMiddle.display("Siege", "Your Outpost has been destroyed", 20, 100, 20, _ownerClan.getOnlinePlayersArray()); + + if (getState() == OutpostState.AWAITING) + cleanup(); + else + kill(); + + event.setCancelled(true); + } + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent event) + { + if (getState() == OutpostState.AWAITING && event.getBlock().getLocation().equals(_origin)) + { + _origin.getBlock().setType(Material.AIR); + _origin.getWorld().dropItem(_origin, OUTPOST_ITEM); + _ownerClan.inform("Your Outpost block has been destroyed.", null); + cleanup(); + event.setCancelled(true); + return; + } + + if (event.getBlock().getLocation().equals(_core) && getState() == OutpostState.LIVE) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You have destroyed " + F.elem(_ownerClan.getName()) + "'s Outpost!")); + + _core.getBlock().setType(Material.AIR); + + _ownerClan.inform("Your Outpost has been destroyed!", null); + UtilTextMiddle.display("Siege", "Your Outpost has been destroyed", 20, 100, 20, _ownerClan.getOnlinePlayersArray()); + + if (getState() == OutpostState.AWAITING) + cleanup(); + else + kill(); + + event.setCancelled(true); + return; + } + + if (UtilAlg.inBoundingBox(event.getBlock().getLocation(), _startCorner.clone().subtract(.5, 0, .5), _endCorner)) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not break blocks in Outposts.")); + event.setCancelled(true); + } + } + + @EventHandler + public void onWaterPlace(ClansWaterPlaceEvent event) + { + if (UtilAlg.inBoundingBox(event.getBlock().getLocation(), _startCorner.clone().subtract(.5, 0, .5), _endCorner)) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not place water in Outposts.")); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onBlockPlace(BlockPlaceEvent event) + { + if (event.isCancelled()) + return; + + if (UtilAlg.inBoundingBox(event.getBlock().getLocation(), _startCorner.clone().subtract(.5, 0, .5), _endCorner)) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not place blocks in Outposts.")); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void claimTerritory(PlayerClaimTerritoryEvent event) + { + if (UtilMath.offset2d(event.getClaimedChunk().getBlock(8, 0, 8).getLocation(), _origin) < 32) + { + UtilPlayer.message(event.getClaimer(), F.main("Clans", "You may not claim this close to an Outpost.")); + event.setCancelled(true); + } + } + + protected void update() + { + if (_state == OutpostState.AWAITING) + { + if (getLifetime() > 60000) + { + _origin.getBlock().setType(Material.AIR); + _ownerClan.inform("You have lost your Outpost block, as no one activated it fast enough!", null); + cleanup(); + return; + } + + _preHologram2.setText(UtilText.getProgress(null, UtilMath.clamp(getLifetime(), 0., 60000.) / 60000., null, true)); + + RGBData color = UtilColor.RgbLightBlue; + + for (int x = -_type._size; x <= _type._size; x++) + for (int z = -_type._size; z <= _type._size; z++) + if (x == -_type._size || x == _type._size || z == -_type._size || z == _type._size) + UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, UtilBlock.getHighest(_origin.getWorld(), _origin.clone().add(x + .5, .1, z + .5).getBlockX(), _origin.clone().add(x + .5, .1, z + .5).getBlockZ()).getLocation().add(0.5, 0, 0.5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1f, 0, ViewDist.NORMAL); + + return; + } + + if (_lifetimeLeft != null) + _lifetimeLeft.setText("Despawning in " + F.time(UtilTime.MakeStr(MAX_LIFETIME - (System.currentTimeMillis() - _timeSpawned)))); + + if (_state == OutpostState.CONSTRUCTING) + { + if (_buildQueue.isEmpty()) + { + _state = OutpostState.LIVE; + + return; + } + else + { + Iterator iterator = _buildQueue.keySet().iterator(); + + if (iterator.hasNext()) + _buildQueue.remove(iterator.next()).set(); + } + + // Forcefield + RGBData color = UtilColor.RgbLightBlue; + + for (int x = _forceFieldStart.getBlockX(); x <= _forceFieldEnd.getBlockX(); x++) + for (int z = _forceFieldStart.getBlockZ(); z <= _forceFieldEnd.getBlockZ(); z++) + if (x == _forceFieldStart.getBlockX() || x == _forceFieldEnd.getBlockX() || z == _forceFieldStart.getBlockZ() || z == _forceFieldEnd.getBlockZ()) + UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, new Location(_core.getWorld(), x + .5, UtilBlock.getHighest(_core.getWorld(), x, z).getY() + .15, z + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1f, 0, ViewDist.NORMAL); + } + + RGBData next = _fader.next(); + + { + RGBData color = _state == OutpostState.LIVE ? next : UtilColor.RgbRed; + + Vector nextCircleStage = _circleStages.next(); + + double circleX = nextCircleStage.getX(); + double circleZ = nextCircleStage.getZ(); + + UtilParticle.PlayParticleToAll(ParticleType.MOB_SPELL, _core.clone().add(circleX + .5, 1.1d, circleZ + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1.f, 0, ViewDist.NORMAL); + } + + { + RGBData color = _state == OutpostState.LIVE ? next : UtilColor.RgbRed; + + Vector nextCircleStage = _reverseCircleStages.next(); + + double circleX = nextCircleStage.getX(); + double circleZ = nextCircleStage.getZ(); + + UtilParticle.PlayParticleToAll(ParticleType.MOB_SPELL, _core.clone().add(circleX + .5, 1.1d, circleZ + .5), new Vector(color.getRed(), color.getGreen(), color.getBlue()), 1.f, 0, ViewDist.NORMAL); + } + } + + @EventHandler + public void forcefield(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST || getState() != OutpostState.CONSTRUCTING) + return; + + UtilServer.getPlayersCollection().stream() + .filter(player -> !_ownerClan.isMember(player)) + .filter(player -> UtilAlg.inBoundingBox(player.getLocation(), _forceFieldStart, _forceFieldEnd)) + .forEach(player -> { + UtilAction.velocity(player, UtilAlg.getTrajectory2d(_core, player.getLocation()), .77, true, 0.8, 0, 1.1, true); + UtilPlayer.message(player, F.main("Clans", "This Outpost is still under construction!")); + player.playSound(player.getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); + }); + } + + public void beginConstruction() + { + // Cleanup pre-Outpost stuff + _preHologram.stop(); + _preHologram2.stop(); + + _preHologram = null; + _preHologram = null; + + _lifetimeLeft.start(); + + _state = OutpostState.CONSTRUCTING; + _blocks = new LinkedHashMap<>(_buildQueue = _type.createBuildQueue(_origin, _ownerClan.Clans)); + + _ownerClan.inform("Siege", "Your Outpost is now being constructed.", null); + + //Inform nearby Clans + for (int chunkX = -3; chunkX < 3; chunkX++) + for (int chunkZ = -3; chunkZ < 3; chunkZ++) + { + ClanTerritory territory = _ownerClan.Clans.getClanUtility().getClaim(_origin.getWorld().getChunkAt(_origin.getChunk().getX() + chunkX, _origin.getChunk().getZ() + chunkZ)); + + if (territory != null && _outpostManager.getClansManager().getBlacklist().allowed(territory.Owner)) + { + ClanInfo clan = _ownerClan.Clans.getClanUtility().getClanByClanName(territory.Owner); + + clan.inform("A siege has begun near your territory!", null); + UtilTextMiddle.display("Siege", "A Siege has been declared on your Clan!", 20, 100, 20, clan.getOnlinePlayersArray()); + } + } + } + + public void kill() + { + _state = OutpostState.DESTRUCTING; + + EnclosedObject wait = new EnclosedObject<>(0); + + _blocks.values().stream().filter(block -> UtilMath.random.nextBoolean() && UtilMath.random.nextBoolean()).filter(block -> UtilMath.random.nextBoolean()).limit(13).forEach(block -> + _outpostManager.runSyncLater(() -> { + UtilParticle.PlayParticleToAll(ParticleType.HUGE_EXPLOSION, block.getLocation(), new Vector(0,0,0), 1f, 1, ViewDist.MAX); + _origin.getWorld().playSound(block.getLocation(), Sound.EXPLODE, 1.0f, 1.0f); + }, wait.Set(Integer.valueOf(wait.Get().intValue() + 4 + UtilMath.random.nextInt(4))).longValue()) + ); + + _outpostManager.runSyncLater(() -> { + _blocks.values().stream().forEach(OutpostBlock::restore); + }, wait.Get().intValue() + 5L); + + _outpostManager.runSyncLater(() -> { + _blocks.values().stream().forEach(block -> { + Material mat = Material.getMaterial(block.getId()); + + if (UtilItem.isTranslucent(mat) || UtilMath.random.nextBoolean()) + { + block.restore(); + return; + } + + FallingBlock fall = block.getLocation().getWorld().spawnFallingBlock(block.getLocation(), block.getId(), block.getData()); + fall.setDropItem(false); + Vector vec = UtilAlg.getTrajectory(fall.getLocation(), getExactMiddle()); + + UtilAction.velocity(fall, vec, 1, false, 0, 0.6, 10, false); + + fall.setMetadata("ClansOutpost", new FixedMetadataValue(_ownerClan.Clans.getPlugin(), _ownerClan.getName())); + + block.restore(); + }); + + cleanup(); + }, wait.Get().intValue() + 6L); + + if (_lifetimeLeft != null) _lifetimeLeft.stop(); + + _lifetimeLeft = null; + + _ownerClan.inform("Your Clan's Outpost has been destroyed.", null); + } + + @EventHandler + public void doorOpen(IronDoorOpenEvent event) + { + if (!UtilAlg.inBoundingBox(event.getBlock().getLocation(), _startCorner.clone().subtract(.5, 0, .5), _endCorner)) + { + return; + } + + if (_ownerClan.isMember(event.getPlayer())) + { + return; + } + + event.setCancelled(true); + } + + @EventHandler + public void onSiegeWeaponExplode(SiegeWeaponExplodeEvent event) + { + if (UtilAlg.inBoundingBox(event.getProjectile().getLocation(), _startCorner.clone().subtract(2, 2, 2), _endCorner.clone().add(2, 2, 2))) + { + if (getLifetime() < 15 * 60 * 1000) + { + event.setCancelled(true); + } + } + } + + public ClanInfo getOwner() + { + return _ownerClan; + } + + public long getLifetime() + { + return System.currentTimeMillis() - _timeSpawned; + } + + public AxisAlignedBB getBounds() + { + return UtilAlg.toBoundingBox(_startCorner, _endCorner); + } + + public Location getExactMiddle() + { + return UtilAlg.getMidpoint(_startCorner, _endCorner); + } + + public OutpostState getState() + { + return _state; + } + + public ClanInfo getAgainst() + { + return _againstClan; + } + + public int getUniqueId() + { + return _uniqueId; + } + + public OutpostToken toToken() + { + OutpostToken token = new OutpostToken(); + + token.UniqueId = _uniqueId; + token.Origin = _origin; + token.Type = _type; + token.OwnerClan = _ownerClan; + token.TimeSpawned = _timeSpawned; + token.OutpostState = _state; + + return token; + } + + public Location getCoreLocation() + { + return _core; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostManager.java new file mode 100644 index 000000000..c2f382bf4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostManager.java @@ -0,0 +1,314 @@ +package mineplex.game.clans.clans.siege.outpost; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; + +import com.google.common.collect.Lists; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.F; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.PlayerClaimTerritoryEvent; +import mineplex.game.clans.clans.siege.SiegeManager; +import mineplex.game.clans.clans.siege.repository.OutpostRepository; +import mineplex.game.clans.clans.siege.repository.tokens.OutpostToken; +import mineplex.game.clans.core.repository.ClanTerritory; + +public class OutpostManager extends MiniPlugin +{ + private ClansManager _clansManager; + + private NautHashMap _outposts = new NautHashMap<>(); + private NautHashMap _idToOutpost = new NautHashMap<>(); + + private List _removalQueue; + + private SiegeManager _siegeManager; + + private OutpostRepository _repository; + + public OutpostManager(ClansManager clansManager, SiegeManager siegeManager) + { + super("Outpost Manager", clansManager.getPlugin()); + + _siegeManager = siegeManager; + + _clansManager = clansManager; + + _repository = new OutpostRepository(clansManager.getPlugin(), this); + + _removalQueue = new ArrayList<>(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlaceBlock(BlockPlaceEvent event) + { + if (event.getItemInHand().isSimilar(Outpost.OUTPOST_ITEM)) + if (!spawnOutpost(event.getPlayer(), event.getBlock().getLocation(), OutpostType.MK_III)) + event.setCancelled(true); + } + + public boolean spawnOutpost(Player player, Location location, OutpostType type) + { +// if (_clansManager.getNetherManager().isInNether(player)) +// { +// _clansManager.message(player, "You are not allowed to place this in " + F.clansNether("The Nether") + "."); +// +// return false; +// } + + if (!_clansManager.isInClan(player)) + { + UtilPlayer.message(player, F.main("Clans", "You must be in a Clan to place an Outpost.")); + return false; + } + + if(_clansManager.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You can't place an Outpost whilst protected from PvP.")); + return false; + } + + if (location.getBlockY() < 30) + { + UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost this deep.")); + return false; + } + + ClanInfo clan = _clansManager.getClan(player); + + if (UtilItem.isBoundless(location.clone().subtract(0, 1, 0).getBlock().getType())) + { + UtilPlayer.message(player, F.main("Clans", "An Outpost must not be placed floating.")); + return false; + } + + if (Get(clan) != null) + { + UtilPlayer.message(player, F.main("Clans", "Your Clan already has an outpost.")); + return false; + } + + if (_clansManager.getClanUtility().getClaim(location) != null) + { + UtilPlayer.message(player, F.main("Clans", "An Outpost must be placed in the Wilderness.")); + return false; + } + + for (Outpost outpost : _outposts.values()) + { + if (UtilMath.offset(location, outpost.getExactMiddle()) < type._size + 8) + { + UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost near other Outposts.")); + return false; + } + } + + for (int x = -2; x < 2; x++) + for (int z = -2; z < 2; z++) + { + Chunk chunk = location.getWorld().getChunkAt(location.getChunk().getX() + x, location.getChunk().getZ() + z); + + ClanTerritory claim = _clansManager.getClanUtility().getClaim(chunk); + + if (claim != null) + { + if (!claim.Owner.equals(clan.getName()) && _clansManager.getBlacklist().allowed(claim.Owner)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost this close to a Clan's Territory.")); + return false; + } + } + } + + boolean gut = false; + + for (int x = -6; x < 6; x++) + for (int z = -6; z < 6; z++) + { + Chunk chunk = location.getWorld().getChunkAt(location.getChunk().getX() + x, location.getChunk().getZ() + z); + + ClanTerritory claim = _clansManager.getClanUtility().getClaim(chunk); + + if (claim != null) + { + System.out.println(claim.Owner + ", " + clan.getName()); + + if (!claim.Owner.equals(clan.getName()) && _clansManager.getBlacklist().allowed(claim.Owner)) + { + gut = true; /* das ist gut!!! */ + break; + } + } + } + + /* das ist schlecht */ + if (!gut) + { + UtilPlayer.message(player, F.main("Clans", "An Outpost must be placed near a rival Clan's Territory.")); + return false; + } + + for (int x = -type._size; x < type._size; x++) + for (int y = -1; y < type._ySize; y++) + for (int z = -type._size; z < type._size; z++) + { + Location loc = location.clone().add(x, y, z); + + if (_clansManager.getClanUtility().isClaimed(loc)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot place an Outpost where it may intersect with claimed territory.")); + return false; + } + } + + _outposts.put(clan.getName(), new Outpost(this, clan, location, type)); + _idToOutpost.put(Integer.valueOf(_outposts.get(clan.getName()).getUniqueId()), _outposts.get(clan.getName())); + + return true; + } + + @EventHandler + public void onBlockFall(EntityChangeBlockEvent event) + { + if (event.getEntity().hasMetadata("ClansOutpost")) + event.setCancelled(true); + } + + @EventHandler + public void onClaim(PlayerClaimTerritoryEvent event) + { + for (Outpost outpost : _outposts.values()) + { + if (outpost.getBounds().b(UtilAlg.toBoundingBox(event.getClaimedChunk().getBlock(0, 0, 0).getLocation(), event.getClaimedChunk().getBlock(15, 254, 15).getLocation()))) + { + event.setCancelled(true); + UtilPlayer.message(event.getClaimer(), F.main("Clans", "You cannot claim this territory as it overlaps with " + F.elem(outpost.getOwner().getName()) + "'s Outpost.")); + break; + } + } + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() == UpdateType.TICK) + _outposts.values() + .stream() + .forEach(Outpost::update); + + if (event.getType() == UpdateType.FASTER) + if (!_removalQueue.isEmpty()) + HandlerList.unregisterAll(_idToOutpost.remove(Integer.valueOf(_outposts.remove(_removalQueue.remove(0)).getUniqueId()))); + + if (event.getType() == UpdateType.TWOSEC) + _outposts.values() + .stream() + .filter(outpost -> outpost.getState() == OutpostState.LIVE && outpost.getLifetime() > Outpost.MAX_LIFETIME) + .forEach(Outpost::kill); + } + + public Outpost Get(ClanInfo clan) + { + return clan == null ? null : _outposts.get(clan.getName().toLowerCase()); + } + + public void queueForRemoval(String name) + { + _removalQueue.add(name); + } + + public SiegeManager getSiegeManager() + { + return _siegeManager; + } + + public List getOutposts() + { + return Lists.newArrayList(_outposts.values()); + } + + public Outpost Get(int outpostId) + { + return _idToOutpost.get(Integer.valueOf(outpostId)); + } + + public ClansManager getClansManager() + { + return _clansManager; + } + + public void loadOutposts() + { + System.out.println("[OUTPOSTS] LOADING OUTPOSTS FROM DATABASE"); + + _repository.getOutpostsByServer(_clansManager.getServerId(), tokens -> + tokens.forEach(token -> { + Outpost outpost = new Outpost(this, token); + + if ((System.currentTimeMillis() - token.TimeSpawned) > Outpost.MAX_LIFETIME) + { + System.out.println("[OUTPOSTS] SKIPPING & REMOVING OUTPOST [" + token.UniqueId + "] BECAUSE OF OLD AGE"); + + _repository.deleteOutpost(token.UniqueId); + outpost.kill(); + + return; + } + + System.out.println("[OUTPOSTS] INITIALIZED OUTPOST FROM DATABASE SAVE"); + + _outposts.put(token.OwnerClan.getName(), outpost); + }) + ); + } + + public void saveOutposts() + { + final Stack queue = new Stack<>(); + + _outposts.values().forEach(outpost -> { + final OutpostToken token = outpost.toToken(); + + queue.push(() -> _repository.updateOutpost(token)); + }); + + runAsync(() -> { + while (!queue.isEmpty()) + queue.pop().run(); + + _repository.getOutpostsByServer(_clansManager.getServerId(), tokens -> { + tokens.forEach(token -> { + if (!_idToOutpost.containsKey(Integer.valueOf(token.UniqueId))) + { + System.out.println("[OUTPOSTS] OUTPOST [" + token.UniqueId + "] NO LONGER EXISTS, DELETING"); + _repository.deleteOutpost(token.UniqueId); + } + }); + }); + }); + } + + public OutpostRepository getRepository() + { + return _repository; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostState.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostState.java new file mode 100644 index 000000000..8d37671fa --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostState.java @@ -0,0 +1,38 @@ +package mineplex.game.clans.clans.siege.outpost; + +public enum OutpostState +{ + /** + * this much space between them so that there is some room for any potential new states. + */ + AWAITING(10), + CONSTRUCTING(20), + LIVE(30), + DESTRUCTING(40), + DEAD(50); + + private byte _id; + + OutpostState(int id) + { + _id = (byte) id; + } + + public static OutpostState ById(byte id) + { + for (OutpostState state : values()) + { + if (state._id == id) + { + return state; + } + } + + return null; + } + + public byte getId() + { + return _id; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostType.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostType.java similarity index 76% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostType.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostType.java index d7e04055b..134e6b000 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/outpost/OutpostType.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/OutpostType.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.clans.outpost; +package mineplex.game.clans.clans.siege.outpost; import java.io.File; import java.io.FileInputStream; @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; @@ -13,11 +14,13 @@ import mineplex.core.common.block.schematic.Schematic; import mineplex.core.common.block.schematic.UtilSchematic; import mineplex.core.common.util.UtilWorld; import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.siege.outpost.build.OutpostBlock; +import mineplex.game.clans.clans.siege.outpost.build.OutpostBlockBanner; import net.minecraft.server.v1_8_R3.NBTTagCompound; public enum OutpostType { - ORIGINAL_CLANS(3, 6) { + MK_I(1, 3, 6) { public LinkedHashMap createBuildQueue(Location location, ClansManager clans) { LinkedHashMap build = new LinkedHashMap<>(); @@ -228,7 +231,7 @@ public enum OutpostType return location.clone().subtract(0, 1, 0); } }, - MK2(5, 25) { + MK_II(2, 5, 25) { public LinkedHashMap createBuildQueue(Location location, ClansManager clans) { try @@ -236,7 +239,6 @@ public enum OutpostType LinkedHashMap build = new LinkedHashMap<>(); File file = new File("schematic" + File.separator + "outpost_mk_II.schematic"); - System.out.println(file.getAbsolutePath()); Schematic schematic = UtilSchematic.loadSchematic(file); for (int y = 0; y < schematic.getHeight(); y++) @@ -284,6 +286,71 @@ public enum OutpostType return list; } + public Location getCoreLocation(Location location) + { + return location.clone().subtract(0, 1, 0); + } + }, + MK_III(3, 5, 25) { + public LinkedHashMap createBuildQueue(Location location, ClansManager clans) + { + try + { + LinkedHashMap build = new LinkedHashMap<>(); + + File file = new File("schematic" + File.separator + "outpost_mk_III.schematic"); + Schematic schematic = UtilSchematic.loadSchematic(file); + + for (int y = 0; y < schematic.getHeight(); y++) + { + for (int x = 0; x < schematic.getWidth(); x++) + { + for (int z = 0; z < schematic.getLength(); z++) + { + int relativeX = -(schematic.getWidth() / 2) + x; + int relativeZ = -(schematic.getLength() / 2) + z; + + Location loc = location.clone().add(relativeX, y - 1, relativeZ); + + if (schematic.getBlock(x, y, z) == 0 && loc.getBlock().getType() == Material.AIR) + { + continue; + } + + if (Material.getMaterial(schematic.getBlock(x, y, z)).name().contains("BANNER")) + { + build.put(UtilWorld.locToStr(loc), new OutpostBlockBanner(build, loc, schematic.getBlock(x, y, z), schematic.getData(x, y, z), DyeColor.RED)); + } + else + build.put(UtilWorld.locToStr(loc), new OutpostBlock(build, loc, schematic.getBlock(x, y, z), schematic.getData(x, y, z))); + } + } + } + + //Core + build.put(UtilWorld.locToStr(getCoreLocation(location)), new OutpostBlock(build, getCoreLocation(location), Material.DIAMOND_BLOCK.getId(), (byte)0)); + + return build; + } + catch(Exception e) + { + e.printStackTrace(); + return null; + } + } + + public List getWallLocations(Location middle) + { + List list = new ArrayList<>(); + + list.add(middle.clone().add(_size / 2, 0, 0).add(1, 0, 0)); + list.add(middle.clone().add(_size / 2, 0, -(_size / 2)).add(1, 0, -1)); + list.add(middle.clone().add(-(_size / 2), 0, -(_size / 2)).add(-1, 0, -1)); + list.add(middle.clone().add(-(_size / 2), 0, 0).add(-1, 0, 0)); + + return list; + } + public Location getCoreLocation(Location location) { return location.clone().subtract(0, 1, 0); @@ -293,10 +360,18 @@ public enum OutpostType protected int _size; protected int _ySize; - OutpostType(int size, int ySize) + private int _id; + + OutpostType(int id, int size, int ySize) { _size = size; _ySize = ySize; + _id = id; + } + + public int getId() + { + return _id; } public abstract LinkedHashMap createBuildQueue(Location location, ClansManager clans); @@ -304,4 +379,17 @@ public enum OutpostType public abstract Location getCoreLocation(Location location); public abstract List getWallLocations(Location location); + + public static OutpostType ById(byte id) + { + for (OutpostType type : values()) + { + if (type._id == id) + { + return type; + } + } + + return null; + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlock.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlock.java new file mode 100644 index 000000000..c0f2f490e --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlock.java @@ -0,0 +1,82 @@ +package mineplex.game.clans.clans.siege.outpost.build; + +import java.util.Map; + +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.BlockState; + +import mineplex.core.common.util.UtilWorld; + +public class OutpostBlock +{ + private Location _location; + private int _id; + private byte _data; + + private int _originalId; + private byte _originalData; + + public OutpostBlock(Map blocks, Location loc, int id, byte data) + { + _location = loc; + _id = id; + _data = data; + + String locStr = UtilWorld.locToStr(loc); + + if (blocks.containsKey(locStr)) + { + _originalId = blocks.get(locStr)._originalId; + _originalData = blocks.get(locStr)._originalData; + } + else + { + _originalId = _location.getBlock().getTypeId(); + _originalData = _location.getBlock().getData(); + } + } + + public void set() + { + _location.getBlock().setTypeIdAndData(_id, _data, false); + if (_id != 0) + { + _location.getWorld().playEffect(_location, Effect.STEP_SOUND, Material.getMaterial(_id), 10); + } + } + + public void restore() + { + BlockState state = _location.getBlock().getState(); + state.setTypeId(_originalId); + state.setRawData(_originalData); + state.update(true, false); + } + + public int getId() + { + return _id; + } + + public byte getData() + { + return _data; + } + + public int getOriginalId() + { + return _originalId; + } + + public int getOriginalData() + { + return _originalData; + } + + public Location getLocation() + { + return _location; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlockBanner.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlockBanner.java new file mode 100644 index 000000000..02ec95e86 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/outpost/build/OutpostBlockBanner.java @@ -0,0 +1,40 @@ +package mineplex.game.clans.clans.siege.outpost.build; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.block.Banner; +import org.bukkit.block.banner.Pattern; + +/** + * Special block for Mk III Outpost + * + */ +public class OutpostBlockBanner extends OutpostBlock +{ + private DyeColor _baseColor; + private List _patterns; + + public OutpostBlockBanner(Map blocks, Location loc, int id, byte data, DyeColor color, Pattern... patterns) + { + super(blocks, loc, id, data); + _baseColor = color; + _patterns = new ArrayList<>(Arrays.asList(patterns)); + } + + @Override + public void set() + { + super.set(); + + Banner banner = (Banner) getLocation().getBlock().getState(); + banner.setBaseColor(_baseColor); + banner.setPatterns(_patterns); + + banner.update(true, false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/OutpostRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/OutpostRepository.java new file mode 100644 index 000000000..6ff1675e6 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/OutpostRepository.java @@ -0,0 +1,141 @@ +package mineplex.game.clans.clans.siege.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.List; + +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.collect.Lists; + +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.UtilWorld; +import mineplex.core.database.MinecraftRepository; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.siege.outpost.OutpostManager; +import mineplex.game.clans.clans.siege.outpost.OutpostState; +import mineplex.game.clans.clans.siege.outpost.OutpostType; +import mineplex.game.clans.clans.siege.repository.tokens.OutpostToken; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnByte; +import mineplex.serverdata.database.column.ColumnInt; +import mineplex.serverdata.database.column.ColumnTimestamp; +import mineplex.serverdata.database.column.ColumnVarChar; + +public class OutpostRepository extends MinecraftRepository +{ + private OutpostManager _manager; + + private static final String CREATE = "CREATE TABLE IF NOT EXISTS clansOutposts (uniqueId INT NOT NULL," + + "serverId INT NOT NULL," + + "origin VARCHAR(30)," + + "outpostType TINYINT NOT NULL," + + "ownerClan INT NOT NULL," + + "timeSpawned LONG," + + "outpostState TINYINT NOT NULL," + + "PRIMARY KEY (uniqueId));"; + + private static final String GET_OUTPOST_BY_ID = "SELECT * FROM clansOutposts WHERE uniqueId=?;"; + private static final String GET_OUTPOST_BY_CLAN = "SELECT * FROM clansOutposts WHERE ownerClan=?;"; + private static final String GET_OUTPOSTS_BY_SERVER = "SELECT * FROM clansOutposts WHERE serverId=?;"; + + private static final String UPDATE_OUTPOST = "UPDATE clansOutposts SET outpostState=? WHERE uniqueId=?;"; + private static final String INSERT_OUTPOST = "INSERT INTO clansOutposts VALUES (?, ?, ?, ?, ?, ?, ?);"; + + private static final String DELETE_OUTPOST = "DELETE FROM clansOutposts WHERE uniqueId=?;"; + + public OutpostRepository(JavaPlugin plugin, OutpostManager manager) + { + super(plugin, DBPool.getAccount()); + + _manager = manager; + } + + public void deleteOutpost(final int uniqueId) + { + executeUpdate(DELETE_OUTPOST, new ColumnInt("uniqueId", uniqueId)); + } + + public void getOutpostById(final int uniqueId, final Callback callback) + { + executeQuery(GET_OUTPOST_BY_ID, resultSet -> { + OutpostToken token = new OutpostToken(); + + resultSet.next(); + + load(token, resultSet); + + callback.run(token); + }, new ColumnInt("uniqueId", uniqueId)); + } + + public void getOutpostByClan(final ClanInfo clan, final Callback callback) + { + executeQuery(GET_OUTPOST_BY_CLAN, resultSet -> { + resultSet.next(); + + OutpostToken token = new OutpostToken(); + + load(token, resultSet); + + callback.run(token); + }, new ColumnInt("ownerClan", clan.getId())); + } + + public void getOutpostsByServer(final int serverId, final Callback> callback) + { + executeQuery(GET_OUTPOSTS_BY_SERVER, resultSet -> { + List tokens = Lists.newArrayList(); + + while (resultSet.next()) + { + OutpostToken token = new OutpostToken(); + load(token, resultSet); + tokens.add(token); + } + + callback.run(tokens); + }, new ColumnInt("serverId", serverId)); + } + + private void load(OutpostToken token, ResultSet columns) throws SQLException + { + token.UniqueId = columns.getInt("uniqueId"); + token.Origin = UtilWorld.strToLoc(columns.getString("origin")); + token.Type = OutpostType.ById(columns.getByte("outpostType")); + token.OwnerClan = _manager.getClansManager().getClanUtility().getClanById(columns.getInt("ownerClan")); + token.TimeSpawned = columns.getTimestamp("timeSpawned").getTime(); + token.OutpostState = OutpostState.ById(columns.getByte("outpostState")); + } + + @Override + protected void initialize() + { + executeUpdate(CREATE); + } + + @Override + protected void update() + { + } + + public void updateOutpost(OutpostToken token) + { + executeUpdate(UPDATE_OUTPOST, + new ColumnByte("outpostState", Byte.valueOf(token.OutpostState.getId())), + new ColumnInt("uniqueId", token.UniqueId)); + } + + public void insertOutpost(OutpostToken token) + { + executeUpdate(INSERT_OUTPOST, + new ColumnInt("uniqueId", token.UniqueId), + new ColumnInt("serverId", _manager.getClansManager().getServerId()), + new ColumnVarChar("origin", 30, UtilWorld.locToStr(token.Origin)), + new ColumnInt("outpostType", token.Type.getId()), + new ColumnInt("ownerClan", token.OwnerClan.getId()), + new ColumnTimestamp("timeSpawned", new Timestamp(token.TimeSpawned)), + new ColumnByte("outpostState", Byte.valueOf(token.OutpostState.getId()))); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/SiegeWeaponRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/SiegeWeaponRepository.java new file mode 100644 index 000000000..302329ccb --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/SiegeWeaponRepository.java @@ -0,0 +1,174 @@ +package mineplex.game.clans.clans.siege.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.collect.Lists; + +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.UtilWorld; +import mineplex.core.database.MinecraftRepository; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.siege.SiegeManager; +import mineplex.game.clans.clans.siege.repository.tokens.SiegeWeaponToken; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnInt; +import mineplex.serverdata.database.column.ColumnTimestamp; +import mineplex.serverdata.database.column.ColumnVarChar; + +public class SiegeWeaponRepository extends MinecraftRepository +{ + private static final String CREATE = "CREATE TABLE IF NOT EXISTS clansSiegeWeapons (uniqueId INT NOT NULL," + + "serverId INT NOT NULL," + + "location VARCHAR(30)," + + "ownerClan INT NOT NULL," + + "weaponType TINYINT NOT NULL," + + "health INT NOT NULL," + + "yaw INT NOT NULL," + + "lastFired LONG," + + "entities VARCHAR(200)," + + "PRIMARY KEY (uniqueId));"; + + private static final String GET_WEAPON_BY_ID = "SELECT * FROM clansSiegeWeapons WHERE uniqueId=?;"; + private static final String GET_WEAPONS_BY_CLAN = "SELECT * FROM clansSiegeWeapons WHERE ownerClan=?;"; + private static final String GET_WEAPONS_BY_SERVER = "SELECT * FROM clansSiegeWeapons WHERE serverId=?;"; + + private static final String UPDATE_WEAPON = "UPDATE clansSiegeWeapons SET health=?,yaw=?,lastFired=? WHERE uniqueId=?;"; + private static final String INSERT_WEAPON = "INSERT INTO clansSiegeWeapons VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; + + private static final String DELETE_WEAPON = "DELETE FROM clansSiegeWeapons WHERE uniqueId=?;"; + + private SiegeManager _siegeManager; + + public SiegeWeaponRepository(JavaPlugin plugin, SiegeManager siegeManager) + { + super(plugin, DBPool.getAccount()); + + _siegeManager = siegeManager; + } + + public void deleteWeapon(final int uniqueId) + { + System.out.println("Siege Repo> Deleting weapon " + uniqueId); + + _siegeManager.runAsync(() -> + executeUpdate(DELETE_WEAPON, new ColumnInt("uniqueId", uniqueId)) + ); + } + + public void getWeaponById(final int uniqueId, final Callback callback) + { + _siegeManager.runAsync(() -> + executeQuery(GET_WEAPON_BY_ID, resultSet -> { + SiegeWeaponToken token = new SiegeWeaponToken(); + + resultSet.next(); + + load(token, resultSet); + + callback.run(token); + }, new ColumnInt("uniqueId", uniqueId)) + ); + } + + public void getWeaponsByServer(final int serverId, final Callback> callback) + { + _siegeManager.runAsync(() -> + executeQuery(GET_WEAPONS_BY_SERVER, resultSet -> { + List tokens = Lists.newArrayList(); + + while (resultSet.next()) + { + SiegeWeaponToken token = new SiegeWeaponToken(); + + load(token, resultSet); + + tokens.add(token); + } + + callback.run(tokens); + }, new ColumnInt("serverId", serverId)) + ); + } + + public void getWeaponsByClan(final ClanInfo clan, final Callback> callback) + { + _siegeManager.runAsync(() -> + executeQuery(GET_WEAPONS_BY_CLAN, resultSet -> { + List tokens = Lists.newArrayList(); + + while (resultSet.next()) + { + SiegeWeaponToken token = new SiegeWeaponToken(); + + load(token, resultSet); + + tokens.add(token); + } + + callback.run(tokens); + }, new ColumnInt("ownerClan", clan.getId())) + ); + } + + private void load(SiegeWeaponToken token, ResultSet columns) throws SQLException + { + token.UniqueId = columns.getInt("uniqueId"); + token.Location = UtilWorld.strToLoc(columns.getString("location")); + token.OwnerClan = _siegeManager.getClansManager().getClanUtility().getClanById(columns.getInt("ownerClan")); + token.WeaponType = columns.getByte("weaponType"); + token.Health = columns.getShort("health"); + token.Yaw = columns.getShort("yaw"); + token.LastFired = columns.getTimestamp("lastFired").getTime(); + + System.out.println("Siege Repo> Loaded weapon " + token.UniqueId); + } + + public void updateWeapon(SiegeWeaponToken token) + { + System.out.println("Siege Repo> Updating weapon " + token.UniqueId); + + _siegeManager.runAsync(() -> + executeUpdate(UPDATE_WEAPON, + new ColumnInt("health", token.Health), + new ColumnInt("yaw", token.Yaw), + new ColumnTimestamp("lastFired", new Timestamp(token.LastFired)), + new ColumnInt("uniqueId", token.UniqueId)) + ); + } + + public void insertWeapon(SiegeWeaponToken token) + { + System.out.println("Siege Repo> Inserting new weapon " + token.UniqueId); + + _siegeManager.runAsync(() -> + executeUpdate(INSERT_WEAPON, + new ColumnInt("uniqueId", token.UniqueId), + new ColumnInt("serverId", _siegeManager.getClansManager().getServerId()), + new ColumnVarChar("location", 30, UtilWorld.locToStr(token.Location)), + new ColumnInt("ownerClan", token.OwnerClan.getId()), + new ColumnInt("weaponType", token.WeaponType), + new ColumnInt("health", token.Health), + new ColumnInt("yaw", token.Yaw), + new ColumnTimestamp("lastFired", new Timestamp(token.LastFired)), + new ColumnVarChar("entities", 100, "")) + ); + } + + @Override + protected void initialize() + { + executeUpdate(CREATE); + } + + @Override + protected void update() + { + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/OutpostToken.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/OutpostToken.java new file mode 100644 index 000000000..0436fbda9 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/OutpostToken.java @@ -0,0 +1,17 @@ +package mineplex.game.clans.clans.siege.repository.tokens; + +import org.bukkit.Location; + +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.siege.outpost.OutpostState; +import mineplex.game.clans.clans.siege.outpost.OutpostType; + +public class OutpostToken +{ + public int UniqueId; + public Location Origin; + public OutpostType Type; + public ClanInfo OwnerClan; + public long TimeSpawned; + public OutpostState OutpostState; +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/SiegeWeaponToken.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/SiegeWeaponToken.java new file mode 100644 index 000000000..638aa800c --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/repository/tokens/SiegeWeaponToken.java @@ -0,0 +1,20 @@ +package mineplex.game.clans.clans.siege.repository.tokens; + +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Location; + +import mineplex.game.clans.clans.ClanInfo; + +public class SiegeWeaponToken +{ + public int UniqueId; + public ClanInfo OwnerClan; + public byte WeaponType; + public Location Location; + public int Health; + public int Yaw; + public long LastFired; + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/Cannon.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/Cannon.java new file mode 100644 index 000000000..bb880fcf0 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/Cannon.java @@ -0,0 +1,463 @@ +package mineplex.game.clans.clans.siege.weapon; + +import java.util.ArrayList; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.entity.Slime; +import org.bukkit.event.EventHandler; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +import com.google.common.collect.Lists; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.siege.SiegeManager; +import mineplex.game.clans.clans.siege.events.SiegeWeaponExplodeEvent; +import mineplex.game.clans.clans.siege.repository.tokens.SiegeWeaponToken; +import mineplex.game.clans.clans.siege.weapon.projectile.WeaponProjectile; +import mineplex.game.clans.clans.siege.weapon.util.AccessRule; +import mineplex.game.clans.clans.siege.weapon.util.AccessType; +import mineplex.game.clans.clans.siege.weapon.util.WeaponStateInfo; + +public class Cannon extends SiegeWeapon +{ + public static final ItemStack CANNON_ITEM = new ItemBuilder(Material.SPONGE, 1).setData((byte) 1).setRawTitle(C.Reset + C.cBlue + "Cannon").build(); + + private int _firepower = 1; + + public Cannon(SiegeManager siegeManager, SiegeWeaponToken token) + { + super(300, "Cannon", token, siegeManager.getClansManager(), siegeManager); + + if (_ownerClan == null) + { + System.out.println("[cannon] owner clan null, killing"); + kill(); + return; + } + + System.out.println("Siege> Loading Cannon from token " + token.UniqueId); + + setBoundingBox(1); + + setStateInfo("Unloaded", new WeaponStateInfo(Material.SPONGE, (byte) 1)); + setStateInfo("Loaded", new WeaponStateInfo(Material.SPONGE, (byte) 0)); + + setAmmunitionType(Material.TNT); + + setAmmunitionSlot(4); + setMaximumAmmunitionPerSlot(1); + + _baseDamage = 650; + + setFireRule(new AccessRule(AccessType.LCLICK_BB, player -> { + if (!isRiding(player)) + { + return false; + } + +// if (!_ownerClan.isMember(player)) +// { +// UtilPlayer.message(player, F.main("Clans", "This cannon is not owned by your Clan.")); +// return false; +// } + + if(_clans.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot fire a cannon whilst on PvPTimer")); + return false; + } + + if (!canBeFired()) + { + UtilPlayer.message(player, F.main("Clans", "Cannon is not loaded correctly.")); + return false; + } + + if (System.currentTimeMillis() - _lastFired < 20000) + { + UtilPlayer.message(player, F.main("Clans", "Cannon is cooling down (" + F.time(UtilTime.MakeStr(20000 - (System.currentTimeMillis() - _lastFired))) + ")")); + return false; + } + + return true; + })); + + enableInventory(UtilServer.getServer().createInventory(null, InventoryType.DISPENSER, C.cDAquaB + _name), new AccessRule(AccessType.RCLICK_BB, player -> player.equals(getRider()))); + + setRideable(new AccessRule(AccessType.RCLICK_BB, player -> { + if (!_ownerClan.isMember(player)) + { + UtilPlayer.message(player, F.main("Clans", "This Cannon is not owned by your Clan.")); + return false; + } + + if (getRider() != null && !getRider().equals(player)) + { + UtilPlayer.message(player, F.main("Clans", "Someone is already riding this cannon.")); + return false; + } + + if(_clans.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot ride on a Cannon whilst on PvPTimer")); + return false; + } + + return !player.equals(getRider()); + })); + } + + public Cannon(Location location, ClanInfo clan, SiegeManager siegeManager, boolean syncWithDb) + { + super(2, location.clone().add(0.5, 0, 0.5), 1400, "Cannon", clan, clan.Clans, siegeManager); + + _syncWithDb = syncWithDb; + + setBoundingBox(1); + + setStateInfo("Unloaded", new WeaponStateInfo(Material.SPONGE, (byte) 1)); + setStateInfo("Loaded", new WeaponStateInfo(Material.SPONGE, (byte) 0)); + + loadEntities(true); + + setFirepowerType(Material.SULPHUR); + setAmmunitionType(Material.TNT); + + setFirepowerSlots(Integer.valueOf(1), Integer.valueOf(3), Integer.valueOf(5), Integer.valueOf(7)); + setMaximumFirepowerPerSlot(3); + + setAmmunitionSlot(4); + setMaximumAmmunitionPerSlot(1); + + _baseDamage = 650; + + setFireRule(new AccessRule(AccessType.LCLICK_BB, player -> { + if (!isRiding(player)) + { + return false; + } + +// if (!_ownerClan.isMember(player)) +// { +// UtilPlayer.message(player, F.main("Clans", "This Cannon is not owned by your Clan.")); +// return false; +// } + + if (_clans.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot fire a Cannon whilst protected from pvp.")); + return false; + } + + if (!canBeFired()) + { + UtilPlayer.message(player, F.main("Clans", "Cannon is not loaded correctly.")); + return false; + } + + if (System.currentTimeMillis() - _lastFired < 30000) + { + UtilPlayer.message(player, F.main("Clans", "Cannon is cooling down (" + F.time(UtilTime.MakeStr(30000 - (System.currentTimeMillis() - _lastFired))) + ")")); + return false; + } + + return true; + })); + + enableInventory(UtilServer.getServer().createInventory(null, InventoryType.DISPENSER, C.cDAquaB + _name), new AccessRule(AccessType.RCLICK_BB, player -> player.equals(getRider()))); + + setRideable(new AccessRule(AccessType.RCLICK_BB, player -> { + if (!_ownerClan.isMember(player)) + { + UtilPlayer.message(player, F.main("Clans", "This Cannon is not owned by your Clan.")); + return false; + } + + if (getRider() != null && !getRider().equals(player)) + { + UtilPlayer.message(player, F.main("Clans", "Someone is already riding this Cannon.")); + return false; + } + + if(_clans.hasTimer(player)) + { + UtilPlayer.message(player, F.main("Clans", "You cannot ride on a Cannon whilst protected from pvp.")); + return false; + } + + return !player.equals(getRider()); + })); + } + + @EventHandler + protected void InventoryClick(InventoryClickEvent event) + { + if (event.getClickedInventory() == null) + { + return; + } + + if (event.getClick() == ClickType.SHIFT_RIGHT || event.getClick() == ClickType.SHIFT_RIGHT) + { + if(_inventory.getViewers().contains(event.getWhoClicked())) + { + event.setCancelled(true); //block shift right clicking tnt into this inventory + getClans().runSyncLater(() -> ((Player) event.getWhoClicked()).updateInventory(), 1L); + } + + return; + } + + if (!event.getClickedInventory().equals(_inventory)) + { + return; + } + + if (event.getSlot() == 0) + { + int oldFirepower = _firepower; + + _firepower = UtilMath.clamp(--_firepower, 1, 3); + + if (oldFirepower != _firepower) + { + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.NOTE_PLING, 1.0f, 1.0f); + } + else + { + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); + } + + event.setCancelled(true); + } + else if (event.getSlot() == 1) + { + event.setCancelled(true); + } + else if (event.getSlot() == 2) + { + int oldFirepower = _firepower; + + _firepower = UtilMath.clamp(++_firepower, 1, 3); + + if (oldFirepower != _firepower) + { + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.NOTE_PLING, 1.0f, 1.0f); + } + else + { + ((Player) event.getWhoClicked()).playSound(event.getWhoClicked().getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); + } + + event.setCancelled(true); + } + else if (event.getSlot() != _ammunitionSlot) + { + event.setCancelled(true); + } + } + + private void updateInventory() + { + _inventory.setItem(0, new ItemBuilder(Material.LEVER).setTitle(C.cRed + "-1 Firepower").build()); + _inventory.setItem(1, new ItemBuilder(Material.SULPHUR).setTitle(C.cWhiteB + "Firepower: " + C.cYellow + _firepower).setAmount(_firepower).build()); + _inventory.setItem(2, new ItemBuilder(Material.LEVER).setTitle(C.cGreen + "+1 Firepower").build()); + + for (int slot : UtilCollections.newList(Integer.valueOf(3), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8))) + { + _inventory.setItem(slot, new ItemBuilder(Material.COBBLESTONE).setTitle(C.cGray + "Cannon Wall").build()); + } + } + + protected boolean CustomInventoryValid(int slot, ItemStack item) + { + return true; // all slots are now filled; slot == 0 || slot == 1 || slot == 2; + } + + private void loadEntities(boolean insert) + { + Slime filler = _location.getWorld().spawn(_location.clone(), Slime.class); + + UtilEnt.silence(filler, true); + UtilEnt.Vegetate(filler); + + filler.setSize(-1); + filler.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 99999999, 1, true, false)); + + addEntity(filler, "Filler_1"); + + Slime playerMount = _location.getWorld().spawn(_location.clone(), Slime.class); + + UtilEnt.silence(playerMount, true); + UtilEnt.Vegetate(playerMount); + + playerMount.setSize(-1); + playerMount.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 99999999, 1, true, false)); + + getEntity("Filler_1").setPassenger(playerMount); + addEntity(playerMount, "PLAYERMOUNT"); + + ArmorStand weapon = _location.getWorld().spawn(_location.clone(), ArmorStand.class); + + UtilEnt.setFakeHead(weapon, true); + weapon.teleport(_location); + weapon.setVisible(false); + weapon.setGravity(false); + + weapon.setPassenger(getEntity("Filler_1")); + + addEntity(weapon, "WEAPON"); + + if (insert) + { + insert(); + } + } + + @Override + public void FindEntities() + { + Lists.newArrayList(_location.getWorld().getEntities()) + .forEach(entity -> { + if (Integer.toString(_uniqueId).equals(entity.getCustomName())) + { + entity.remove(); + } + }); + + loadEntities(false); + } + + @Override + protected WeaponProjectile CustomFire(double yawRot, double verticalVel, double horizontalVel) + { + Location location = UtilAlg.moveForward(new Location(_location.getWorld(), _location.getX(), _location.getY() + .2, _location.getZ(), (float) yawRot, (float) 0), 0.35, (float) yawRot, false); + + UtilParticle.PlayParticleToAll(ParticleType.LARGE_EXPLODE, location, new Vector(0, 0, 0), .1f, 2, ViewDist.MAX); + UtilServer.getServer().getOnlinePlayers().forEach(player -> player.playSound(location, Sound.EXPLODE, 1.f, 1.f)); + + return new TntProjectile(this, location, yawRot, verticalVel, horizontalVel); + } + + @Override + public String GetNextState() + { + if (getAmmunition() > 0) + { + return "Loaded"; + } + + return "Unloaded"; + } + + protected int getPowerLevel() + { + return _firepower; + } + + @Override + protected void CustomTick() + { + updateInventory(); + + if (getProjectile() != null) + { + UtilParticle.PlayParticleToAll(ParticleType.LARGE_SMOKE, getProjectile().getLocation().add(0, .5, 0), new Vector(0, 0, 0), .1f, 3, ViewDist.MAX); + } + } + + protected void handleLeftClick(Player player) + { + super.handleLeftClick(player); + } + + @Override + protected double[] GetProjectileVelocity() + { + int firepower = getPowerLevel(); + + double hMult = 0; + double yAdd = 0; + + if (firepower == 1) + { + hMult = 1.2; + yAdd = 0.5; + } + else if (firepower == 2) + { + hMult = 1.7; + yAdd = 0.55; + } + else if (firepower >= 3) + { + hMult = 2.35; + yAdd = 0.6; + } + + return new double[] { yAdd, hMult }; + } + + @EventHandler + public void explosionEffects(SiegeWeaponExplodeEvent event) + { +// for (int i = 0; i < 8; i++) +// { +// // Explosion particle effects. +// Location point = UtilAlg.getRandomLocation(event.getProjectile().getLocation(), 5); +// UtilParticle.PlayParticle(ParticleType.HUGE_EXPLOSION, point, 0, 0, 0, 1, 2, ViewDist.MAX); +// } + + // Block explosion. + ArrayList blocks = new ArrayList<>(); + int attempts = 0; + while (blocks.size() < 10 && (attempts < 30)) + { + Block block = UtilAlg.getRandomLocation(event.getProjectile().getLocation(), (4 * getPowerLevel())).getBlock(); + + if (_siegeManager.getClansManager().getClanUtility().getClaim(block.getLocation()) != null && !_siegeManager.getClansManager().getBlacklist().allowed(_siegeManager.getClansManager().getClanUtility().getClaim(block.getLocation()).Owner)) + { + continue; + } + + if ((block.getType() != Material.AIR) && (!blocks.contains(block))) + { + blocks.add(block); + } + + attempts++; + } + + _clans.getExplosion().BlockExplosion( + blocks, + event.getProjectile().getLocation(), + false, + false + ); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/SiegeWeapon.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/SiegeWeapon.java new file mode 100644 index 000000000..7974c50c4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/SiegeWeapon.java @@ -0,0 +1,976 @@ +package mineplex.game.clans.clans.siege.weapon; + +import java.util.UUID; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.EulerAngle; +import org.spigotmc.event.entity.EntityDismountEvent; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.NautArrayList; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.hologram.Hologram; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClanDeleteEvent; +import mineplex.game.clans.clans.siege.SiegeManager; +import mineplex.game.clans.clans.siege.events.LoadSiegeWeaponEvent; +import mineplex.game.clans.clans.siege.events.MountSiegeWeaponEvent; +import mineplex.game.clans.clans.siege.events.SiegeWeaponExplodeEvent; +import mineplex.game.clans.clans.siege.repository.tokens.SiegeWeaponToken; +import mineplex.game.clans.clans.siege.weapon.projectile.WeaponProjectile; +import mineplex.game.clans.clans.siege.weapon.util.AccessRule; +import mineplex.game.clans.clans.siege.weapon.util.AccessType; +import mineplex.game.clans.clans.siege.weapon.util.BarrierCollisionBox; +import mineplex.game.clans.clans.siege.weapon.util.WeaponStateInfo; +import mineplex.game.clans.items.PlayerGear; +import mineplex.game.clans.items.legendaries.AlligatorsTooth; +import mineplex.game.clans.items.legendaries.GiantsBroadsword; +import mineplex.game.clans.items.legendaries.HyperAxe; +import mineplex.game.clans.items.legendaries.LegendaryItem; +import mineplex.game.clans.items.legendaries.MagneticMaul; +import mineplex.game.clans.items.legendaries.WindBlade; + +public abstract class SiegeWeapon implements Listener +{ + // Constants + protected final int _maxHealth; + protected final byte _weaponTypeIdentifier; + + protected SiegeWeaponToken _loadedToken; + + // Managers + protected ClansManager _clans; + protected SiegeManager _siegeManager; + + // Info + protected final int _uniqueId; + + protected final ClanInfo _ownerClan; + protected final Location _location; + protected final String _name; + + protected int _health; + protected String _currentState; + protected boolean _alive = true; + protected boolean _invincible = false; + + // Mechanics + protected final NautArrayList _comprisedOf; + + protected Player _rider; + protected Inventory _inventory; + protected AccessRule _inventoryAccess; + protected BarrierCollisionBox _collisionBox; + + protected AccessRule _fireAccess; + + protected int _boundingBoxSize; + + protected double _yaw; + + protected long _lastRight = -1; + protected long _lastLeft = -1; + protected long _lastFired = -1; + + // Display + protected Hologram _infoHologram; + + // Utility + protected final NautHashMap _registeredStates; + protected final NautHashMap _entityMapping; + + protected boolean _syncWithDb; + + // Customizability + private double[] _forcedVelocity; + + protected boolean _isRideable; + protected boolean _invertRotation; + protected AccessRule _mountAccess; + + protected float _rotSpeed = 20.f; + + protected int _ammunitionSlot; + protected Material _ammunitionType; + protected int _maxAmmunition; + + protected NautArrayList _firepowerSlots = new NautArrayList<>(); + protected Material _firepowerType; + protected int _maxFirepowerPerSlot; + + protected int _baseDamage; + + protected WeaponProjectile _projectile; + + public SiegeWeapon(int maxHealth, String name, SiegeWeaponToken token, ClansManager clansManager, SiegeManager siegeManager) + { + _weaponTypeIdentifier = token.WeaponType; + + _loadedToken = token; + + _uniqueId = token.UniqueId; + + _siegeManager = siegeManager; + _location = token.Location; + _name = name; + _health = _maxHealth = maxHealth; + _ownerClan = token.OwnerClan; + + _comprisedOf = new NautArrayList<>(); + _registeredStates = new NautHashMap<>(); + _entityMapping = new NautHashMap<>(); + + _infoHologram = new Hologram(ClansManager.getInstance().getHologramManager(), _location.clone().add(.5, 3, .5), _name + " Health", getDisplayHealth()); + _infoHologram.start(); + + _infoHologram.setInteraction((player, type) -> { + if (type.equals(ClickType.LEFT)) + { + handleLeftClick(player); + } + else if (type.equals(ClickType.RIGHT)) + { + handleRightClick(player); + } + }); + + UtilServer.RegisterEvents(this); + + _clans = clansManager; + + _yaw = token.Yaw; + _lastFired = token.LastFired; + + _health = token.Health; + + FindEntities(); + } + + public SiegeWeapon(int typeId, Location location, int maxHealth, String name, ClanInfo owner, ClansManager clansManager, SiegeManager siegeManager) + { + _uniqueId = siegeManager.randomId(); + _weaponTypeIdentifier = (byte) typeId; + + _siegeManager = siegeManager; + _location = location; + _name = name; + _health = _maxHealth = maxHealth; + _ownerClan = owner; + + _comprisedOf = new NautArrayList<>(); + _registeredStates = new NautHashMap<>(); + _entityMapping = new NautHashMap<>(); + + _infoHologram = new Hologram(ClansManager.getInstance().getHologramManager(), _location.clone().add(.5, 3, .5), _name + " Health", getDisplayHealth()); + _infoHologram.start(); + + UtilServer.getPluginManager().registerEvents(this, clansManager.getPlugin()); + + _clans = clansManager; + } + + protected void insert() + { + if (_syncWithDb) + _siegeManager.getRepository().insertWeapon(toToken()); + } + + protected int calculateDamage(Player player) + { + ItemStack stack = player.getItemInHand(); + PlayerGear gear = _clans.getGearManager().getPlayerGear(player); + + if (stack == null) + return 1; + + if (gear.getWeapon() != null && gear.getWeapon() instanceof LegendaryItem) + if (gear.getWeapon() instanceof AlligatorsTooth) + return 8; + else if (gear.getWeapon() instanceof GiantsBroadsword) + return 10; + else if (gear.getWeapon() instanceof HyperAxe) + return 3; + else if (gear.getWeapon() instanceof MagneticMaul) + return 8; + else if (gear.getWeapon() instanceof WindBlade) + return 7; + + return (int) UtilItem.getAttackDamage(stack.getType()); + } + + protected void enableInventory(Inventory inventory, AccessRule accessRule) + { + _inventory = inventory; + _inventoryAccess = accessRule; + } + + protected void setBoundingBox(int size) + { + Validate.isTrue(size > 0, "Size must be a positive number."); + Validate.isTrue(UtilMath.isOdd(size), "Size must be an odd number."); + + _boundingBoxSize = size; + + _collisionBox = size == 1 ? BarrierCollisionBox.single(_location.clone()) : BarrierCollisionBox.all(_location.clone().subtract((size - 1) / 2, 0, (size - 1) / 2), _location.clone().add(((size - 1) / 2) + .2, size - 1, ((size - 1) / 2) + .2)); + _collisionBox.Construct(); + _collisionBox.registerRight((block, player) -> handleRightClick(player)); + _collisionBox.registerLeft((block, player) -> handleLeftClick(player)); + } + + protected void setBoundingBox(int size, int y) + { + Validate.isTrue(size > 0, "Size must be a positive number."); + Validate.isTrue(UtilMath.isOdd(size), "Size must be an odd number."); + + _boundingBoxSize = size; + + _collisionBox = size == 1 ? BarrierCollisionBox.single(_location.clone()) : BarrierCollisionBox.all(_location.clone().subtract((size - 1) / 2, 0, (size - 1) / 2), _location.clone().add(((size - 1) / 2) + .2, y, ((size - 1) / 2) + .2)); + _collisionBox.Construct(); + _collisionBox.registerRight((block, player) -> handleRightClick(player)); + _collisionBox.registerLeft((block, player) -> handleLeftClick(player)); + } + + private void update() + { + if (getEntity("WEAPON") == null || getEntity("PLAYERMOUNT") == null) + { + kill(); + return; + } + + if (_inventory != null) + checkInventory(); + + _rider = (Player) getEntity("PLAYERMOUNT").getPassenger(); + + if (!GetNextState().equals(_currentState)) + setState(GetNextState()); + + if (_projectile != null && _projectile.hasDied()) + _projectile = null; + + ArmorStand armorStand = (ArmorStand) getEntity("WEAPON"); + double standYaw = _yaw % 360; + + if (getRider() != null) + { + double riderYaw = (getRider().getLocation().getYaw() + (_invertRotation ? 180 : 0)) % 360; + + double dif = riderYaw - standYaw; + if (dif > 180) dif -= 360; + if (dif < -180) dif += 360; + + double yaw = (float) ((float)standYaw + Math.min(dif / _rotSpeed, 4f)); + + armorStand.setHeadPose(new EulerAngle(0, Math.toRadians(CustomRotate(_yaw = yaw)), 0)); + } + } + + protected boolean canBeFired() + { + return getPowerLevel() > 0 && getAmmunition() > 0 && _projectile == null; + } + + public void SetForcedVelocity(double vertical, double horizontal) + { + _forcedVelocity = new double[] { vertical, horizontal }; + } + + private void fire(Player player) + { + _lastFired = System.currentTimeMillis(); + + double[] vel = GetProjectileVelocity(); + + if (_forcedVelocity != null) + { + vel = _forcedVelocity; + } + + _inventory.clear(); + + _projectile = CustomFire(((ArmorStand) getEntity("WEAPON")).getHeadPose().getY(), vel[0], vel[1]); + } + + protected void setFireRule(AccessRule rule) + { + _fireAccess = rule; + } + + protected void setFirepowerType(Material type) + { + _firepowerType = type; + } + + protected void setAmmunitionType(Material type) + { + _ammunitionType = type; + } + + protected void setFirepowerSlots(Integer... slots) + { + _firepowerSlots = UtilCollections.newNautList(slots); + } + + protected void setMaximumFirepowerPerSlot(int maxFirepowerPerSlot) + { + _maxFirepowerPerSlot = maxFirepowerPerSlot; + } + + protected void setAmmunitionSlot(int ammunitionSlot) + { + _ammunitionSlot = ammunitionSlot; + } + + protected void setMaximumAmmunitionPerSlot(int maxAmmunition) + { + _maxAmmunition = maxAmmunition; + } + + protected boolean isRiding(Player player) + { + return player.equals(getRider()); + } + + protected void setRideable(AccessRule accessRule) + { + _isRideable = true; + _mountAccess = accessRule; + } + + public void kill() + { + System.out.println("Killing: " + this.getClass().getSimpleName() + " [" + _uniqueId + "]"); + + _siegeManager.runSync(() -> { + CustomCleanup(); + + _comprisedOf.forEach(Entity::remove); + + _entityMapping.clear(); + _comprisedOf.clear(); + _infoHologram.stop(); + + if (_collisionBox != null) _collisionBox.Destruct(); + + _siegeManager.dead(this); + + _alive = false; + }); + + HandlerList.unregisterAll(this); + } + + private void handleMount(Player player) + { + UtilServer.CallEvent(new MountSiegeWeaponEvent(player, this)); + + if (!CustomMount(player)) + { + getEntity("PLAYERMOUNT").setPassenger(player); + } + + CustomOnMount(player); + } + + private void handleInventoryOpen(Player player) + { + player.openInventory(_inventory); + } + + private void handleRightClick(Player player) + { + if (_lastRight == -1) + { + _lastRight = System.currentTimeMillis(); + } + else + { + if (System.currentTimeMillis() - _lastRight <= 40) + { + return; + } + } + + _lastRight = System.currentTimeMillis(); + + CustomRightClick(player); + + if (_isRideable && _mountAccess.allow(AccessType.RCLICK_BB, player)) + { + handleMount(player); + return; + } + + if (_inventory != null && _inventoryAccess.allow(AccessType.RCLICK_BB, player)) + { + handleInventoryOpen(player); + return; + } + + if (_fireAccess.allow(AccessType.RCLICK_BB, player)) + { + fire(player); + } + } + + protected boolean CustomInventoryValid(int slot, ItemStack item) + { + return false; + } + + private void dismount(Player player) + { + player.teleport(player.getLocation().add(0, 1, 0)); + } + + protected void handleLeftClick(Player player) + { + if (_lastLeft == -1) + { + _lastLeft = System.currentTimeMillis(); + } + else + { + if (System.currentTimeMillis() - _lastLeft <= 40) + { + return; + } + } + + _lastLeft = System.currentTimeMillis(); + + CustomLeftClick(player); + + if (_isRideable && _mountAccess.allow(AccessType.LCLICK_BB, player)) + { + handleMount(player); + return; + } + + if (_inventory != null && _inventoryAccess.allow(AccessType.LCLICK_BB, player)) + { + handleInventoryOpen(player); + return; + } + + if (_fireAccess.allow(AccessType.LCLICK_BB, player)) + { + fire(player); + return; + } + + if (!player.equals(_rider) && Recharge.Instance.use(player, "Damage Cannon", 200, false, false)) + { + int health = calculateDamage(player); + + removeHealth(health); + + new Hologram( + _siegeManager.getClansManager().getHologramManager(), + _location.clone().add(UtilMath.random(-1, 1),1.4, UtilMath.random(-1, 1)), + 3500l, + C.cRed + "-" + health) + .start(); + } + } + + + protected abstract double[] GetProjectileVelocity(); + protected abstract String GetNextState(); + protected abstract void FindEntities(); + protected abstract WeaponProjectile CustomFire(double yawRot, double verticalVel, double horizontalVel); + protected void CustomTick() { return; } + protected void CustomOnMount(Player player) { return; } + protected void CustomLeftClick(Player player) { return; } + protected void CustomRightClick(Player player) { return; } + protected void CustomCleanup() { return; } + protected void CustomUpdateState(String state) { return; } + protected double CustomRotate(double yaw) { return yaw; } + protected boolean CustomDismount(Player player, Entity entity) { return false; } + protected boolean CustomMount(Player player) { return false; } + + protected final void addEntity(Entity entity, String uniqueName) + { + entity.setCustomName(Integer.toString(_uniqueId)); + entity.setCustomNameVisible(false); + + _comprisedOf.add(entity); + + _entityMapping.put(uniqueName, entity); + } + + protected final void removeEntity(String uniqueName) + { + Entity entity = _entityMapping.get(uniqueName); + + _entityMapping.remove(uniqueName); + _comprisedOf.remove(entity); + + entity.remove(); + } + + protected final Entity getEntity(String uniqueName) + { + return _entityMapping.get(uniqueName); + } + + public final int getHealth() + { + return _health; + } + + public final String getDisplayHealth() + { + return UtilText.getProgress(null, ((double) _health) / ((double) _maxHealth), null, false, 12); + } + + public final void setHealth(int health) + { + _health = UtilMath.clamp(health, 0, _maxHealth); + + _infoHologram.setText(_name + " Health", getDisplayHealth()); + + if (_health == 0 && !_invincible) + kill(); + } + + public final void removeHealth(int health) + { + if (_invincible) return; + setHealth(_health - health); + } + + public final void addHealth(int health) + { + setHealth(_health + health); + } + + public final void setState(String state) + { + Validate.isTrue(_registeredStates.containsKey(state), "Provided state has not yet been registered."); + + ((ArmorStand) getEntity("WEAPON")).setHelmet(new ItemStack(_registeredStates.get(state).getType(), 1, (short) 0, (byte) _registeredStates.get(state).getData())); + + CustomUpdateState(_currentState = state); + } + + public final void setStateInfo(String state, WeaponStateInfo info) + { + _registeredStates.put(state, info); + } + + public final WeaponStateInfo getStateInfo(String state) + { + if (!_registeredStates.containsKey(state)) + _registeredStates.put(state, new WeaponStateInfo(Material.STONE, (byte) 101)); + + return _registeredStates.get(state); + } + + public void checkInventory() + { + for (int slot = 0; slot < _inventory.getSize(); slot++) + { + ItemStack item = _inventory.getItem(slot); + + if (item == null) + continue; + + if (slot == _ammunitionSlot) + { + if (item.getType() != _ammunitionType) + { + if (CustomInventoryValid(slot, item)) + continue; + + if (getRider() != null) + getRider().getInventory().addItem(item); + else + _location.getWorld().dropItem(_location, item); + + _inventory.setItem(slot, null); + } + else + { + if (item.getAmount() > _maxAmmunition) + { + if (getRider() != null) + getRider().getInventory().addItem(new ItemStack(_ammunitionType, item.getAmount() - _maxAmmunition)); + else + _location.getWorld().dropItem(_location, item); + + _inventory.setItem(slot, new ItemStack(_ammunitionType, _maxAmmunition)); + } + else + { + UtilServer.CallEvent(new LoadSiegeWeaponEvent(getRider(), this)); + } + } + } + else if (_firepowerSlots.contains(Integer.valueOf(slot))) + { + if (item.getType() != _firepowerType) + { + if (CustomInventoryValid(slot, item)) + continue; + + if (getRider() != null) + getRider().getInventory().addItem(item); + else + _location.getWorld().dropItem(_location, item); + + _inventory.setItem(slot, null); + } + else + { + if (item.getAmount() > _maxFirepowerPerSlot) + { + if (getRider() != null) + getRider().getInventory().addItem(new ItemStack(_firepowerType, item.getAmount() - _maxFirepowerPerSlot)); + else + _location.getWorld().dropItem(_location, item); + + _inventory.setItem(slot, new ItemStack(_firepowerType, _maxFirepowerPerSlot)); + } + } + } + else + { + if (CustomInventoryValid(slot, item)) + continue; + + if (getRider() != null) + getRider().getInventory().addItem(item); + else + _location.getWorld().dropItem(_location, item); + + _inventory.setItem(slot, null); + } + } + } + + @EventHandler + public void clanDelete(ClanDeleteEvent event) + { + if (event.getClanInfo().getName().equals(_ownerClan.getName())) + { + System.out.println("Killing Siege weapon " + _uniqueId + " because owner clan has been deleted."); + kill(); + } + } + + @EventHandler + public void onSiegeWeaponExplode(SiegeWeaponExplodeEvent event) + { + if (UtilAlg.inBoundingBox(event.getProjectile().getLocation(), _location.clone().subtract(3, 2, 3), _location.clone().add(3, 2, 3))) + { + kill(); + + _ownerClan.inform("One of your Cannons has been destroyed!", null); + UtilTextMiddle.display("Damage", "You destroyed " + F.elem(getOwner().getName()) + "'s " + _name + ".", 10, 60, 10, event.getWeapon().getRider()); + UtilPlayer.message(event.getWeapon().getRider(), F.main("Clans", "You destroyed " + F.elem(getOwner().getName()) + "'s " + _name + ".")); + } + } + + @EventHandler + public void onDamage(EntityDamageEvent event) + { + if (_comprisedOf.contains(event.getEntity())) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDmg(EntityDamageByEntityEvent event) + { + if (_comprisedOf.contains(event.getEntity()) && event.getDamager() instanceof Player) + { + if (!((Player) event.getDamager()).equals(_rider)) + { + handleLeftClick((Player) event.getDamager()); + } + + event.setCancelled(true); + } + } + + @EventHandler + public void onCloseInv(InventoryCloseEvent event) + { + if (!event.getInventory().equals(_inventory)) + return; + + ClansManager.getInstance().runSyncLater(() -> { + if (!event.getPlayer().getInventory().equals(_inventory) && canBeFired()) + UtilTextMiddle.display(_name + " Ready", "Power Level: " + C.cGreen + UtilText.repeat("▌", getPowerLevel()) + C.cRed + UtilText.repeat("▌", _maxFirepowerPerSlot - getPowerLevel()), 20, 100, 20, (Player) event.getPlayer()); + }, 3L); + } + + @EventHandler + public void onDismount(EntityDismountEvent event) + { + if (event.getEntity() instanceof Player && (event.getDismounted().equals(getEntity("PLAYERMOUNT")) || CustomDismount((Player) event.getEntity(), event.getDismounted()))) + dismount((Player) event.getEntity()); + } + + @EventHandler + public void onInteract(PlayerInteractAtEntityEvent event) + { + if (_comprisedOf.contains(event.getRightClicked())) + { + handleRightClick(event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) + { + if (!event.getPlayer().equals(_rider)) + { + return; + } + + System.out.println(event.getAction()); + + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) + { + handleRightClick(event.getPlayer()); + event.setCancelled(true); + } + else if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) + { + handleLeftClick(event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void onInteract(PlayerInteractEntityEvent event) + { + if (_comprisedOf.contains(event.getRightClicked())) + { + handleRightClick(event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void onBlockBreak(BlockBreakEvent event) + { + if (!event.getBlock().getLocation().getWorld().equals(_location.getWorld())) + { + return; + } + + if (event.getBlock().getLocation().distance(_location) < _boundingBoxSize + 1.65 && event.getBlock().getLocation().getY() <= _location.getY()) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not break blocks near a Siege Weapon")); + event.setCancelled(true); + } + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) + { + if (!event.getBlock().getLocation().getWorld().equals(_location.getWorld())) + { + return; + } + + if (event.getBlock().getLocation().distance(_location) < _boundingBoxSize + 1.65 && event.getBlock().getLocation().getY() <= _location.getY()) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You may not place blocks near a Siege Weapon")); + event.setCancelled(true); + } + } + + public boolean inProtection(Block block) + { + if (!block.getLocation().getWorld().equals(_location.getWorld())) + { + return false; + } + + return block.getLocation().distance(_location) < _boundingBoxSize + 1.65 && block.getLocation().getY() <= _location.getY() + 2; + } + + @EventHandler + public void onInteract(PlayerArmorStandManipulateEvent event) + { + if (_comprisedOf.contains(event.getRightClicked())) + { + handleRightClick(event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void chunkUnload(ChunkUnloadEvent event) + { + if (_comprisedOf.stream().anyMatch(entity -> entity.getLocation().getChunk().equals(event.getChunk()))) + event.setCancelled(true); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + update(); + + CustomTick(); + } + + public Location getLocation() + { + return _location.clone(); + } + + public double getSize() + { + return _boundingBoxSize; + } + + + public int getBaseDamage() + { + return _baseDamage; + } + + public ClanInfo getOwner() + { + return _ownerClan; + } + + public ClansManager getClans() + { + return _clans; + } + + protected WeaponProjectile getProjectile() + { + return _projectile; + } + + protected int getAmmunition() + { + ItemStack item = _inventory.getItem(_ammunitionSlot); + + if (item != null && item.getType().equals(_ammunitionType)) + return item.getAmount(); + + return 0; + } + + protected int getPowerLevel() + { + int power = 0; + + for (int slot : _firepowerSlots) + { + ItemStack item = _inventory.getItem(slot); + + if (item == null || !item.getType().equals(_firepowerType)) + continue; + + power += _inventory.getItem(slot).getAmount(); + } + + return power / 4; + } + + public int getUniqueId() + { + return _uniqueId; + } + + public Player getRider() + { + return _rider; + } + + public final String getState() + { + return _currentState; + } + + public final boolean shouldSyncWithDb() + { + return _syncWithDb; + } + + public SiegeWeaponToken toToken() + { + SiegeWeaponToken token = new SiegeWeaponToken(); + + token.UniqueId = _uniqueId; + token.OwnerClan = _ownerClan; + token.WeaponType = _weaponTypeIdentifier; + token.Location = _location; + token.Health = _health; + token.Yaw = (int) _yaw; + + return token; + } + + public boolean isPartOf(UUID uniqueId) + { + for (Entity entity : _comprisedOf) + { + if (entity.getUniqueId().equals(uniqueId)) + return true; + } + + return false; + } + + public void setInvincible(boolean invincible) + { + _invincible = invincible; + } + + public boolean isInvincible() + { + return _invincible; + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/TntProjectile.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/TntProjectile.java new file mode 100644 index 000000000..e53e6abd4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/TntProjectile.java @@ -0,0 +1,63 @@ +package mineplex.game.clans.clans.siege.weapon; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.siege.weapon.projectile.WeaponProjectile; + +public class TntProjectile extends WeaponProjectile +{ + public TntProjectile(SiegeWeapon weapon, Location origin, double yawRot, double yVel, double xMulti) + { + super(weapon, origin, yawRot, yVel, xMulti); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onTntExplode(EntityExplodeEvent event) + { + if (event.getEntity().equals(_projectileEntity)) + { + ((TNTPrimed) event.getEntity()).setFuseTicks(60); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onTntExplode(UpdateEvent event) + { + if (event.getType() != UpdateType.SEC) + { + return; + } + + ((TNTPrimed) _projectileEntity).setFuseTicks(60); + } + + @Override + public Entity spawn() + { + TNTPrimed tnt = _origin.getWorld().spawn(_origin, TNTPrimed.class); + + Vector velocity = UtilAlg.getTrajectory( + _origin, + UtilAlg.moveForward( + _origin, + 2., + (float) Math.toDegrees(_yawRot), false)) + .multiply(_xMulti) + .setY(_yVel); + + tnt.setVelocity(velocity); + + return tnt; + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/Crater.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/Crater.java new file mode 100644 index 000000000..7f270cd9a --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/Crater.java @@ -0,0 +1,155 @@ +package mineplex.game.clans.clans.siege.weapon.projectile; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Chest; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; +import mineplex.game.clans.core.repository.ClanTerritory; +import net.minecraft.server.v1_8_R3.Explosion; + +public class Crater implements Listener +{ + public static final Material CHARRED_TYPE = Material.OBSIDIAN; + + private final SiegeWeapon _weapon; + private final Location _origin; + + private final long _birthTime; + + private final List _blocks; + + public Crater(SiegeWeapon weapon, WeaponProjectile projectile, Location origin) + { + _weapon = weapon; + _origin = origin; + + _birthTime = System.currentTimeMillis(); + _blocks = new ArrayList<>(); + + UtilServer.getPluginManager().registerEvents(this, _weapon.getClans().getPlugin()); + + createExplosion(); + } + + @EventHandler + public void updateEffects(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + _blocks.stream().filter(block -> block.Type == CHARRED_TYPE).forEach(block -> { + long lifetime = System.currentTimeMillis() - _birthTime; + + long max = 80000; + + if (block.Location.getBlock().getType() != CHARRED_TYPE) + { + return; + } + + // Water touching the charred blocks + if (UtilBlock.getInRadius(block.Location, 1.6).keySet().stream().filter(water -> water.getType() == Material.WATER).iterator().hasNext()) + { + return; + } + + if (lifetime < max) + { + UtilParticle.PlayParticleToAll(ParticleType.FLAME, block.Location.clone().add(.5, 1, .5), new Vector(0, 0, 0), .0f, 3, ViewDist.MAX); + UtilParticle.PlayParticleToAll(lifetime >= max / 1.4 ? ParticleType.SMOKE : ParticleType.LARGE_SMOKE, block.Location.clone().add(.5, .8, .5), new Vector(0, 0, 0), .0f, 1, ViewDist.MAX); + } + else + { + HandlerList.unregisterAll(this); + } + }); + } + + private void createExplosion() + { + ClanTerritory terr = _weapon.getClans().getClanUtility().getClaim(_origin); + + if (terr != null && !ClansManager.getInstance().getBlacklist().allowed(terr.Owner)) + { + return; + } + + boolean explosion = _origin.getWorld().createExplosion(_origin, 2.6f); + + boolean floating = _origin.distance(UtilBlock.nearestFloor(_origin)) > 0.6; + + if (explosion) + { + for (Block block : UtilBlock.getInRadius(_origin.getBlock(), 2.6f).keySet()) + { + boolean charred = false; + double dist = block.getLocation().distance(_origin); + + if (floating) + { + if (!block.getRelative(BlockFace.DOWN).getType().equals(CHARRED_TYPE) + && !block.getRelative(BlockFace.DOWN).getType().equals(Material.AIR) + && Math.random() > 0.79) + { + charred = true; + } + } + else + { + if (block.getRelative(BlockFace.UP).getType().equals(Material.AIR) + && !block.getRelative(BlockFace.DOWN).getType().equals(CHARRED_TYPE) + && !block.getRelative(BlockFace.DOWN).getType().equals(Material.AIR) + && Math.random() > 0.79) + { + charred = true; + } + } + + if (block.getType().equals(Material.SMOOTH_BRICK)) + { + charred = false; + } + + if (block.getType().equals(Material.BEDROCK)) + { + charred = false; + } + + if (charred) + { + CraterBlock charredBlock = new CraterBlock(block.getLocation(), dist, CHARRED_TYPE, (byte) 0); + + charredBlock.set(); + + _blocks.add(charredBlock); + } + } + } + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/CraterBlock.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/CraterBlock.java new file mode 100644 index 000000000..e8ff4058b --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/CraterBlock.java @@ -0,0 +1,32 @@ +package mineplex.game.clans.clans.siege.weapon.projectile; + +import org.bukkit.Location; +import org.bukkit.Material; + +public class CraterBlock +{ + public Material Type; + public byte Data; + public double DistanceToOrigin; + + public Location Location; + + public CraterBlock(Location location, double dist, Material type, byte data) + { + Location = location; + DistanceToOrigin = dist; + Type = type; + Data = data; + } + + public CraterBlock(Location location, double dist, Material type) + { + this(location, dist, type, (byte) 0); + } + + public void set() + { + Location.getBlock().setType(Type); + Location.getBlock().setData(Data); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/ProjectileType.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/ProjectileType.java new file mode 100644 index 000000000..018255e8f --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/ProjectileType.java @@ -0,0 +1,7 @@ +package mineplex.game.clans.clans.siege.weapon.projectile; + +public enum ProjectileType +{ + PRIMED_TNT, + FALLING_BLOCK; +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/WeaponProjectile.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/WeaponProjectile.java new file mode 100644 index 000000000..6ba7ae951 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/WeaponProjectile.java @@ -0,0 +1,125 @@ +package mineplex.game.clans.clans.siege.weapon.projectile; + +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.siege.events.SiegeWeaponExplodeEvent; +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; + +public abstract class WeaponProjectile implements Listener +{ + protected Location _origin; + protected Entity _projectileEntity; + + protected SiegeWeapon _weapon; + + protected double _yawRot; + protected double _xMulti; + protected double _yVel; + + protected boolean _dead; + + protected Player _shooter; + + public WeaponProjectile(SiegeWeapon weapon, Location origin, double yawRot, double yVel, double xMulti) + { + _shooter = weapon.getRider(); + _weapon = weapon; + _origin = origin; + _yawRot = yawRot; + _yVel = yVel; + _xMulti = xMulti; + + UtilServer.getPluginManager().registerEvents(this, weapon.getClans().getPlugin()); + + _projectileEntity = spawn(); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + if (_projectileEntity == null || _projectileEntity.isDead()) + { + die(); + return; + } + + if (_projectileEntity.getTicksLived() <= 10) + { + return; + } + + boolean moving = Math.abs(_projectileEntity.getVelocity().getX()) > 0.01 || Math.abs(_projectileEntity.getVelocity().getZ()) > 0.01; + + // Some rough collision detection. Not perfect, but the best I could conjure up myself. + if (!moving && !UtilBlock.boundless(_projectileEntity.getLocation(), 2)) + { + SiegeWeaponExplodeEvent newEvent = UtilServer.CallEvent(new SiegeWeaponExplodeEvent(_weapon, this)); + + if (!newEvent.isCancelled()) + { + new Crater(_weapon, this, _projectileEntity.getLocation()); + UtilServer.getServer().getOnlinePlayers().forEach(player -> player.playSound(_projectileEntity.getLocation(), Sound.EXPLODE, 1.f, 1.f)); + } + + die(); + } + } + + public boolean hasDied() + { + return _dead; + } + + public Location getLocation() + { + return _projectileEntity.getLocation(); + } + + public void setLocation(Location location) + { + _projectileEntity.teleport(location); + } + + private void die() + { + HandlerList.unregisterAll(this); + + if (_projectileEntity != null) + { + _projectileEntity.remove(); + _projectileEntity = null; + } + + _dead = true; + } + + public abstract Entity spawn(); + + public Player getShooter() + { + return _shooter; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/event/PreCraterSetBlockEvent.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/event/PreCraterSetBlockEvent.java new file mode 100644 index 000000000..81bc117fc --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/projectile/event/PreCraterSetBlockEvent.java @@ -0,0 +1,72 @@ +package mineplex.game.clans.clans.siege.weapon.projectile.event; + +import java.util.Set; + +import org.bukkit.block.Block; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import mineplex.game.clans.clans.siege.weapon.SiegeWeapon; +import mineplex.game.clans.clans.siege.weapon.projectile.Crater; +import mineplex.game.clans.clans.siege.weapon.projectile.WeaponProjectile; + +public class PreCraterSetBlockEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + private SiegeWeapon _weapon; + private WeaponProjectile _projectile; + private Set _blocks; + private Crater _crater; + + + private boolean _cancelled; + + public PreCraterSetBlockEvent(Set blocks, Crater crater, SiegeWeapon weapon, WeaponProjectile projectile) + { + _blocks = blocks; + _crater = crater; + _weapon = weapon; + _projectile = projectile; + } + + public Set getBlocks() + { + return _blocks; + } + + public Crater getCrater() + { + return _crater; + } + + public SiegeWeapon getWeapon() + { + return _weapon; + } + + public WeaponProjectile getProjectile() + { + return _projectile; + } + + public boolean isCancelled() + { + return _cancelled; + } + + public void setCancelled(boolean cancelled) + { + _cancelled = cancelled; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessRule.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessRule.java new file mode 100644 index 000000000..b1eb7b37d --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessRule.java @@ -0,0 +1,23 @@ +package mineplex.game.clans.clans.siege.weapon.util; + +import java.util.function.Predicate; + +import org.bukkit.entity.Player; + +public class AccessRule +{ + private Predicate _access; + private AccessType _type; + + public AccessRule(AccessType type, Predicate access) + { + _type = type; + _access = access; + } + + public boolean allow(AccessType type, Player player) + { + return type.equals(_type) && _access.test(player); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessType.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessType.java new file mode 100644 index 000000000..6fccb310d --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/AccessType.java @@ -0,0 +1,7 @@ +package mineplex.game.clans.clans.siege.weapon.util; + +public enum AccessType +{ + RCLICK_BB, + LCLICK_BB, +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/BarrierCollisionBox.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/BarrierCollisionBox.java new file mode 100644 index 000000000..08b28a04d --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/BarrierCollisionBox.java @@ -0,0 +1,251 @@ +package mineplex.game.clans.clans.siege.weapon.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.BiConsumer; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + +public class BarrierCollisionBox implements Listener +{ + private List _collisionBlocks; + + private List> _leftClickListeners; + private List> _rightClickListeners; + + BarrierCollisionBox() + { + _collisionBlocks = new ArrayList<>(); + + _leftClickListeners = new ArrayList<>(); + _rightClickListeners = new ArrayList<>(); + } + + BarrierCollisionBox(List locations) + { + this(); + + _collisionBlocks.addAll(locations); + } + + BarrierCollisionBox(Location start, Location end) + { + this(); + + UtilBlock.getInBoundingBox(start.getBlock().getLocation(), end.getBlock().getLocation(), false).forEach(block -> _collisionBlocks.add(block.getLocation())); + } + + public void Construct() + { + setBlocks(); + + UtilServer.RegisterEvents(this); + } + + public void Destruct() + { + HandlerList.unregisterAll(this); + + resetBlocks(); + + _leftClickListeners.clear(); + _rightClickListeners.clear(); + _collisionBlocks.clear(); + } + + public void Update() + { + setBlocks(); + } + + public void registerLeft(BiConsumer listener) + { + _leftClickListeners.add(listener); + } + + public void registerRight(BiConsumer listener) + { + _rightClickListeners.add(listener); + } + + public void unregisterLeft(BiConsumer listener) + { + _leftClickListeners.remove(listener); + } + + public void unregisterRight(BiConsumer listener) + { + _rightClickListeners.remove(listener); + } + + private void onLeftClick(Location location, Player player) + { + UtilCollections.ForEach(_leftClickListeners, listener -> listener.accept(location, player)); + } + + private void onRightClick(Location location, Player player) + { + UtilCollections.ForEach(_rightClickListeners, listener -> listener.accept(location, player)); + } + + private void resetBlocks() + { + _collisionBlocks + .stream() + .filter(location -> location.getBlock().getType().equals(Material.BARRIER)) + .forEach(location -> location.getBlock().setType(Material.AIR)); + } + + private void setBlocks() + { + for (Location location : _collisionBlocks) + { + location.getBlock().setType(Material.BARRIER); + } + } + + public boolean isInBox(Location location) + { + for (Location other : _collisionBlocks) + { + if (other.equals(location)) + { + return true; + } + } + + return false; + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() == UpdateType.FAST) + { + Update(); + } + } + + // Events for interaction with the collision box; + @EventHandler + public void blockDamage(BlockDamageEvent event) + { + if (isInBox(event.getBlock().getLocation())) + { + onLeftClick(event.getBlock().getLocation(), event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void blockBreak(BlockBreakEvent event) + { + if (isInBox(event.getBlock().getLocation())) + { + onLeftClick(event.getBlock().getLocation(), event.getPlayer()); + event.setCancelled(true); + } + } + + @EventHandler + public void interact(PlayerInteractEvent event) + { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + + if (isInBox(event.getClickedBlock().getLocation())) + { + onRightClick(event.getClickedBlock().getLocation(), event.getPlayer()); + event.setCancelled(true); + } + } + + public BarrierCollisionBox add(Location... location) + { + _collisionBlocks.addAll(Arrays.asList(location)); + + Update(); + + return this; + } + + public BarrierCollisionBox add(List location) + { + _collisionBlocks.addAll(location); + + Update(); + + return this; + } + + public BarrierCollisionBox remove(Location... location) + { + _collisionBlocks.removeAll(Arrays.asList(location)); + + Update(); + + return this; + } + + public BarrierCollisionBox add(BarrierCollisionBox box, boolean destructOld, boolean cloneListeners) + { + _collisionBlocks.addAll(box._collisionBlocks); + + if (cloneListeners) + { + _leftClickListeners.addAll(box._leftClickListeners); + _rightClickListeners.addAll(box._rightClickListeners); + } + + if (destructOld) + { + box.Destruct(); + } + + Update(); + + return this; + } + + public BarrierCollisionBox add(BarrierCollisionBox box) + { + return add(box, false, false); + } + + public BarrierCollisionBox addAll(Location start, Location end) + { + UtilBlock.getInBoundingBox(start, end).forEach(block -> _collisionBlocks.add(block.getLocation())); + + Update(); + + return this; + } + + public static BarrierCollisionBox all(Location start, Location end) + { + return new BarrierCollisionBox(start, end); + } + + public static BarrierCollisionBox single(Location location) + { + return new BarrierCollisionBox(new ArrayList<>(Arrays.asList(location.getBlock().getLocation()))); + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/WeaponStateInfo.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/WeaponStateInfo.java new file mode 100644 index 000000000..b0eae35e7 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/siege/weapon/util/WeaponStateInfo.java @@ -0,0 +1,25 @@ +package mineplex.game.clans.clans.siege.weapon.util; + +import org.bukkit.Material; + +public class WeaponStateInfo +{ + private Material _material; + private byte _data; + + public WeaponStateInfo(Material material, byte data) + { + _material = material; + _data = data; + } + + public Material getType() + { + return _material; + } + + public byte getData() + { + return _data; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckClient.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckClient.java deleted file mode 100644 index ab5a8b285..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package mineplex.game.clans.clans.stuck; - -import org.bukkit.Location; - -public class StuckClient -{ - public Location StartLoc = null; - public long UnstickStartTime = -1; - public long UnstickEndTime = -1; - - public long getTimeLeft() - { - return UnstickEndTime - System.currentTimeMillis(); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckManager.java deleted file mode 100644 index 4dd767615..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/StuckManager.java +++ /dev/null @@ -1,109 +0,0 @@ -package mineplex.game.clans.clans.stuck; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; - -import mineplex.core.MiniClientPlugin; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTextMiddle; -import mineplex.core.common.util.UtilTime; -import mineplex.core.common.util.UtilTime.TimeUnit; -import mineplex.core.recharge.Recharge; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.stuck.commands.StuckCommand; -import mineplex.game.clans.spawn.Spawn; - -public class StuckManager extends MiniClientPlugin -{ - public static final long UNSTICK_WAIT_TIME = UtilTime.convert(35, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); - - public StuckManager(ClansManager clans) - { - super("Stuck Handler", clans.getPlugin()); - } - - @Override - public void addCommands() - { - addCommand(new StuckCommand(this)); - } - - @Override - protected StuckClient AddPlayer(String player) - { - return new StuckClient(); - } - - public void unstick(Player player) - { - Get(player).UnstickStartTime = System.currentTimeMillis(); - Get(player).UnstickEndTime = Get(player).UnstickStartTime + UNSTICK_WAIT_TIME; - Get(player).StartLoc = player.getLocation(); - } - - public boolean isUnsticking(Player caller) - { - return Get(caller).UnstickStartTime != -1; - } - - @EventHandler - public void updateTeleport(UpdateEvent event) - { - if (event.getType() != UpdateType.FASTER) - { - for (Player player : Bukkit.getOnlinePlayers()) - { - if (isUnsticking(player)) - { - if (player.getLocation().distance(Get(player).StartLoc) >= 0.75) - { - cancelTeleport(player); - break; - } - - UtilTextMiddle.display("", "Teleporting to Spawn in " + F.elem(UtilTime.MakeStr(Get(player).getTimeLeft())), 0, 20, 60, player); - - if (Get(player).getTimeLeft() <= 500) - { - teleport(player); - } - } - } - } - } - - private void cancelTeleport(Player player) - { - UtilPlayer.message(player, F.main("Clans", "You have moved, and cancelled the teleport.")); - - Get(player).UnstickStartTime = -1; - Get(player).UnstickEndTime = -1; - Get(player).StartLoc = null; - } - - private void teleport(Player player) - { - Recharge.Instance.use(player, "Spawn Teleport", UtilTime.convert(15, TimeUnit.MINUTES, TimeUnit.MILLISECONDS), false, false); - - UtilPlayer.message(player, F.main("Clans", "You have been teleported to Spawn.")); - - Get(player).UnstickStartTime = -1; - Get(player).UnstickEndTime = -1; - Get(player).StartLoc = null; - - if (Math.random() < .5) - { - player.teleport(Spawn.getEastSpawn()); - } - else - { - player.teleport(Spawn.getWestSpawn()); - } - - } - -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/commands/StuckCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/commands/StuckCommand.java deleted file mode 100644 index f43064682..000000000 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/stuck/commands/StuckCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -package mineplex.game.clans.clans.stuck.commands; - -import org.bukkit.entity.Player; - -import mineplex.core.command.CommandBase; -import mineplex.core.common.Rank; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTime; -import mineplex.core.recharge.Recharge; -import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.stuck.StuckManager; - -public class StuckCommand extends CommandBase -{ - public StuckCommand(StuckManager plugin) - { - super(plugin, Rank.ALL, "spawn", "stuck", "unstick", "unstuck"); - } - - @Override - public void Execute(Player caller, String[] args) - { - if (Plugin.isUnsticking(caller)) - { - UtilPlayer.message(caller, F.main("Clans", "You are already teleporting to Spawn.")); - - return; - } - - if (!Recharge.Instance.usable(caller, "Spawn Teleport", true)) - { - return; - } - - if(ClansManager.getInstance().getClanUtility().getClaim(caller.getLocation()) != null && !ClansManager.getInstance().getClanUtility().getClaim(caller.getLocation()).Owner.equals("Borderlands") && - !ClansManager.getInstance().getClanUtility().getClaim(caller.getLocation()).Owner.equals("Shops") && !ClansManager.getInstance().getClanUtility().getClaim(caller.getLocation()).Owner.equals("Spawn")) - { - UtilPlayer.message(caller, F.main("Clans", "You must be in the Wilderness/Borderlands/Shops/Spawn to use this command.")); - - return; - } - - UtilPlayer.message(caller, F.main("Clans", "Teleporting to Spawn... Please do not move for " + F.elem(UtilTime.MakeStr(StuckManager.UNSTICK_WAIT_TIME))) + "."); - - Plugin.unstick(caller); - } -} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/supplyDrop/SupplyDropManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/supplyDrop/SupplyDropManager.java index 8380afa6e..2a0c69166 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/supplyDrop/SupplyDropManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/supplyDrop/SupplyDropManager.java @@ -140,7 +140,7 @@ public class SupplyDropManager extends MiniPlugin if (item == null) return false; - return item.getType() == SupplyDrop.SUPPLY_DROP_MATERIAL; + return item.getType() == SupplyDrop.SUPPLY_DROP_MATERIAL && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().contains("Supply"); // if (item.getType() == SUPPLY_DROP_MATERIAL) // { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGenerator.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGenerator.java index 3712896f2..c27697061 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGenerator.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGenerator.java @@ -1,16 +1,18 @@ package mineplex.game.clans.clans.tntGenerator; +import java.util.UUID; + import org.bukkit.block.Block; public class TntGenerator { - private Block _block; + private UUID _creator; private int _ticks; private int _stock; - public TntGenerator(Block block) + public TntGenerator(String data) { - _block = block; + _creator = UUID.fromString(data); } public int getTicks() @@ -38,8 +40,8 @@ public class TntGenerator _stock = stock; } - public Block getBlock() + public UUID getBuyer() { - return _block; + return _creator; } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGeneratorManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGeneratorManager.java index b6f4edf09..cf57f77d1 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGeneratorManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/tntGenerator/TntGeneratorManager.java @@ -1,40 +1,18 @@ package mineplex.game.clans.clans.tntGenerator; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; -import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; -import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; -import net.minecraft.server.v1_8_R3.TileEntityBrewingStand; - import mineplex.core.MiniPlugin; -import mineplex.core.common.util.C; -import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilTextMiddle; -import mineplex.core.common.util.UtilTime; -import mineplex.core.common.util.UtilWorld; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.event.ClanDeleteEvent; public class TntGeneratorManager extends MiniPlugin { - public static final Material GENERATOR_MATERIAL = Material.BREWING_STAND; - public static final Material GENERATOR_DROP_MATERIAL = Material.BREWING_STAND_ITEM; - public static final int SECONDS_PER_TNT = 60 * 60 * 10; // 10 Hours + public static final int SECONDS_PER_TNT = 60 * 60 * 12; // 12 Hours public static final int MAX_GENERATOR_STOCK = 3; private ClansManager _clansManager; @@ -57,26 +35,6 @@ public class TntGeneratorManager extends MiniPlugin TntGenerator generator = clanInfo.getGenerator(); if (generator != null) { - // Check that generator still exists - if (generator.getBlock().getType() != GENERATOR_MATERIAL) - { - clanInfo.setGenerator(null); - _clansManager.getClanDataAccess().updateGenerator(clanInfo, null); - continue; - } - - // Check that generator is still in clan territory - ClanInfo owner = _clansManager.getClanUtility().getOwner(generator.getBlock().getLocation()); - if (!clanInfo.equals(owner)) - { - _clansManager.messageClan(clanInfo, F.main("Clans", "Your " + F.elem("TNT Generator") + " has been destroyed due to the land no longer being claimed")); - destroyGenerator(generator); - clanInfo.setGenerator(null); - _clansManager.getClanDataAccess().updateGenerator(clanInfo, null); - continue; - } - - if (generator.getStock() >= MAX_GENERATOR_STOCK) { generator.setTicks(0); @@ -85,10 +43,9 @@ public class TntGeneratorManager extends MiniPlugin { if (generator.getTicks() >= SECONDS_PER_TNT) { - _clansManager.messageClan(clanInfo, F.main("Clans", "Your " + F.elem("TNT Generator") + " has a new TNT available")); + _clansManager.messageClan(clanInfo, F.main("Clans", "Your " + F.elem("TNT Generator") + " in the " + F.elem("PvP Shop") + " has a new TNT available")); generator.setStock(generator.getStock() + 1); generator.setTicks(0); - updateBrewingStand(generator); _clansManager.getClanDataAccess().updateGenerator(clanInfo, null); } @@ -97,202 +54,4 @@ public class TntGeneratorManager extends MiniPlugin } } } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent event) - { - if (event.getBlockPlaced().getType() == GENERATOR_MATERIAL) - { - ClanInfo clan = _clansManager.getClan(event.getPlayer()); - - if (clan == null) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "You must be in a clan to place a " + F.elem("TNT Generator"))); - event.setCancelled(true); - return; - } - - // Confirm they are placing in their own land - ClanInfo owner = _clansManager.getClanUtility().getOwner(event.getBlock().getLocation()); - if (!clan.equals(owner)) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "You must place the " + F.elem("TNT Generator") + " on your own land")); - event.setCancelled(true); - return; - } - - TntGenerator oldGenerator = clan.getGenerator(); - - if (oldGenerator != null) - { - UtilPlayer.message(event.getPlayer(), F.main("Clans", "Your clan already has a " + F.elem("TNT Generator"))); - event.setCancelled(true); - return; - } - -// event.getBlockPlaced().setType(GENERATOR_MATERIAL); - - TntGenerator generator = new TntGenerator(event.getBlock()); - clan.setGenerator(generator); - _clansManager.getClanDataAccess().updateGenerator(clan, null); - - _clansManager.messageClan(clan, F.main("Clans", F.name(event.getPlayer().getName()) + " placed a " + F.elem("TNT Generator") + " at " + F.elem(UtilWorld.blockToStrClean(event.getBlock())))); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreak(BlockBreakEvent event) - { - if (event.getBlock() != null && event.getBlock().getType() == GENERATOR_MATERIAL) - { - ClanInfo clan = getGenerator(event.getBlock()); - if (clan != null) - { - destroyGenerator(clan.getGenerator()); - clan.setGenerator(null); - _clansManager.getClanDataAccess().updateGenerator(clan, null); - _clansManager.messageClan(clan, F.main("Clans", "Your " + F.elem("TNT Generator") + " has been destroyed by " + F.elem(event.getPlayer().getName()))); - } - - clearStand(event.getBlock()); - event.getBlock().setTypeId(0); - event.setCancelled(true); - } - } - - @EventHandler - public void onInteract(final PlayerInteractEvent event) - { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && event.getClickedBlock().getType() == GENERATOR_MATERIAL) - { - ClanInfo clan = getGenerator(event.getClickedBlock()); - if (clan != null) - { - interact(clan, event.getPlayer()); - }else { //fix tnt gen issues - //Can only place one of these in a clan location. so it must be a generator - ClanInfo owner = _clansManager.getClanUtility().getOwner(event.getClickedBlock().getLocation()); - if(owner == null) return; //Wilderness - TntGenerator generator = owner.getGenerator(); - System.out.println("Unable to find generator"); - //Create generator if not exist - if(generator == null || !generator.getBlock().equals(event.getClickedBlock())) { - generator = new TntGenerator(event.getClickedBlock()); - generator.setStock(2); - clan.setGenerator(generator); - _clansManager.getClanDataAccess().updateGenerator(clan, null); - } - interact(owner, event.getPlayer()); - } - - event.setCancelled(true); - } - } - - private void interact(ClanInfo clan, Player player) { - final TntGenerator generator = clan.getGenerator(); - final int stock = generator.getStock(); - - if (stock > 0) - { - generator.setStock(stock - 1); - _clansManager.getClanDataAccess().updateGenerator(clan, new Callback() - { - @Override - public void run(Boolean data) - { - if (data) - { - updateBrewingStand(generator); - dropItem(generator.getBlock(), new ItemStack(Material.TNT)); - } - else - { - // failed - generator.setStock(stock); - } - } - }); - } - else - { - int secondLeft = SECONDS_PER_TNT - generator.getTicks(); - int msLeft = secondLeft * 1000; - UtilTextMiddle.display("", C.cRed + "Next TNT in " + C.cGold + UtilTime.convertString(msLeft, 1, UtilTime.TimeUnit.FIT), player); - } - } - - @EventHandler - public void onDelete(ClanDeleteEvent event) - { - ClanInfo clan = event.getClanInfo(); - - if (clan != null && clan.getGenerator() != null) - { - clearStand(clan.getGenerator().getBlock()); - clan.getGenerator().getBlock().setTypeId(0); - } - } - - private void dropItem(Block dropLocation, ItemStack item) - { - dropLocation.getWorld().dropItemNaturally(dropLocation.getLocation().add(0.5, 0.5, 0.5), item); - } - - public ClanInfo getGenerator(Block block) - { - for (ClanInfo clanInfo : _clansManager.getClanMap().values()) - { - TntGenerator generator = clanInfo.getGenerator(); - - if (generator != null && block.equals(generator.getBlock())) - return clanInfo; - } - - return null; - } - - private void destroyGenerator(TntGenerator generator) - { - for (int i = 0; i < generator.getStock(); i++) - { - dropItem(generator.getBlock(), new ItemStack(Material.TNT)); - } - - generator.setStock(0); - dropItem(generator.getBlock(), new ItemStack(GENERATOR_DROP_MATERIAL)); - clearStand(generator.getBlock()); - generator.getBlock().setTypeId(0); - } - - private void clearStand(Block block) - { - TileEntityBrewingStand tileEntity = (TileEntityBrewingStand)((CraftWorld)block.getWorld()).getTileEntityAt(block.getX(), block.getY(), block.getZ()); - if (tileEntity != null) - { - for (int i = 0; i < 4; i++) - { - tileEntity.setItem(i, null); - } - } - } - - private void updateBrewingStand(TntGenerator generator) - { - Block block = generator.getBlock(); - - if (block != null && block.getType() == Material.BREWING_STAND) - { - TileEntityBrewingStand tileEntity = (TileEntityBrewingStand)((CraftWorld)block.getWorld()).getTileEntityAt(block.getX(), block.getY(), block.getZ()); - for (int i = 0; i < 3; i++) - { - ItemStack item = new ItemStack(Material.TNT); - net.minecraft.server.v1_8_R3.ItemStack nmsItem = CraftItemStack.asNMSCopy(item); - - int itemSlot = i; - tileEntity.setItem(i, (generator.getStock() > i) ? nmsItem : null); - } - tileEntity.update(); - } - } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/warpoints/WarPointEvasion.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/warpoints/WarPointEvasion.java index e3f066e3c..dee5e2ac6 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/warpoints/WarPointEvasion.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/warpoints/WarPointEvasion.java @@ -3,8 +3,6 @@ package mineplex.game.clans.clans.warpoints; import com.google.common.collect.Maps; import mineplex.core.MiniPlugin; import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; @@ -12,75 +10,102 @@ import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.event.*; import org.bukkit.Bukkit; import org.bukkit.Chunk; -import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; +import java.util.Iterator; import java.util.UUID; -public class WarPointEvasion extends MiniPlugin{ +public class WarPointEvasion extends MiniPlugin +{ private HashMap _chunkCooldown; private HashMap _playerCooldown; private final long COOLDOWN_TIME = 1000 * 60 * 10; - public WarPointEvasion(JavaPlugin plugin) { + public WarPointEvasion(JavaPlugin plugin) + { super("WP Evasion", plugin); + _chunkCooldown = Maps.newHashMap(); _playerCooldown = Maps.newHashMap(); } @EventHandler - public void updateCooldown(UpdateEvent event) { + public void updateCooldown(UpdateEvent event) + { if(!event.getType().equals(UpdateType.SEC)) return; - _chunkCooldown.keySet().stream().filter(chunk -> UtilTime.elapsed(_chunkCooldown.get(chunk), COOLDOWN_TIME)).forEach(chunk -> _chunkCooldown.remove(chunk)); + for (Iterator chunkIterator = _chunkCooldown.keySet().iterator(); chunkIterator.hasNext();) + { + Chunk chunk = chunkIterator.next(); + + if (UtilTime.elapsed(_chunkCooldown.get(chunk), COOLDOWN_TIME)) + chunkIterator.remove(); + } - _playerCooldown.keySet().stream().filter(player -> UtilTime.elapsed(_playerCooldown.get(player), COOLDOWN_TIME)).forEach(player -> { - _playerCooldown.remove(player); - if(Bukkit.getOfflinePlayer(player).isOnline()) { - if(ClansManager.getInstance().getClan(Bukkit.getPlayer(player)) == null) { - Bukkit.getPlayer(player).sendMessage(F.main("Clans", "You can now create a clan.")); + + for (Iterator uuidIterator = _playerCooldown.keySet().iterator(); uuidIterator.hasNext();) + { + UUID uuid = uuidIterator.next(); + + if (UtilTime.elapsed(_playerCooldown.get(uuid), COOLDOWN_TIME)) + { + uuidIterator.remove(); + + Player player = Bukkit.getPlayer(uuid); + if (player.isOnline()) + { + if(ClansManager.getInstance().getClan(player) == null) + { + player.sendMessage(F.main("Clans", "You can now create a clan.")); + } } - } - }); + } + } } @EventHandler - public void onClaim(PlayerPreClaimTerritoryEvent event) { + public void onClaim(PlayerPreClaimTerritoryEvent event) + { Chunk chunk = event.getClaimedChunk(); - if(_chunkCooldown.containsKey(chunk)) { + + if(_chunkCooldown.containsKey(chunk)) + { event.setCancelled(true); event.getClaimer().sendMessage(F.main("Clans", "You cannot claim this chunk for another " + UtilTime.convertString(COOLDOWN_TIME - (System.currentTimeMillis() - _chunkCooldown.get(chunk)), 1, UtilTime.TimeUnit.MINUTES))); } } @EventHandler - public void onunClaim(PlayerUnClaimTerritoryEvent event) { - Chunk chunk = event.getUnClaimedChunk(); - _chunkCooldown.put(chunk, System.currentTimeMillis()); - + public void onunClaim(PlayerUnClaimTerritoryEvent event) + { + _chunkCooldown.put(event.getUnClaimedChunk(), System.currentTimeMillis()); } @EventHandler - public void onClanDisband(ClanDisbandedEvent event) { + public void onClanDisband(ClanDisbandedEvent event) + { _playerCooldown.put(event.getDisbander().getUniqueId(), System.currentTimeMillis()); } @EventHandler - public void onClanLeave(ClanLeaveEvent event) { + public void onClanLeave(ClanLeaveEvent event) + { _playerCooldown.put(event.getPlayer().getUuid(), System.currentTimeMillis()); } @EventHandler - public void onClanCreate(ClanCreatedEvent event) { + public void onClanCreate(ClanCreatedEvent event) + { if (event.getFounder() == null) return; - if (_playerCooldown.containsKey(event.getFounder().getUniqueId())) { + if (_playerCooldown.containsKey(event.getFounder().getUniqueId())) + { event.setCancelled(true); event.getFounder().sendMessage(F.main("Clans", "You cannot create a clan for another " + UtilTime.convertString(COOLDOWN_TIME - (System.currentTimeMillis() - _playerCooldown.get(event.getFounder().getUniqueId())), 1, UtilTime.TimeUnit.MINUTES))); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/EventTerrainFinder.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/EventTerrainFinder.java index ee7e6014d..4cc189f34 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/EventTerrainFinder.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/EventTerrainFinder.java @@ -1,19 +1,17 @@ package mineplex.game.clans.clans.worldevent; -import java.util.Arrays; -import java.util.HashSet; import java.util.Set; +import org.bukkit.Chunk; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import mineplex.core.common.util.EnclosedObject; import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilItem; -import mineplex.core.common.util.UtilItem.ItemCategory; import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilWorld; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.regions.ClansRegions; @@ -38,57 +36,28 @@ public class EventTerrainFinder public Location findAreaInBorderlands(World world, int size, int vert) { - int borderlandsDist = 31; - int borderlandsWidth = 47 - borderlandsDist; - - for (int i = 0; i < 20; i++) + for (int i = 0; i < 150; i++) { - int x = 0; - int z = 0; + EnclosedObject loc = new EnclosedObject<>(); - x = (borderlandsDist * 16) + (UtilMath.clamp(UtilMath.random.nextInt(borderlandsWidth), 2, borderlandsWidth - 2) * 16); - z = (borderlandsDist * 16) + (UtilMath.clamp(UtilMath.random.nextInt(borderlandsWidth), 2, borderlandsWidth - 2) * 16); - - if (UtilMath.random.nextBoolean()) + if (_clansManager.getClanUtility().getClanByClanName("Borderlands") == null) { - x = -x; - z = -z; + System.out.println("[WORLD EVENT] FATAL ERROR: CLAN BORDERLANDS NOT FOUND."); + break; } - Location loc = UtilBlock.getHighest(world, x, z).getLocation(); + _clansManager.getClanUtility().getClanByClanName("Borderlands").getClaimSet().stream().filter(claim -> Math.random() > .5).filter(claim -> Math.random() > .5).filter(claim -> Math.random() > .3).filter(claim -> Math.random() > .7).limit(1).forEach(claim -> { + Chunk chunk = UtilWorld.strToChunk(claim); + + loc.Set(UtilBlock.getHighest(chunk.getWorld(), chunk.getBlock(0, 0, 0)).getLocation()); + }); - int blocks = ((size * 2) + 1) * ((size * 2) + 1); - - boolean suitable = true; - - int liquids = 0; - for (x = -size; x < size; x++) + if (!UtilWorld.isBoxInWorldBorder(world, loc.Get().clone().subtract(size * 2, vert, size * 2), loc.Get().clone().add(size * 2, vert, size * 2))) { - for (z = -size; z < size; z++) - { - Block topBlock = loc.getWorld().getBlockAt(loc.getBlockX() + x, UtilBlock.getHighest(loc.getWorld(), loc.getBlockX() + x, loc.getBlockZ() + z, new HashSet(UtilItem.listIn(ItemCategory.BOUNDLESS))).getY(), loc.getBlockZ()); - - if (255 - topBlock.getY() < size) - { - suitable = false; - continue; - } - - if (topBlock.isLiquid()) - { - liquids++; - } - } + continue; } - if (liquids > 1 && (((double) blocks)) / ((double) liquids) > 0.25) - { - System.out.println("water bad"); - suitable = false; - } - - // If this region is not suitable, try again. - if (!suitable) + if (loc.Get() == null) { continue; } @@ -96,10 +65,10 @@ public class EventTerrainFinder System.out.println("Done finding area... [success]"); // Success - return loc; + return loc.Get(); } - System.out.println("Done finding area..."); + System.out.println("Failed to find area..."); return null; } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/WorldEventManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/WorldEventManager.java index 6db1192cd..a419b2d1c 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/WorldEventManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/WorldEventManager.java @@ -77,6 +77,19 @@ public class WorldEventManager extends MiniPlugin implements ScoreboardElement } } + public boolean isInEvent(Location location) + { + for (WorldEvent event : _runningEvents) + { + if (event.isInBounds(location)) + { + return true; + } + } + + return false; + } + @EventHandler public void update(UpdateEvent event) { @@ -124,6 +137,17 @@ public class WorldEventManager extends MiniPlugin implements ScoreboardElement } } + public void randomEvent() + { + if (_runningEvents.size() == 0) + { + if (UtilServer.getPlayers().length > 0) + { + tryStartEvent(); + } + } + } + private void tryStartEvent() { WorldEventType[] types = WorldEventType.values(); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/RandomCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/RandomCommand.java new file mode 100644 index 000000000..9fd1762b8 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/RandomCommand.java @@ -0,0 +1,28 @@ +package mineplex.game.clans.clans.worldevent.command; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.worldevent.WorldEventManager; +import mineplex.game.clans.clans.worldevent.WorldEventType; +import mineplex.minecraft.game.core.boss.WorldEvent; + +/** + * Command for spawning a random world event in the world. + */ +public class RandomCommand extends CommandBase +{ + public RandomCommand(WorldEventManager plugin) + { + super(plugin, Rank.JNR_DEV, "random", "rand"); + } + + @Override + public void Execute(Player caller, String[] args) + { + Plugin.randomEvent(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/WorldEventCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/WorldEventCommand.java index 152d6ba2c..7a830d9c6 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/WorldEventCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/command/WorldEventCommand.java @@ -10,10 +10,11 @@ public class WorldEventCommand extends MultiCommandBase { public WorldEventCommand(WorldEventManager plugin) { - super(plugin, Rank.CMOD, "worldevent", "we", "event"); + super(plugin, Rank.SNR_MODERATOR, "worldevent", "we", "event"); AddCommand(new StartCommand(Plugin)); AddCommand(new ClearCommand(Plugin)); + AddCommand(new RandomCommand(Plugin)); } @Override @@ -22,3 +23,4 @@ public class WorldEventCommand extends MultiCommandBase } } + diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/kinghill/KingHill.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/kinghill/KingHill.java index 6d08c9e19..6b14c395f 100755 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/kinghill/KingHill.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/kinghill/KingHill.java @@ -6,14 +6,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import mineplex.core.common.util.*; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilTime; -import mineplex.core.common.util.UtilWorld; import mineplex.core.scoreboard.ScoreboardManager; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansManager; @@ -184,4 +181,15 @@ public class KingHill extends WorldEvent { public int TicksOnHill; } + + @Override + public void announceStart() + { + for(Player player : UtilServer.getPlayers()) { + if(_clansManager.getTutorial().inTutorial(player)) continue; + + UtilTextMiddle.display(C.cGreen + getName(), UtilWorld.locToStrClean(getCenterLocation()), 10, 100, 40, player); + player.sendMessage(F.main("Event", F.elem(getName()) + " has started at coordinates " + F.elem(UtilWorld.locToStrClean(getCenterLocation())))); + } + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/undead/UndeadCamp.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/undead/UndeadCamp.java index a3a746469..6ccc12bfa 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/undead/UndeadCamp.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/clans/worldevent/undead/UndeadCamp.java @@ -4,22 +4,18 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import mineplex.core.common.util.*; import mineplex.game.clans.clans.ClansManager; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerInteractEvent; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilWorld; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; @@ -509,4 +505,16 @@ public class UndeadCamp extends WorldEvent } } } + + + @Override + public void announceStart() + { + for(Player player : UtilServer.getPlayers()) { + if(ClansManager.getInstance().getTutorial().inTutorial(player)) continue; + + UtilTextMiddle.display(C.cGreen + getName(), UtilWorld.locToStrClean(getCenterLocation()), 10, 100, 40, player); + player.sendMessage(F.main("Event", F.elem(getName()) + " has started at coordinates " + F.elem(UtilWorld.locToStrClean(getCenterLocation())))); + } + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/economy/GoldManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/economy/GoldManager.java index 66261b6ad..ab3a0b03c 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/economy/GoldManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/economy/GoldManager.java @@ -41,7 +41,7 @@ import mineplex.game.clans.shop.bank.BankShop; public class GoldManager extends MiniPlugin { - public static final double GEM_CONVERSION_RATE = 32; // The number of gold coins when converted from a single gem + public static final double GEM_CONVERSION_RATE = 16; // The number of gold coins when converted from a single gem public static final double DEATH_TAX = 0.04d; // Percentage of gold lost on death public static final String META_STRING = "clans.goldAmount"; @@ -217,7 +217,9 @@ public class GoldManager extends MiniPlugin public void deductGold(Callback resultCallback, Player player, int amount) { - if (amount >= 0) + if (amount == 0) + resultCallback.run(true); + if (amount > 0) _donationManager.rewardGold(resultCallback, "GoldManager", player, -amount); } @@ -236,6 +238,15 @@ public class GoldManager extends MiniPlugin public void dropGold(Location location, int amount, double velMult) { int count = amount / 1000; + + if (count > 75) + { + double x = Math.random() * 2 * Math.PI; + Vector velocity = new Vector(Math.sin(x), 0, Math.cos(x)); + dropGold(location, amount, velocity, velMult, "Gold " + 0); + return; + } + int extraGold = amount % 1000; for (int i = 0; i < count; i++) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/Gameplay.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/Gameplay.java index 3d4320ac8..8f2a72d4a 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/Gameplay.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/Gameplay.java @@ -14,7 +14,6 @@ import org.bukkit.Sound; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; import org.bukkit.entity.EntityType; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; @@ -55,9 +54,12 @@ import mineplex.core.common.util.UtilEvent; import mineplex.core.common.util.UtilEvent.ActionType; import mineplex.core.common.util.UtilGear; import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilItem; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilWorld; import mineplex.core.common.weight.Weight; import mineplex.core.common.weight.WeightSet; import mineplex.core.itemstack.ItemStackFactory; @@ -66,6 +68,8 @@ import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClansWaterPlaceEvent; +import mineplex.game.clans.clans.event.IronDoorOpenEvent; import mineplex.game.clans.core.repository.ClanTerritory; import mineplex.minecraft.game.classcombat.Class.ClientClass; import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; @@ -157,9 +161,15 @@ public class Gameplay extends MiniPlugin @EventHandler public void onBowShoot(EntityShootBowEvent event) { + if (event.isCancelled()) + { + return; + } + if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); + ClientClass playerClass = _clansManager.getClassManager().Get(player); if (!playerClass.IsGameClass(ClassType.Assassin, ClassType.Ranger)) @@ -230,7 +240,7 @@ public class Gameplay extends MiniPlugin HashSet remove = new HashSet(); for (Block cur : _bucketWater.keySet()) - if (UtilTime.elapsed(_bucketWater.get(cur), 2000)) remove.add(cur); + if (UtilTime.elapsed(_bucketWater.get(cur).longValue(), 2000)) remove.add(cur); for (Block cur : remove) _bucketWater.remove(cur); @@ -295,6 +305,61 @@ public class Gameplay extends MiniPlugin event.setCancelled(true); } + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void disableEnderChest(PlayerInteractEvent event) + { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + + if (event.getClickedBlock() == null) + { + return; + } + + if (_clansManager.getWorldEvent().isInEvent(event.getClickedBlock().getLocation())) + { + return; + } + + if (event.getClickedBlock().getType().equals(Material.ENDER_CHEST)) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not permitted to use Ender Chests.")); + event.setCancelled(true); + return; + } + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) + { + if (!_clansManager.getIncognitoManager().Get(event.getPlayer()).Status) + { + return; + } + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + + if (event.getClickedBlock() == null) + { + return; + } + + if (!event.getClickedBlock().getType().equals(Material.CHEST) + && !event.getClickedBlock().getType().equals(Material.TRAPPED_CHEST)) + { + return; + } + + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not allowed to use this whilst incognito.")); + + event.setCancelled(true); + } + /** * Disable all Piston related events in Clans * @@ -328,12 +393,27 @@ public class Gameplay extends MiniPlugin @EventHandler public void LapisPlace(BlockPlaceEvent event) { - if (event.isCancelled()) return; + if (event.isCancelled()) + { + return; + } - if (event.getBlock().getType() != Material.LAPIS_BLOCK) return; + if (event.getBlock().getType() != Material.LAPIS_BLOCK) + { + return; + } event.setCancelled(true); + ClansWaterPlaceEvent placeEvent = new ClansWaterPlaceEvent(event.getPlayer(), event.getBlock()); + + UtilServer.CallEvent(placeEvent); + + if (placeEvent.isCancelled()) + { + return; + } + UtilInv.remove(event.getPlayer(), Material.LAPIS_BLOCK, (byte) 0, 1); final Block block = event.getBlock(); @@ -395,16 +475,30 @@ public class Gameplay extends MiniPlugin @EventHandler public void IronDoor(PlayerInteractEvent event) { - if (!UtilEvent.isAction(event, ActionType.R_BLOCK)) return; + if (event.isCancelled()) + { + return; + } - if (event.getClickedBlock().getTypeId() != 71) return; + if (!UtilEvent.isAction(event, ActionType.R_BLOCK)) + { + return; + } + if (event.getClickedBlock().getTypeId() != 71) + { + return; + } + Block block = event.getClickedBlock(); // Knock if (event.isCancelled()) { - if (!Recharge.Instance.use(event.getPlayer(), "Door Knock", 500, false, false)) return; + if (!Recharge.Instance.use(event.getPlayer(), "Door Knock", 500, false, false)) + { + return; + } block.getWorld().playEffect(block.getLocation(), Effect.ZOMBIE_CHEW_WOODEN_DOOR, 0); } @@ -412,6 +506,13 @@ public class Gameplay extends MiniPlugin // Open else { + IronDoorOpenEvent customEvent = UtilServer.CallEvent(new IronDoorOpenEvent(event.getPlayer(), block)); + + if (customEvent.isCancelled()) + { + return; + } + if (block.getData() >= 8) block = block.getRelative(BlockFace.DOWN); if (block.getData() < 4) @@ -546,46 +647,50 @@ public class Gameplay extends MiniPlugin } } -// @EventHandler(priority = EventPriority.LOWEST) -// public void replantTree(BlockBreakEvent event) -// { -// final Block block = event.getBlock(); -// -// if (_clansManager.getClanUtility().getClaim(block.getLocation()) != null) -// { -// return; -// } -// -// if (!UtilItem.isLog(block.getType())) -// { -// return; -// } -// -// if (UtilItem.isLog(block.getRelative(BlockFace.DOWN).getType())) -// { -// return; -// } -// -// if (UtilItem.isLeaf(block.getRelative(BlockFace.DOWN).getType())) -// { -// return; -// } -// -// if (block.getRelative(BlockFace.DOWN).getType() != Material.DIRT && block.getRelative(BlockFace.DOWN).getType() != Material.GRASS) -// { -// return; -// } -// -// final byte data = block.getData(); -// -// UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { -// public void run() -// { -// block.setType(Material.SAPLING); -// block.setData(data); -// } -// }, 20 * 5); -// } + @EventHandler(priority = EventPriority.LOWEST) + public void replantTree(BlockBreakEvent event) + { + final Block block = event.getBlock(); + + if (_clansManager.getClanUtility().getClaim(block.getLocation()) != null) + { + return; + } + + if (!UtilItem.isLog(block.getType())) + { + return; + } + + if (UtilItem.isLog(block.getRelative(BlockFace.DOWN).getType())) + { + return; + } + + if (UtilItem.isLeaf(block.getRelative(BlockFace.DOWN).getType())) + { + return; + } + + if (block.getRelative(BlockFace.DOWN).getType() != Material.DIRT && block.getRelative(BlockFace.DOWN).getType() != Material.GRASS) + { + return; + } + + final byte data = block.getData(); + + UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { + public void run() + { + Material mat = block.getRelative(BlockFace.DOWN).getType(); + if (mat == Material.DIRT || mat == Material.GRASS) + { + block.setType(Material.SAPLING); + block.setData(data); + } + } + }, 20 * 10); + } @EventHandler public void killRain(WeatherChangeEvent event) @@ -769,12 +874,18 @@ public class Gameplay extends MiniPlugin UtilInv.Update(player); // Break - if (Math.random() > 0.85) event.getClickedBlock().setData((byte) (event.getClickedBlock().getData() + 4)); - - if (event.getClickedBlock().getData() >= 12) + if (Math.random() > 0.85) { - player.getWorld().playEffect(event.getClickedBlock().getLocation(), Effect.STEP_SOUND, 145); - event.getClickedBlock().setTypeIdAndData(0, (byte) 0, true); + byte data = event.getClickedBlock().getData(); + if (data >= 8) // Anvil has already been damaged twice + { + player.getWorld().playEffect(event.getClickedBlock().getLocation(), Effect.STEP_SOUND, 145); + event.getClickedBlock().setType(Material.AIR); + } + else + { + event.getClickedBlock().setData((byte)(data + 4)); + } } // Record diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/SafeLog.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/SafeLog.java index f07a24ea6..8d819ff9b 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/SafeLog.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/SafeLog.java @@ -1,6 +1,8 @@ package mineplex.game.clans.gameplay.safelog; +import java.io.DataInputStream; import java.io.File; +import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; @@ -15,9 +17,6 @@ import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.MiniPlugin; import mineplex.core.common.util.C; import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilFile; -import mineplex.core.common.util.UtilFile.ChunkType; -import mineplex.core.common.util.UtilFile.DataFileReader; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTextMiddle; @@ -77,10 +76,18 @@ public class SafeLog extends MiniPlugin { try { - DataFileReader reader = UtilFile.beginReading(_clansManager.UserDataDir + String.format("DEATH_%s.dat", player.getUniqueId().toString())); + DataInputStream stream = new DataInputStream(new FileInputStream(deathFile)); - final long time = (long) reader.readChunk(ChunkType.LONG); - final String killerName = (String) reader.readChunk(ChunkType.STRING); + final long time = stream.readLong(); + final int length = stream.readInt(); + final StringBuilder killerName = new StringBuilder(); + + for (int i = 0; i < length; i++) + { + killerName.append((char) stream.readByte()); + } + + stream.close(); UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { @@ -91,7 +98,6 @@ public class SafeLog extends MiniPlugin UtilTextMiddle.display("Offline Death", "Log out in a safer place next time!", 15, 80, 40, player); } }, 15); - reader.close(); deathFile.delete(); } @@ -107,9 +113,7 @@ public class SafeLog extends MiniPlugin @EventHandler(priority = EventPriority.LOWEST) public void onPlayerQuit(PlayerQuitEvent event) { - event.setQuitMessage(F.sys("Quit", event.getPlayer().getName())); - - onPlayerQuit(event.getPlayer()); + onPlayerQuit(event.getPlayer()); } @EventHandler(priority = EventPriority.HIGHEST) @@ -117,9 +121,7 @@ public class SafeLog extends MiniPlugin { if (event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getItemMeta() != null && (C.cGold + "Wind Blade").equals(event.getPlayer().getItemInHand().getItemMeta().getDisplayName())) if (event.getReason().contains("flying is not enabled")) - return; - - _flying.add(event.getPlayer().getName()); + _flying.add(event.getPlayer().getName()); } @EventHandler(priority = EventPriority.LOWEST) @@ -130,16 +132,12 @@ public class SafeLog extends MiniPlugin if (event.getReason().contains("flying is not enabled")) return; - event.setLeaveMessage(F.sys("Quit", event.getPlayer().getName())); - onPlayerQuit(event.getPlayer()); } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { - event.setJoinMessage(null); - onPlayerJoin(event.getPlayer()); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/CombatLogNPC.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/CombatLogNPC.java index c37e78a56..f83a7b0cb 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/CombatLogNPC.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/CombatLogNPC.java @@ -1,6 +1,8 @@ package mineplex.game.clans.gameplay.safelog.npc; +import java.io.DataOutputStream; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.util.List; @@ -18,9 +20,6 @@ import org.bukkit.metadata.FixedMetadataValue; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilEnt; -import mineplex.core.common.util.UtilFile; -import mineplex.core.common.util.UtilFile.ChunkType; -import mineplex.core.common.util.UtilFile.DataFileChunk; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; @@ -28,7 +27,6 @@ import mineplex.core.disguise.DisguiseManager; import mineplex.core.disguise.disguises.DisguisePlayer; import mineplex.core.hologram.Hologram; import mineplex.core.hologram.HologramManager; -import mineplex.game.clans.Clans; import mineplex.game.clans.clans.ClansManager; public class CombatLogNPC @@ -92,16 +90,20 @@ public class CombatLogNPC { killerName = ((CraftPlayer) killer).getName(); } - else if (killer != null) + else { killerName = UtilEnt.getName(killer); } - System.out.println(killerName); - try { - UtilFile.writeDataFile(new File(_userDataPath + String.format("DEATH_%s.dat", _playerInfo.getPlayerUuid())), new DataFileChunk(ChunkType.LONG, System.currentTimeMillis()), new DataFileChunk(ChunkType.STRING, killerName)); + DataOutputStream stream = new DataOutputStream(new FileOutputStream(_userDataPath + String.format("DEATH_%s.dat", _playerInfo.getPlayerUuid()))); + + stream.writeLong(System.currentTimeMillis()); + stream.writeInt(killerName.length()); + stream.writeBytes(killerName); + + stream.close(); } catch (IOException e) { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/NPCManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/NPCManager.java index 451149aad..186433d54 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/NPCManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/gameplay/safelog/npc/NPCManager.java @@ -167,7 +167,7 @@ public class NPCManager extends MiniPlugin if (event.GetDamagerPlayer(true) != null) { - ClanInfo clan = this._clansManager.getClan(event.GetDamagerPlayer(true)); + ClanInfo clan = _clansManager.getClan(event.GetDamagerPlayer(true)); if (clan != null && clan.isMember(logoutNpc.getPlayerInfo().getUniqueId())) { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/CustomItem.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/CustomItem.java index ab9a84425..d52ebc928 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/CustomItem.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/CustomItem.java @@ -1,23 +1,27 @@ package mineplex.game.clans.items; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; import java.util.UUID; -import mineplex.core.common.util.UtilInv; -import mineplex.game.clans.items.attributes.AttributeContainer; -import mineplex.game.clans.items.attributes.ItemAttribute; -import mineplex.minecraft.game.core.damage.CustomDamageEvent; - import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.items.attributes.AttributeContainer; +import mineplex.game.clans.items.attributes.ItemAttribute; +import mineplex.minecraft.game.core.damage.CustomDamageEvent; + /** * Represents a customizable wrapper for an {@link ItemStack}, enabling the * possession of special abilities, attributes, and triggers on item. @@ -48,12 +52,12 @@ public class CustomItem } protected String _displayName; - private String[] _description; - private Material _material; + protected String[] _description; + protected Material _material; - private String _uuid; + protected String _uuid; - private boolean _dullEnchantment; + protected boolean _dullEnchantment; public String OriginalOwner = null; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/GearManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/GearManager.java index 73242f881..071aebc74 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/GearManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/GearManager.java @@ -16,6 +16,9 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; @@ -29,6 +32,8 @@ import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; +import mineplex.core.common.weight.Weight; +import mineplex.core.common.weight.WeightSet; import mineplex.core.donation.DonationManager; import mineplex.core.packethandler.IPacketHandler; import mineplex.core.packethandler.PacketHandler; @@ -56,14 +61,17 @@ import mineplex.game.clans.items.attributes.weapon.JaggedAttribute; import mineplex.game.clans.items.attributes.weapon.SharpAttribute; import mineplex.game.clans.items.commands.GearCommand; import mineplex.game.clans.items.economy.GoldToken; -import mineplex.core.common.weight.Weight; -import mineplex.core.common.weight.WeightSet; import mineplex.game.clans.items.legendaries.AlligatorsTooth; +import mineplex.game.clans.items.legendaries.EnergyCrossbow; import mineplex.game.clans.items.legendaries.GiantsBroadsword; import mineplex.game.clans.items.legendaries.HyperAxe; import mineplex.game.clans.items.legendaries.LegendaryItem; import mineplex.game.clans.items.legendaries.MagneticMaul; +import mineplex.game.clans.items.legendaries.MeridianScepter; import mineplex.game.clans.items.legendaries.WindBlade; +import mineplex.game.clans.items.rares.Crossbow; +import mineplex.game.clans.items.rares.RareItem; +import mineplex.game.clans.items.rares.RunedPickaxe; import mineplex.game.clans.items.smelting.SmeltingListener; import mineplex.game.clans.items.ui.GearShop; import mineplex.serverdata.serialization.RuntimeTypeAdapterFactory; @@ -99,18 +107,21 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable // currently in Creative gamemode // Legendary generation - private WeightSet> _legendaryWeights; + public WeightSet> LegendaryWeights; + + // Rare generation + public WeightSet> RareWeights; // Weapon generation - private WeightSet _weaponTypes; + public WeightSet WeaponTypes; // Armor generation - private WeightSet _armorTypes; + public WeightSet ArmorTypes; // Attribute generation - private WeightSet> _weaponAttributes; - private WeightSet> _armorAttributes; - private WeightSet> _bowAttributes; + public WeightSet> WeaponAttributes; + public WeightSet> ArmorAttributes; + public WeightSet> BowAttributes; // Attribute Masks private EnumSet _maskAttributes; @@ -131,29 +142,32 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable // weights? _attributeWeights = new WeightSet(new Weight(3, 3), new Weight(20, 2), new Weight(77, 1)); _typeWeights = new WeightSet(new Weight(6, ItemType.LEGENDARY), - new Weight(46, ItemType.ARMOR), + new Weight(9, ItemType.RARE), + new Weight(46 - 9, ItemType.ARMOR), new Weight(25, ItemType.WEAPON), new Weight(23, ItemType.BOW)); // Weapon-based attributes - _weaponAttributes = new WeightSet>(FrostedAttribute.class, SharpAttribute.class, JaggedAttribute.class, HasteAttribute.class, FlamingAttribute.class, ConqueringAttribute.class); + WeaponAttributes = new WeightSet>(FrostedAttribute.class, SharpAttribute.class, JaggedAttribute.class, HasteAttribute.class, FlamingAttribute.class, ConqueringAttribute.class); // Armor-based attributes - _armorAttributes = new WeightSet>(SlantedAttribute.class, ReinforcedAttribute.class, ConqueringArmorAttribute.class, PaddedAttribute.class, LavaAttribute.class); + ArmorAttributes = new WeightSet>(SlantedAttribute.class, ReinforcedAttribute.class, ConqueringArmorAttribute.class, PaddedAttribute.class, LavaAttribute.class); // Bow-based attributes - _bowAttributes = new WeightSet>(HeavyArrowsAttribute.class, HuntingAttribute.class, InverseAttribute.class, LeechingAttribute.class, RecursiveAttribute.class, ScorchingAttribute.class, SlayingAttribute.class); + BowAttributes = new WeightSet>(HeavyArrowsAttribute.class, HuntingAttribute.class, InverseAttribute.class, LeechingAttribute.class, RecursiveAttribute.class, ScorchingAttribute.class, SlayingAttribute.class); // Weapon material types - _weaponTypes = new WeightSet(Material.DIAMOND_SWORD, Material.GOLD_SWORD, Material.IRON_SWORD, Material.DIAMOND_AXE, Material.GOLD_AXE, Material.IRON_AXE); + WeaponTypes = new WeightSet(Material.DIAMOND_SWORD, Material.GOLD_SWORD, Material.IRON_SWORD, Material.DIAMOND_AXE, Material.GOLD_AXE, Material.IRON_AXE); // Armor material types - _armorTypes = new WeightSet(Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS); + ArmorTypes = new WeightSet(Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS); // TODO: Initialize list of attributes and types // Initialize various LegendaryItem types - _legendaryWeights = new WeightSet>(AlligatorsTooth.class, WindBlade.class, GiantsBroadsword.class, HyperAxe.class, MagneticMaul.class); + LegendaryWeights = new WeightSet>(MeridianScepter.class, AlligatorsTooth.class, WindBlade.class, GiantsBroadsword.class, HyperAxe.class, MagneticMaul.class); + + RareWeights = new WeightSet>(RunedPickaxe.class); // TODO: Add rest of legendaries, find better way? // Register listeners @@ -163,15 +177,15 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable // Initialize attribute types factory for JSON handling of polymorphism. RuntimeTypeAdapterFactory attributeFactory = RuntimeTypeAdapterFactory.of(ItemAttribute.class); - for (Class attributeType : _armorAttributes.elements()) + for (Class attributeType : ArmorAttributes.elements()) { attributeFactory.registerSubtype(attributeType); } - for (Class attributeType : _weaponAttributes.elements()) + for (Class attributeType : WeaponAttributes.elements()) { attributeFactory.registerSubtype(attributeType); } - for (Class attributeType : _bowAttributes.elements()) + for (Class attributeType : BowAttributes.elements()) { attributeFactory.registerSubtype(attributeType); } @@ -181,8 +195,14 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable RuntimeTypeAdapterFactory customItemType = RuntimeTypeAdapterFactory.of(CustomItem.class); customItemType.registerSubtype(CustomItem.class); customItemType.registerSubtype(LegendaryItem.class); + customItemType.registerSubtype(RareItem.class); customItemType.registerSubtype(GoldToken.class); - for (Class itemType : _legendaryWeights.elements()) + for (Class itemType : LegendaryWeights.elements()) + { + customItemType.registerSubtype(itemType); + } + + for (Class itemType : RareWeights.elements()) { customItemType.registerSubtype(itemType); } @@ -262,17 +282,21 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable RareItemFactory factory = RareItemFactory.begin(itemType); - if (itemType == ItemType.LEGENDARY) + if (itemType == ItemType.RARE) { - factory.setLegendary(_legendaryWeights.generateRandom()); + factory.setRare(RareWeights.generateRandom()); + } + else if (itemType == ItemType.LEGENDARY) + { + factory.setLegendary(LegendaryWeights.generateRandom()); } else if (itemType == ItemType.ARMOR) { - factory.setType(_armorTypes.generateRandom()); + factory.setType(ArmorTypes.generateRandom()); } else if (itemType == ItemType.WEAPON) { - factory.setType(_weaponTypes.generateRandom()); + factory.setType(WeaponTypes.generateRandom()); } else if (itemType == ItemType.BOW) { @@ -323,13 +347,13 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable switch (type) { case ARMOR: - sampleAttribute = instantiate(_armorAttributes.generateRandom()); + sampleAttribute = instantiate(ArmorAttributes.generateRandom()); break; case WEAPON: - sampleAttribute = instantiate(_weaponAttributes.generateRandom()); + sampleAttribute = instantiate(WeaponAttributes.generateRandom()); break; case BOW: - sampleAttribute = instantiate(_bowAttributes.generateRandom()); + sampleAttribute = instantiate(BowAttributes.generateRandom()); break; default: break; @@ -340,6 +364,8 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable attribute = sampleAttribute; // Select valid attribute to // add } + + attempts++; } container.addAttribute(attribute); @@ -549,8 +575,9 @@ public class GearManager extends MiniPlugin implements IPacketHandler, Runnable } } - if (ci != null && _legendaryWeights.elements().contains(ci.getClass())) + if (ci != null && LegendaryWeights.elements().contains(ci.getClass())) { + lore.add(" "); lore.add(C.cWhite + "Original Owner: " + C.cYellow + (ci.OriginalOwner == null ? "You" : Bukkit.getOfflinePlayer(UUID.fromString(ci.OriginalOwner)).getName())); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ItemType.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ItemType.java index 4d854879a..bcd0f9def 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ItemType.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ItemType.java @@ -4,6 +4,8 @@ public enum ItemType { LEGENDARY, + RARE, + ARMOR, WEAPON, diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/PlayerGear.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/PlayerGear.java index a57bdc824..64fec8dcf 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/PlayerGear.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/PlayerGear.java @@ -5,6 +5,7 @@ import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; @@ -29,11 +30,11 @@ public class PlayerGear private String _playerName; // Name of player who owns the gear // Cached custom item information for player's gear - private CustomItem weapon; - private CustomItem helmet; - private CustomItem chestplate; - private CustomItem leggings; - private CustomItem boots; + private CustomItem _weapon; + private CustomItem _helmet; + private CustomItem _chestplate; + private CustomItem _leggings; + private CustomItem _boots; /** * Class constructor @@ -160,60 +161,60 @@ public class PlayerGear { ItemStack weaponItem = getPlayer().getInventory().getItemInHand(); - if (!itemsMatch(weapon, weaponItem)) + if (!itemsMatch(_weapon, weaponItem)) { - weapon = parseItem(weaponItem); + _weapon = parseItem(weaponItem); } - return weapon; + return _weapon; } public CustomItem getHelmet() { ItemStack helmetItem = getPlayer().getInventory().getHelmet(); - if (!itemsMatch(helmet, helmetItem)) + if (!itemsMatch(_helmet, helmetItem)) { - helmet = parseItem(helmetItem); + _helmet = parseItem(helmetItem); } - return helmet; + return _helmet; } public CustomItem getChestplate() { ItemStack chestplateItem = getPlayer().getInventory().getChestplate(); - if (!itemsMatch(chestplate, chestplateItem)) + if (!itemsMatch(_chestplate, chestplateItem)) { - chestplate = parseItem(chestplateItem); + _chestplate = parseItem(chestplateItem); } - return chestplate; + return _chestplate; } public CustomItem getLeggings() { ItemStack leggingsItem = getPlayer().getInventory().getLeggings(); - if (!itemsMatch(leggings, leggingsItem)) + if (!itemsMatch(_leggings, leggingsItem)) { - leggings = parseItem(leggingsItem); + _leggings = parseItem(leggingsItem); } - return leggings; + return _leggings; } public CustomItem getBoots() { ItemStack bootsItem = getPlayer().getInventory().getBoots(); - if (!itemsMatch(boots, bootsItem)) + if (!itemsMatch(_boots, bootsItem)) { - boots = parseItem(bootsItem); + _boots = parseItem(bootsItem); } - return boots; + return _boots; } /** diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/RareItemFactory.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/RareItemFactory.java index a2723f7e6..7f1af9015 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/RareItemFactory.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/RareItemFactory.java @@ -3,9 +3,9 @@ package mineplex.game.clans.items; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import mineplex.core.common.util.UtilInv; import mineplex.game.clans.items.attributes.ItemAttribute; import mineplex.game.clans.items.legendaries.LegendaryItem; +import mineplex.game.clans.items.rares.RareItem; /** * Quick little guide on how to use this thing: @@ -75,6 +75,28 @@ public class RareItemFactory return this; } + public RareItemFactory setRare(Class rare) + { + if (_itemType.equals(ItemType.RARE)) + { + try + { + _item = rare.newInstance(); + _material = _item.getMaterial(); + } + catch (InstantiationException | IllegalAccessException e) + { + e.printStackTrace(); + } + } + else + { + throw new RuntimeException("Unexpected call to setRare(RareType)"); + } + + return this; + } + public RareItemFactory setSuperPrefix(Class superPrefix) { _superPrefix = superPrefix; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/armor/ConqueringArmorAttribute.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/armor/ConqueringArmorAttribute.java index 9e47e5923..9e9596b05 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/armor/ConqueringArmorAttribute.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/armor/ConqueringArmorAttribute.java @@ -1,11 +1,10 @@ package mineplex.game.clans.items.attributes.armor; import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import mineplex.game.clans.items.attributes.AttributeType; -import mineplex.game.clans.items.attributes.ItemAttribute; import mineplex.game.clans.items.generation.ValueDistribution; // A.K.A Conquering for Armor @@ -34,6 +33,6 @@ public class ConqueringArmorAttribute extends FlatReductionAttribute @Override public boolean reducesDamage(DamageCause cause, Entity attacker) { - return attacker != null; // Reduces damage from all entities + return !(attacker instanceof Player); // Reduces damage from all entities } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/weapon/JaggedAttribute.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/weapon/JaggedAttribute.java index 3c4186d94..1b532943b 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/weapon/JaggedAttribute.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/attributes/weapon/JaggedAttribute.java @@ -3,35 +3,34 @@ package mineplex.game.clans.items.attributes.weapon; import mineplex.game.clans.items.attributes.AttackAttribute; import mineplex.game.clans.items.attributes.AttributeType; import mineplex.game.clans.items.generation.ValueDistribution; - import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; -public class JaggedAttribute extends AttackAttribute -{ - private static ValueDistribution attackGen = generateDistribution(2, 4); - - public JaggedAttribute() - { - super(AttributeType.PREFIX, attackGen.generateIntValue()); - } +public class JaggedAttribute extends AttackAttribute { + private static ValueDistribution attackGen = generateDistribution(2, 4); - @Override - public String getDisplayName() - { - return "Jagged"; - } - - @Override - public String getDescription() - { - return String.format("Every %d attacks mini-stuns enemies", getAttackLimit()); - } - - @Override - public void triggerAttack(Entity attacker, Entity defender) - { - defender.setVelocity(new Vector(0, 0, 0)); - } + public JaggedAttribute() { + super(AttributeType.PREFIX, attackGen.generateIntValue()); + } + + @Override + public String getDisplayName() { + return "Jagged"; + } + + @Override + public String getDescription() { + return String.format("Every %d attacks mini-stuns enemies", getAttackLimit()); + } + + @Override + public void triggerAttack(Entity attacker, Entity defender) { + defender.setVelocity(new Vector(0, 0, 0)); + if (defender instanceof LivingEntity) + ((LivingEntity) defender).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20, 1, false, false)); + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/EnergyCrossbow.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/EnergyCrossbow.java new file mode 100644 index 000000000..473627884 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/EnergyCrossbow.java @@ -0,0 +1,188 @@ +package mineplex.game.clans.items.legendaries; + +import java.util.HashMap; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.LineFormat; +import mineplex.core.common.util.RGBData; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilColor; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTrig; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; + +public class EnergyCrossbow extends LegendaryItem +{ + private long _lastFire = System.currentTimeMillis(); + private long _interactWait; + + private static List _preCalculatedSphere; + + { + ClansManager.getInstance().runAsync(() -> + _preCalculatedSphere = UtilTrig.GetSpherePoints(new Vector(0, 0, 0), 1.8d, 1.8d, true, .4d) + ); + } + + public EnergyCrossbow() + { + super("Energy Crossbow", UtilText.splitLinesToArray(new String[] { + C.cWhite + "Legend says " + + " ", + "#" + C.cYellow + "Right-Click" + C.cWhite + " to fire Crossbow." + }, LineFormat.LORE), Material.RECORD_6); + } + + @Override + public void update(Player wielder) + { + if ((System.currentTimeMillis() - _lastBlock) < 98 && (System.currentTimeMillis() - _interactWait) >= 98) + { + if (Recharge.Instance.use(wielder, "Crossbow", 6500, true, true)) + { + fire(wielder); + + _interactWait = System.currentTimeMillis(); + } + } + } + + private void fire(final Player player) + { + UtilServer.RegisterEvents(new Listener() { + private Location _lastLoc; + + private Arrow _arrow; + private Player _player; + + private RGBData[] colors = { UtilColor.RgbLightRed, UtilColor.RgbLightRed.Lighten(), UtilColor.RgbLightRed.Darken() }; + + { + _player = player; + + Arrow arrow = _player.shootArrow(); + + arrow.setVelocity(arrow.getVelocity().multiply(3.4444444444444)); + + arrow.setShooter(_player); + + _arrow = arrow; + + _player.playSound(_arrow.getLocation(), Sound.BAT_TAKEOFF, 0.1f, 2.f); + _player.playSound(_arrow.getLocation(), Sound.ZOMBIE_WOODBREAK, 0.5f, .5f); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (_arrow == null || _arrow.isDead()) + { + HandlerList.unregisterAll(this); + + return; + } + + if (_lastLoc != null) + { + Location lastLoc = _lastLoc.clone(); + + while (UtilMath.offset(lastLoc, _arrow.getLocation()) > 0.1) + { + lastLoc.add(UtilAlg.getTrajectory(lastLoc, _arrow.getLocation()).multiply(0.1)); + + UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, lastLoc, UtilCollections.random(colors).ToVector(), 1f, 0, ViewDist.MAX); + } + } + + _lastLoc = _arrow.getLocation(); + } + + private void hit() + { + HandlerList.unregisterAll(this); + + for (Vector vector : _preCalculatedSphere) + { + UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, _arrow.getLocation().add(vector), UtilColor.RgbLightRed.ToVector(), 1.0f, 0, ViewDist.MAX); + } + + HashMap targets = UtilEnt.getInRadius(_arrow.getLocation(), 3.d); + for (LivingEntity entity : targets.keySet()) + { + if (entity.equals(_arrow.getShooter())) + continue; + + ClansManager.getInstance().getDamageManager().NewDamageEvent(entity, _player, _arrow, + DamageCause.CUSTOM, 8, true, true, false, + _player.getName(), "Energy Crossbow"); + } + + _arrow.remove(); + _arrow = null; + } + + @EventHandler + public void projectileHit(ProjectileHitEvent event) + { + if (!event.getEntity().equals(_arrow)) + { + return; + } + + ClansManager.getInstance().runSyncLater(this::hit, 1); + } + + @EventHandler + public void entityHurt(EntityDamageByEntityEvent event) + { + if (!event.getDamager().equals(_arrow)) + { + return; + } + + if (event.getEntity().equals(_arrow.getShooter()) || !(event.getEntity() instanceof LivingEntity)) + { + _arrow.remove(); + _arrow = null; + + return; + } + + event.setCancelled(true); + + ClansManager.getInstance().getDamageManager().NewDamageEvent((LivingEntity) event.getEntity(), _player, _arrow, + DamageCause.CUSTOM, 1.5d, true, true, false, + _player.getName(), "Energy Crossbow"); + + hit(); + } + + }); + + _lastFire = System.currentTimeMillis(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/GiantsBroadsword.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/GiantsBroadsword.java index d9f71353c..746ac5312 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/GiantsBroadsword.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/GiantsBroadsword.java @@ -60,6 +60,6 @@ public class GiantsBroadsword extends LegendaryItem private void buffPlayer(Player player) { grantPotionEffect(player, PotionEffectType.SLOW, 40, SLOW_AMPLIFIER); - grantPotionEffect(player, PotionEffectType.REGENERATION, 40, REGEN_AMPLIFIER); //Regen + grantPotionEffect(player, PotionEffectType.REGENERATION, 2, REGEN_AMPLIFIER); //Regen } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/HyperAxe.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/HyperAxe.java index c9630b26c..085cc7fb4 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/HyperAxe.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/HyperAxe.java @@ -12,7 +12,7 @@ import mineplex.minecraft.game.core.damage.CustomDamageEvent; public class HyperAxe extends LegendaryItem { - public static final long ATTACK_RATE_DURATION = 200; + public static final long ATTACK_RATE_DURATION = 1000 / 10; private static ValueDistribution amountGen = generateDistribution(0, 3); // [1, 4] speed amount private static ValueDistribution durationGen = generateDistribution(80, 320); // [4, 16] seconds speed duration @@ -20,11 +20,10 @@ public class HyperAxe extends LegendaryItem private int _speedDuration; private long _lastAttack; - public long timeSinceLastAttack() { return System.currentTimeMillis() - _lastAttack; } public HyperAxe() { - super("Hyper Axe", new String[]{ + super("Hyper Axe", new String[] { C.cWhite + "Of all the weapons known to man,", C.cWhite + "none is more prevalent than the", C.cWhite + "Hyper Axe. Infused with rabbit's", @@ -43,10 +42,9 @@ public class HyperAxe extends LegendaryItem @Override public void update(Player wielder) { - if (isHoldingRightClick() && canBuff()) + if (isHoldingRightClick() && canBuff(wielder)) { buffPlayer(wielder); - _lastAttack = System.currentTimeMillis(); } } @@ -56,9 +54,9 @@ public class HyperAxe extends LegendaryItem if (timeSinceLastAttack() >= ATTACK_RATE_DURATION) { event.SetIgnoreRate(true); -// log("Ignoring rate!"); - event.AddMod("Hyper Axe", 1); + event.AddMod("Hyper Axe", 9); + _lastAttack = System.currentTimeMillis(); } else { @@ -66,18 +64,22 @@ public class HyperAxe extends LegendaryItem } } + public long timeSinceLastAttack() + { + return System.currentTimeMillis() - _lastAttack; + } + private void buffPlayer(Player wielder) { - if (!Recharge.Instance.use(wielder, "Hyper Rush", 16000, true, true)) - return; + Recharge.Instance.use(wielder, "Hyper Rush", 16000, true, false); // Give player speed buff wielder.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, _speedDuration, _speedAmount)); log("Buffing"); } - private boolean canBuff() + private boolean canBuff(Player wielder) { - return true; // TODO: Implement cooldown? (None specified in docs, sounds OP) + return Recharge.Instance.usable(wielder, "Hyper Rush", true); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/LegendaryItem.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/LegendaryItem.java index 45c32ed17..0d21efc43 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/LegendaryItem.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/LegendaryItem.java @@ -15,7 +15,7 @@ public class LegendaryItem extends CustomItem { public final long BLOCK_COOLDOWN = 200l; // Right clicking activates right click for 200ms - private long _lastBlock; // Timestamp of last block from wielder + protected long _lastBlock; // Timestamp of last block from wielder public long timeSinceLastBlock() { return System.currentTimeMillis() - _lastBlock; } public LegendaryItem(String name, String[] description, Material material) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/MeridianScepter.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/MeridianScepter.java new file mode 100644 index 000000000..61bdc4645 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/legendaries/MeridianScepter.java @@ -0,0 +1,261 @@ +package mineplex.game.clans.items.legendaries; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.LineFormat; +import mineplex.core.common.util.RGBData; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilCollections; +import mineplex.core.common.util.UtilColor; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilShapes; +import mineplex.core.common.util.UtilText; +import mineplex.core.recharge.Recharge; +import mineplex.game.clans.clans.ClansManager; + +public class MeridianScepter extends LegendaryItem +{ + private long _lastFire = System.currentTimeMillis(); + private long _interactWait; + + private RGBData[] colors = { UtilColor.RgbPurple, UtilColor.RgbPurple.Lighten(), UtilColor.RgbPurple.Darken() }; + + private int _witherDamageTimes = 5; + + public MeridianScepter() + { + super("Meridian Scepter", UtilText.splitLinesToArray(new String[] { + C.cWhite + "Legend says that this scepter was found, and retrieved from the deepest trench in all of Minecraftia. It is said that he who wields this scepter holds the power of Poseidon himself." + + " ", + "#" + C.cYellow + "Right-Click" + C.cWhite + " to use Scepter." + }, LineFormat.LORE), Material.RECORD_6); + } + + @Override + public void update(Player wielder) + { + if ((System.currentTimeMillis() - _lastBlock) < 98 && (System.currentTimeMillis() - _interactWait) >= 98) + { + if (ClansManager.getInstance().hasTimer(wielder)) + { + UtilPlayer.message(wielder, F.main("Clans", "You are not allowed to fire the Meridian Scepter whilst under pvp protection.")); + return; + } + + if (ClansManager.getInstance().getClanUtility().getClaim(wielder.getLocation()) != null && ClansManager.getInstance().getClanUtility().getClaim(wielder.getLocation()).isSafe(wielder.getLocation())) + { + UtilPlayer.message(wielder, F.main("Clans", "You are not allowed to fire the " + F.elem("Meridian Scepter") + " whilst in a safe zone.")); + return; + } + + if (Recharge.Instance.use(wielder, "Meridian Scepter", 4000, true, true)) + { + fire(wielder); + + _interactWait = System.currentTimeMillis(); + } + } + } + + private void fire(final Player shooter) + { + final Location projectile = shooter.getEyeLocation(); + final Location origin = shooter.getEyeLocation(); + final Vector direction = shooter.getEyeLocation().getDirection().normalize().multiply(0.25); + final int maxRange = 50; + final int maxDings = maxRange * 4; + + UtilServer.repeat(new BukkitRunnable() + { + private int dingsDone; + private Location previousLocation = projectile; + + private void burst() + { + for (Entity cur : projectile.getWorld().getEntities()) + { + if (cur == shooter || !(cur instanceof Player) || (cur instanceof Player && UtilPlayer.isSpectator(cur))) + continue; + + Player player = (Player) cur; + + // If they are less than 0.5 blocks away + if (player.getEyeLocation().subtract(0, .3, 0).distance(projectile) <= 2) + { + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 20 * _witherDamageTimes, 0)); + + int time = 0; + + for (int i = 0; i < _witherDamageTimes; i++) + { + UtilServer.getServer().getScheduler().scheduleSyncDelayedTask(UtilServer.getPlugin(), () -> { + ClansManager.getInstance().getDamageManager().NewDamageEvent(player, shooter, null, + DamageCause.CUSTOM, 1.75, false, true, true, + shooter.getName(), "Meridian Scepter"); + }, ++time * 20); + } + + UtilPlayer.message(player, F.main("Clans", F.elem(player.getName()) + " hit you with a " + F.elem("Meridian Scepter") + C.mBody + ".")); + UtilPlayer.message(shooter, F.main("Clans", "You hit " + F.elem(player.getName()) + " with your " + F.elem("Meridian Scepter") + C.mBody + ".")); + } + } + + playParticle(projectile, previousLocation); + + cancel(); + } + + public void run() + { + if (dingsDone >= maxDings || !shooter.isOnline()) + { + burst(); + } + else + { + for (int i = 0; i < 2; i++) + { + Player closestPlayer = null; + double dist = 0; + + for (Player closest : UtilServer.getPlayers()) + { + if (!closest.getWorld().equals(projectile.getWorld())) + { + continue; + } + + if (ClansManager.getInstance().hasTimer(closest)) + { + continue; + } + + if (ClansManager.getInstance().isInClan(shooter) && ClansManager.getInstance().getClan(shooter).isMember(closest)) + { + continue; + } + + if (shooter.getGameMode().equals(GameMode.CREATIVE) || shooter.getGameMode().equals(GameMode.SPECTATOR)) + { + continue; + } + + if (closest.getGameMode().equals(GameMode.CREATIVE) || closest.getGameMode().equals(GameMode.SPECTATOR)) + { + continue; + } + + if (ClansManager.getInstance().getIncognitoManager().Get(closest).Status) + { + continue; + } + + if (ClansManager.getInstance().isInClan(shooter) && ClansManager.getInstance().getClan(shooter).isAlly(ClansManager.getInstance().getClan(closest))) + { + continue; + } + + if (ClansManager.getInstance().getClanUtility().getClaim(closest.getLocation()) != null && ClansManager.getInstance().getClanUtility().getClaim(closest.getLocation()).isSafe(closest.getLocation())) + { + continue; + } + + Location loc = closest.getLocation(); + + if (closest != shooter) + { + double dist1 = loc.distance(origin); + if (dist1 < maxRange + 10) + { + double dist2 = projectile.distance(loc); + if (closestPlayer == null || dist2 < dist) + { + double dist3 = projectile.clone().add(direction).distance(loc); + + if (dist3 < dist2) + { + closestPlayer = closest; + dist = dist2; + } + } + } + } + } + + if (closestPlayer != null) + { + Vector newDirection = closestPlayer.getLocation().add(0, 1, 0).toVector() + .subtract(projectile.toVector()); + + direction.add(newDirection.normalize().multiply(0.01)).normalize().multiply(0.15); + } + + projectile.add(direction); + + for (Entity cur : projectile.getWorld().getEntities()) + { + if (cur == shooter || !(cur instanceof LivingEntity) + || (cur instanceof Player && UtilPlayer.isSpectator(cur))) + continue; + + LivingEntity ent = (LivingEntity) cur; + + Location eLoc = ent.getLocation(); + + // If they are less than 0.5 blocks away + if (eLoc.clone().add(0, projectile.getY() - eLoc.getY(), 0).distance(projectile) <= 0.7) + { + // If it is in their body height + if (Math.abs((eLoc.getY() + (ent.getEyeHeight() / 1.5)) - projectile.getY()) <= ent.getEyeHeight() / 2) + { + burst(); + return; + } + } + } + + if (UtilBlock.solid(projectile.getBlock())) + { + burst(); + return; + } + + playParticle(projectile, previousLocation); + previousLocation = projectile.clone(); + + dingsDone++; + } + + projectile.getWorld().playSound(projectile, Sound.BLAZE_BREATH, 0.2F, 1f); + } + } + }, 0); + } + + private void playParticle(Location start, Location end) + { + for (Location loc : UtilShapes.getLinesDistancedPoints(start, end, 0.06)) + { + UtilParticle.PlayParticleToAll(ParticleType.RED_DUST, loc, UtilCollections.random(colors).ToVector(), 1f, 0, ViewDist.LONG); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/Crossbow.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/Crossbow.java new file mode 100644 index 000000000..99b983de9 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/Crossbow.java @@ -0,0 +1,62 @@ +package mineplex.game.clans.items.rares; + +import org.bukkit.Material; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.LineFormat; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilText; +import mineplex.core.recharge.Recharge; + +public class Crossbow extends RareItem +{ + private static final Material LOADED_TYPE = Material.COMMAND_MINECART; + private static final Material UNLOADED_TYPE = Material.RECORD_6; + + private long _lastFire = System.currentTimeMillis(); + private long _interactWait; + + public Crossbow() + { + super("Crossbow", UtilText.splitLinesToArray(new String[] { + "#" + C.cYellow + "Right-Click" + C.cWhite + " to fire Crossbow." + }, LineFormat.LORE), UNLOADED_TYPE); + } + + @Override + public void update(Player wielder) + { + if (UtilInv.contains(wielder, Material.ARROW, (byte) 0, 1)) + { + wielder.getItemInHand().setType(LOADED_TYPE); + } + else + { + wielder.getItemInHand().setType(UNLOADED_TYPE); + } + + if ((System.currentTimeMillis() - _lastBlock) < 98 && (System.currentTimeMillis() - _interactWait) >= 98) + { + if (UtilInv.remove(wielder, Material.ARROW, (byte) 0, 1)) + { + if (Recharge.Instance.use(wielder, "Crossbow", 4000, true, true)) + { + fire(wielder); + + _interactWait = System.currentTimeMillis(); + } + } + } + } + + private void fire(final Player player) + { + Arrow arrow = player.shootArrow(); + + arrow.setShooter(player); + + _lastFire = System.currentTimeMillis(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RareItem.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RareItem.java new file mode 100644 index 000000000..a986b1840 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RareItem.java @@ -0,0 +1,98 @@ +package mineplex.game.clans.items.rares; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import mineplex.game.clans.items.CustomItem; +import mineplex.game.clans.items.generation.ValueDistribution; +import mineplex.minecraft.game.core.damage.CustomDamageEvent; + +public class RareItem extends CustomItem +{ + public final long BLOCK_COOLDOWN = 200l; // Right clicking activates right click for 200ms + + protected long _lastBlock; // Timestamp of last block from wielder + public long timeSinceLastBlock() { return System.currentTimeMillis() - _lastBlock; } + + public RareItem(String name, String[] description, Material material) + { + super(name, description, material); + + _lastBlock = 0l; + } + + public void update(Player wielder) + { + // Leave implementation to potential subtypes + } + + public void preUpdate(Player wielder) + { + } + + public void onAttack(CustomDamageEvent event, Player wielder) + { + // Leave implementation to potential subtypes + } + + @Override + public void onAttack(CustomDamageEvent event) + { + if (event.GetDamagerPlayer(true) != null) + { + onAttack(event, event.GetDamagerPlayer(true)); + } + + super.onAttack(event); + } + + public void onInteract(PlayerInteractEvent event) + { + Action action = event.getAction(); + + if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) + { + _lastBlock = System.currentTimeMillis(); + } + + super.onInteract(event); + } + + public boolean isHoldingRightClick() + { + return timeSinceLastBlock() <= BLOCK_COOLDOWN; + } + + protected void log(String message) + { + System.out.println("[Custom Item - " + _displayName + "] " + message); + } + + /** + * @param minValue - the minimum value for attribute value range + * @param maxValue - the maximum value for attribute value range + * @return newly instantiated {@link ValueDistribution} for attribute values in range [{@code minValue}. {@code maxValue}]. + */ + public static ValueDistribution generateDistribution(double minValue, double maxValue) + { + return new ValueDistribution(minValue, maxValue); + } + + /** + * Add a {@link PotionEffect} to {@code player} with specified {@code type}, {@code amplifier} (power) and + * {@code tickDuration} of the effect. + * @param player - the player to receive the potion effect + * @param type - the type of potion to apply + * @param tickDuration - the duration (in ticks) to apply the potion for + * @param amplifier - the amplifier (level/power, zero-based) of the potion effect + */ + public static void grantPotionEffect(Player player, PotionEffectType type, int tickDuration, int amplifier) + { + player.removePotionEffect(type); + player.addPotionEffect(new PotionEffect(type, amplifier, tickDuration)); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RunedPickaxe.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RunedPickaxe.java new file mode 100644 index 000000000..2bd901525 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/rares/RunedPickaxe.java @@ -0,0 +1,130 @@ +package mineplex.game.clans.items.rares; + +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.LineFormat; +import mineplex.core.common.util.UtilEvent; +import mineplex.core.common.util.UtilEvent.ActionType; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTextBottom; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.core.repository.ClanTerritory; +import mineplex.game.clans.items.PlayerGear; + +public class RunedPickaxe extends RareItem +{ + private long _instamineEnabled; + private boolean _enabled; + + static + { + UtilServer.RegisterEvents(new Listener() { + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + UtilServer.getPlayersCollection().forEach(player -> { + PlayerGear gear = ClansManager.getInstance().getGearManager().getPlayerGear(player); + + if (!(gear.getWeapon() instanceof RunedPickaxe)) + { + return; + } + + RunedPickaxe pick = (RunedPickaxe) gear.getWeapon(); + + if (pick._enabled && !UtilTime.elapsed(pick._instamineEnabled, 12000)) + { + UtilTextBottom.displayProgress("Instant mine", (((double) (((double) System.currentTimeMillis()) - ((double) pick._instamineEnabled))) / 12000D), null, true, player); + } + + if (pick._enabled + && (System.currentTimeMillis() - pick._instamineEnabled) >= 12000) + { + Recharge.Instance.use(player, "Instant Mine", 15 * 1000, true, true); + + pick._enabled = false; + } + }); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void blockDamage(BlockDamageEvent event) + { + PlayerGear gear = ClansManager.getInstance().getGearManager().getPlayerGear(event.getPlayer()); + + if (!(gear.getWeapon() instanceof RunedPickaxe)) + { + return; + } + + RunedPickaxe pick = (RunedPickaxe) gear.getWeapon(); + + String playerClan = ClansManager.getInstance().getClanUtility().getClanByPlayer(event.getPlayer()) == null ? null : ClansManager.getInstance().getClanUtility().getClanByPlayer(event.getPlayer()).getName(); + + ClanTerritory territory = ClansManager.getInstance().getClanUtility().getClaim(event.getBlock().getLocation()); + + if (territory != null && !territory.Owner.equals(playerClan)) + return; + + if (event.getBlock().getType() == Material.BEDROCK) + return; + + if (!UtilTime.elapsed(pick._instamineEnabled, 12000)) + { + event.getBlock().breakNaturally(); + + event.getBlock().getWorld().playEffect(event.getBlock().getLocation(), Effect.TILE_BREAK, event.getBlock().getTypeId(), 10); + + event.getPlayer().playSound(event.getBlock().getLocation(), Sound.LAVA_POP, 1.f, 1.f); + } + } + }); + } + + public RunedPickaxe() + { + super("Runed Pickaxe", UtilText.splitLinesToArray(new String[] { + "What an interesting design this pickaxe seems to have!", + C.cYellow + "Right-Click" + C.cWhite + " to use " + F.elem("Instant mine") + "." + }, LineFormat.LORE), Material.RECORD_7); + } + + public void onInteract(PlayerInteractEvent event) + { + if (!UtilEvent.isAction(event, ActionType.R)) + { + return; + } + + if (Recharge.Instance.usable(event.getPlayer(), "Instant Mine", true) && UtilTime.elapsed(_instamineEnabled, 15000)) + { + UtilTextMiddle.display("", "Instant mine enabled for " + F.elem("12 Seconds"), 20, 80, 20, event.getPlayer()); + _instamineEnabled = System.currentTimeMillis(); + _enabled = true; + } + + super.onInteract(event); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ui/GearPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ui/GearPage.java index 536c94df1..a2cc1a83f 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ui/GearPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/items/ui/GearPage.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.apache.commons.lang3.text.WordUtils; +import org.apache.commons.lang3.tuple.Triple; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; @@ -12,6 +14,7 @@ import org.bukkit.inventory.ItemStack; import mineplex.core.account.CoreClientManager; import mineplex.core.common.Pair; import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilCollections; import mineplex.core.common.util.UtilUI; import mineplex.core.donation.DonationManager; import mineplex.core.shop.item.IButton; @@ -40,13 +43,16 @@ import mineplex.game.clans.items.attributes.weapon.HasteAttribute; import mineplex.game.clans.items.attributes.weapon.JaggedAttribute; import mineplex.game.clans.items.attributes.weapon.SharpAttribute; import mineplex.game.clans.items.legendaries.AlligatorsTooth; +import mineplex.game.clans.items.legendaries.EnergyCrossbow; import mineplex.game.clans.items.legendaries.GiantsBroadsword; import mineplex.game.clans.items.legendaries.HyperAxe; import mineplex.game.clans.items.legendaries.LegendaryItem; import mineplex.game.clans.items.legendaries.MagneticMaul; +import mineplex.game.clans.items.legendaries.MeridianScepter; import mineplex.game.clans.items.legendaries.WindBlade; -import org.apache.commons.lang3.text.WordUtils; -import org.apache.commons.lang3.tuple.Triple; +import mineplex.game.clans.items.rares.Crossbow; +import mineplex.game.clans.items.rares.RareItem; +import mineplex.game.clans.items.rares.RunedPickaxe; public class GearPage extends ShopPageBase { @@ -74,6 +80,7 @@ public class GearPage extends ShopPageBase private List> _bowSuffixes; private List> _legendaryItems; + private List> _rareItems; private List _weaponTypes; private List _armorTypes; @@ -98,7 +105,9 @@ public class GearPage extends ShopPageBase } }; - _legendaryItems = Arrays.> asList(AlligatorsTooth.class, WindBlade.class, GiantsBroadsword.class, HyperAxe.class, MagneticMaul.class); + _legendaryItems = Arrays.> asList(MeridianScepter.class, AlligatorsTooth.class, WindBlade.class, GiantsBroadsword.class, HyperAxe.class, MagneticMaul.class); + + _rareItems = Arrays.> asList(RunedPickaxe.class); _armorSuperPrefixes = Arrays.> asList(LavaAttribute.class); _armorPrefixes = Arrays.> asList(PaddedAttribute.class, ReinforcedAttribute.class, SlantedAttribute.class); @@ -141,7 +150,7 @@ public class GearPage extends ShopPageBase { Triple stage2 = doStageTwo(); - if (stage2.getLeft()) + if (stage2.getLeft().booleanValue()) { return; } @@ -156,7 +165,7 @@ public class GearPage extends ShopPageBase { Triple stage3 = doStageThree(); - if (stage3.getLeft()) + if (stage3.getLeft().booleanValue()) { return; } @@ -214,8 +223,10 @@ public class GearPage extends ShopPageBase { String stageTitle; + int[] indices = UtilUI.getIndicesFor(5, 1, 1); + stageTitle = "1. Select Item Type"; - addButton(9 + 1, Material.GOLD_RECORD, 0, C.cGold + "Legendary", new IButton() + addButton(indices[0], Material.GOLD_RECORD, 0, C.cGold + "Legendary", new IButton() { public void onClick(Player player, ClickType clickType) { @@ -225,7 +236,17 @@ public class GearPage extends ShopPageBase } }, _factory != null && ItemType.LEGENDARY.equals(_factory.getItemType()), new String[] { _factory != null && ItemType.LEGENDARY.equals(_factory.getItemType()) ? C.cGreen + "Selected" : C.cRed + "Not Selected" }); - addButton(9 + 3, Material.DIAMOND_AXE, 0, C.cDAqua + "Weapon", new IButton() + addButton(indices[1], Material.RECORD_8, 0, C.cAqua + "Rare", new IButton() + { + public void onClick(Player player, ClickType clickType) + { + _factory = RareItemFactory.begin(ItemType.RARE); + performNext(); + buildPage(); + } + }, _factory != null && ItemType.RARE.equals(_factory.getItemType()), new String[] { _factory != null && ItemType.RARE.equals(_factory.getItemType()) ? C.cGreen + "Selected" : C.cRed + "Not Selected" }); + + addButton(indices[2], Material.DIAMOND_SWORD, 0, C.cDGreen + "Weapon", new IButton() { public void onClick(Player player, ClickType clickType) { @@ -233,9 +254,9 @@ public class GearPage extends ShopPageBase performNext(); buildPage(); } - }, _factory != null && ItemType.WEAPON.equals(_factory.getItemType()), new String[] { _factory != null && ItemType.WEAPON.equals(_factory.getItemType()) ? C.cGreen + "Selected" : C.cRed + "Not Selected" }); + }, _factory != null && ItemType.RARE.equals(_factory.getItemType()), new String[] { _factory != null && ItemType.RARE.equals(_factory.getItemType()) ? C.cGreen + "Selected" : C.cRed + "Not Selected" }); - addButton(9 + 5, Material.DIAMOND_CHESTPLATE, 0, C.cDGreen + "Armor", new IButton() + addButton(indices[3], Material.DIAMOND_CHESTPLATE, 0, C.cDGreen + "Armor", new IButton() { public void onClick(Player player, ClickType clickType) { @@ -245,7 +266,7 @@ public class GearPage extends ShopPageBase } }, _factory != null && ItemType.ARMOR.equals(_factory.getItemType()), new String[] { _factory != null && ItemType.ARMOR.equals(_factory.getItemType()) ? C.cGreen + "Selected" : C.cRed + "Not Selected" }); - addButton(9 + 7, Material.BOW, 0, C.cDGreen + "Bow", new IButton() + addButton(indices[4], Material.BOW, 0, C.cDGreen + "Bow", new IButton() { public void onClick(Player player, ClickType clickType) { @@ -262,15 +283,47 @@ public class GearPage extends ShopPageBase { String stageTitle = "Fatal Error"; Material stageMaterial = null; - boolean _return = false; + boolean $return = false; if (_factory == null || _factory.getItemType() == null) { performBack(); - return Triple.of(true, stageTitle, stageMaterial); + return Triple.of(Boolean.valueOf(true), stageTitle, stageMaterial); } - if (_factory.getItemType().equals(ItemType.LEGENDARY)) + if (_factory.getItemType().equals(ItemType.RARE)) + { + stageTitle = "2. Select Rare Item"; + stageMaterial = _factory.getMaterial() == null ? stageMaterial : _factory.getMaterial(); + + int[] indices = UtilUI.getIndicesFor(_rareItems.size(), 1); + + int index = 0; + for (final Class rare : _rareItems) + { + final RareItem item = rare.newInstance(); + + List lore = new ArrayList<>(); + + lore.addAll(UtilCollections.toList(item.getDescription())); + + lore.add(" "); + lore.add(item.getDisplayName().equals(_factory.getWrapper() == null ? null : _factory.getWrapper().getDisplayName()) ? C.cGreen + "Selected" : C.cRed + "Not Selected"); + + addButton(indices[index], item.toItemStack().getType(), 0, C.cAqua + item.getDisplayName(), new IButton() + { + public void onClick(Player player, ClickType clickType) + { + _factory.setRare(rare); + performNext(); + buildPage(); + } + }, item.getDisplayName().equals(_factory.getWrapper() == null ? null : _factory.getWrapper().getDisplayName()), lore.toArray(new String[lore.size()])); + + index++; + } + } + else if (_factory.getItemType().equals(ItemType.LEGENDARY)) { stageTitle = "2. Select Legendary Item"; stageMaterial = _factory.getMaterial() == null ? stageMaterial : _factory.getMaterial(); @@ -369,13 +422,13 @@ public class GearPage extends ShopPageBase _factory.setType(Material.BOW); _stage = 2; buildPage(); - _return = true; + $return = true; break; } } } - return Triple.of(_return, stageTitle, stageMaterial); + return Triple.of(Boolean.valueOf($return), stageTitle, stageMaterial); } private Triple doStageThree() throws InstantiationException, IllegalAccessException @@ -385,12 +438,12 @@ public class GearPage extends ShopPageBase if (_factory.getMaterial() == null) { performBack(); - return Triple.of(true, null, null); + return Triple.of(Boolean.valueOf(true), null, null); } Material stageMaterial = _factory.getMaterial(); - if (_factory.getItemType().equals(ItemType.LEGENDARY)) + if (_factory.getItemType().equals(ItemType.LEGENDARY) || _factory.getItemType().equals(ItemType.RARE)) { finish(); stageTitle = "The End"; @@ -481,7 +534,7 @@ public class GearPage extends ShopPageBase } } - return Triple.of(false, stageTitle, stageMaterial); + return Triple.of(Boolean.valueOf(false), stageTitle, stageMaterial); } private Pair doStageFour() throws InstantiationException, IllegalAccessException diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/Tutorial.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/Tutorial.java similarity index 96% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/Tutorial.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/Tutorial.java index ac0f637e4..b3221c89f 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/Tutorial.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/Tutorial.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials; +package mineplex.game.clans.legacytutorial; import java.util.ArrayList; import java.util.Iterator; @@ -30,6 +30,7 @@ import mineplex.core.common.util.F; import mineplex.core.common.util.UtilFirework; import mineplex.core.common.util.UtilInv; import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.donation.DonationManager; @@ -60,9 +61,6 @@ public abstract class Tutorial implements ScoreboardElement, Listener public static String TUTORIAL_REWARD_TASK = "tatatatatat%sRewardGiven"; //do not change public static String SKIPPED_TASK = "tatatatata%sSkip"; - public static String AllowedMessage = C.cGold + "TutorialAllowedMessage" + C.Reset; - public static String AllowedBypass = C.cBlue + "Tutorial>"; - protected final TutorialManager _manager; protected final GoldManager _goldManager; protected final ClansManager _clansManager; @@ -307,7 +305,7 @@ public abstract class Tutorial implements ScoreboardElement, Listener if (_goldReward != -1) { _goldManager.addGold(player, _goldReward); - _manager.sendTutorialMsg(player, F.main("Tutorials", "You have been awarded " + F.elem(_goldReward + " Gold") + ".")); + UtilPlayer.message(player, F.main("Tutorials", "You have been awarded " + F.elem(_goldReward + " Gold") + ".")); } if (_gemReward != -1) @@ -315,7 +313,7 @@ public abstract class Tutorial implements ScoreboardElement, Listener _donationManager.RewardGems(new Callback() { public void run(Boolean data) { - _manager.sendTutorialMsg(player, F.main("Tutorials", "You have been awarded " + F.elem(_goldReward + " Gems") + ".")); + UtilPlayer.message(player, F.main("Tutorials", "You have been awarded " + F.elem(_goldReward + " Gems") + ".")); } }, "Clans", player.getName(), player.getUniqueId(), _gemReward); } @@ -325,7 +323,7 @@ public abstract class Tutorial implements ScoreboardElement, Listener _donationManager.RewardCoins(new Callback() { public void run(Boolean data) { - _manager.sendTutorialMsg(player, F.main("Tutorials", "You have been awarded " + F.elem(_coinReward + " Coins") + ".")); + UtilPlayer.message(player, F.main("Tutorials", "You have been awarded " + F.elem(_coinReward + " Coins") + ".")); } }, "Clans", player.getName(), _clansManager.getClientManager().getAccountId(player), _coinReward); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialClient.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialClient.java similarity index 92% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialClient.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialClient.java index ac44d52a1..a73f4fdd6 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialClient.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialClient.java @@ -1,9 +1,7 @@ -package mineplex.game.clans.tutorials; +package mineplex.game.clans.legacytutorial; import org.bukkit.entity.Player; -import mineplex.core.task.TaskManager; - public class TutorialClient { public Player Player; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialManager.java similarity index 75% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialManager.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialManager.java index 02bcc6899..56142641d 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialManager.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialManager.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials; +package mineplex.game.clans.legacytutorial; import java.util.HashMap; import java.util.LinkedList; @@ -11,6 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin; import mineplex.core.MiniPlugin; import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.donation.DonationManager; import mineplex.core.packethandler.IPacketHandler; import mineplex.core.packethandler.PacketHandler; @@ -21,9 +22,8 @@ import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.commands.RestartTutCommand; import mineplex.game.clans.clans.playtime.Playtime; import mineplex.game.clans.economy.GoldManager; -import mineplex.game.clans.tutorials.commands.DoSkipTutorialCommand; -import mineplex.game.clans.tutorials.commands.SkipTutorialCommand; -import mineplex.game.clans.tutorials.gettingstarted.TutorialGettingStarted; +import mineplex.game.clans.legacytutorial.commands.DoSkipTutorialCommand; +import mineplex.game.clans.legacytutorial.commands.SkipTutorialCommand; import net.md_5.bungee.api.ChatColor; import net.minecraft.server.v1_8_R3.PacketPlayOutChat; @@ -45,36 +45,6 @@ public class TutorialManager extends MiniPlugin _taskManager = taskManager; // _tutorials.put(TutorialGettingStarted.class, new TutorialGettingStarted(this, playtime, clansManager, donationManager, goldManager, taskManager, packetHandler)); - - packetHandler.addPacketHandler(new IPacketHandler() { - public void handle(PacketInfo packet) - { - if (packet.getPacket() instanceof PacketPlayOutChat) - { - PacketPlayOutChat chat = (PacketPlayOutChat) packet.getPacket(); - - if (chat.b == 1) - { - if (chat.a.a().isEmpty()) - { - return; - } - - if (chat.a.a().get(0).c().equals(ChatColor.stripColor(Tutorial.AllowedMessage))) - { - chat.a.a().remove(0); - } - else if (!chat.a.a().get(0).c().contains(Tutorial.AllowedBypass)) - { - if (isInTutorial(packet.getPlayer())) - { - packet.setCancelled(true); - } - } - } - } - } - }, PacketPlayOutChat.class); } public void addCommands() @@ -112,8 +82,7 @@ public class TutorialManager extends MiniPlugin { getTutorial(player).cancelFor(player); - - sendTutorialMsg(player, F.main("Tutorials", "You have cancelled the " + F.elem(getTutorial(player)._displayName + " Tutorial") + ".")); + UtilPlayer.message(player, F.main("Tutorials", "You have cancelled the " + F.elem(getTutorial(player)._displayName + " Tutorial") + ".")); _playerTutorials.remove(player.getName()); } } @@ -130,7 +99,7 @@ public class TutorialManager extends MiniPlugin { if (isInTutorial(player)) { - sendTutorialMsg(player, F.main("Tutorials", "You have skipped the " + F.elem(getTutorial(player)._displayName + " Tutorial") + ".")); + UtilPlayer.message(player, F.main("Tutorials", "You have skipped the " + F.elem(getTutorial(player)._displayName + " Tutorial") + ".")); getTutorial(player).doSkip(player); } } @@ -147,19 +116,6 @@ public class TutorialManager extends MiniPlugin _playerTutorials.remove(event.getPlayer().getName()); } - public void sendTutorialMsg(Player player, String message) - { - player.sendMessage(Tutorial.AllowedMessage + message); - } - - public void sendTutorialMsg(Player player, LinkedList messages) - { - for (String message : messages) - { - sendTutorialMsg(player, message); - } - } - public void finishTutorial(Player player) { _playerTutorials.remove(player.getName()); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialTask.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialTask.java similarity index 80% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialTask.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialTask.java index 6b4d2a332..15598cd14 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/TutorialTask.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/TutorialTask.java @@ -1,15 +1,15 @@ -package mineplex.game.clans.tutorials; +package mineplex.game.clans.legacytutorial; import java.util.Iterator; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import mineplex.core.common.util.C; import mineplex.core.common.util.NautArrayList; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilText; import mineplex.core.common.util.UtilTextMiddle; @@ -156,15 +156,15 @@ public class TutorialTask implements Listener if (clan != null) description = description.replace("(clan)", clan.getName()); description = description.replace("{", C.cAqua).replace("}", C.cWhite); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cYellowB + "Part " + (_id + 1) + ": " + _displayName); - _tutorial._manager.sendTutorialMsg(player, C.cWhite + " " + description); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cYellowB + "Part " + (_id + 1) + ": " + _displayName); + UtilPlayer.message(player, C.cWhite + " " + description); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); UtilTextMiddle.display("", getDisplayName(), player); @@ -239,14 +239,14 @@ public class TutorialTask implements Listener if (clan != null) finishMessage = finishMessage.replace("(clan)", clan.getName()); finishMessage = finishMessage.replace("{", C.cAqua).replace("}", C.cWhite); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cWhite + finishMessage); - _tutorial._manager.sendTutorialMsg(player, " "); - _tutorial._manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cWhite + finishMessage); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/DoSkipTutorialCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/DoSkipTutorialCommand.java similarity index 85% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/DoSkipTutorialCommand.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/DoSkipTutorialCommand.java index 2d9025081..599a875c5 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/DoSkipTutorialCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/DoSkipTutorialCommand.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.commands; +package mineplex.game.clans.legacytutorial.commands; import org.bukkit.entity.Player; @@ -6,7 +6,7 @@ import mineplex.core.command.CommandBase; import mineplex.core.common.Rank; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; -import mineplex.game.clans.tutorials.TutorialManager; +import mineplex.game.clans.legacytutorial.TutorialManager; public class DoSkipTutorialCommand extends CommandBase { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/SkipTutorialCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/SkipTutorialCommand.java similarity index 73% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/SkipTutorialCommand.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/SkipTutorialCommand.java index 87caf4ce3..2a8b36d20 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/commands/SkipTutorialCommand.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/commands/SkipTutorialCommand.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.commands; +package mineplex.game.clans.legacytutorial.commands; import org.bukkit.entity.Player; @@ -6,7 +6,7 @@ import mineplex.core.command.CommandBase; import mineplex.core.common.Rank; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilPlayer; -import mineplex.game.clans.tutorials.TutorialManager; +import mineplex.game.clans.legacytutorial.TutorialManager; public class SkipTutorialCommand extends CommandBase { @@ -24,7 +24,7 @@ public class SkipTutorialCommand extends CommandBase } else { - Plugin.sendTutorialMsg(caller, F.main("Tutorials", "You are not currently in a tutorial.")); + UtilPlayer.message(caller, F.main("Tutorials", "You are not currently in a tutorial.")); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskClaim.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskClaim.java similarity index 87% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskClaim.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskClaim.java index 23edfed24..c0b966649 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskClaim.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskClaim.java @@ -1,12 +1,11 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; import mineplex.game.clans.clans.event.PlayerPreClaimTerritoryEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskClaim extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCreateClan.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCreateClan.java similarity index 91% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCreateClan.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCreateClan.java index 26cb07f65..97cfa9ba2 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCreateClan.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCreateClan.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -6,7 +6,7 @@ import org.bukkit.event.EventPriority; import mineplex.core.common.util.UtilServer; import mineplex.game.clans.clans.event.ClanCreatedEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskCreateClan extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCustomizeClass.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCustomizeClass.java similarity index 93% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCustomizeClass.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCustomizeClass.java index 91f065320..c591dae4f 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskCustomizeClass.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskCustomizeClass.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import java.util.Iterator; @@ -12,7 +12,7 @@ import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; import mineplex.minecraft.game.classcombat.Class.ClientClass; public class TaskCustomizeClass extends TutorialTask diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskDisbandClan.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskDisbandClan.java similarity index 86% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskDisbandClan.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskDisbandClan.java index a294434cb..8fbc07f2c 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskDisbandClan.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskDisbandClan.java @@ -1,11 +1,10 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; -import mineplex.core.common.util.UtilServer; import mineplex.game.clans.clans.event.ClanDisbandedEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskDisbandClan extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskEquipClass.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskEquipClass.java similarity index 96% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskEquipClass.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskEquipClass.java index 458e04bb4..a2896c445 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskEquipClass.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskEquipClass.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.Location; import org.bukkit.Material; @@ -13,7 +13,7 @@ import mineplex.core.task.TaskManager; import mineplex.game.clans.clans.event.ClansPlayerBuyItemEvent; import mineplex.game.clans.clans.event.ClansShopAddButtonEvent; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; import mineplex.minecraft.game.classcombat.Class.event.ClassEquipEvent; public class TaskEquipClass extends TutorialTask diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskExploreShops.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskExploreShops.java similarity index 95% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskExploreShops.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskExploreShops.java index d34c2129e..eb4b8cb6b 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskExploreShops.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskExploreShops.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import java.util.Iterator; @@ -12,7 +12,7 @@ import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.event.EnergyPageBuildEvent; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskExploreShops extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskLeaveSpawn.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskLeaveSpawn.java similarity index 90% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskLeaveSpawn.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskLeaveSpawn.java index 5f0f7926c..5a812ce65 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskLeaveSpawn.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskLeaveSpawn.java @@ -1,16 +1,14 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import java.util.Iterator; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskLeaveSpawn extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskMakingMoney.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskMakingMoney.java similarity index 92% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskMakingMoney.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskMakingMoney.java index 6ff1d9b4e..7b33cd35a 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskMakingMoney.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskMakingMoney.java @@ -1,4 +1,4 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.Location; import org.bukkit.Material; @@ -7,10 +7,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.inventory.ItemStack; -import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.event.ClansPlayerSellItemEvent; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskMakingMoney extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskSetHome.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskSetHome.java similarity index 90% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskSetHome.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskSetHome.java index ca14eaf8c..42a185e30 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskSetHome.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskSetHome.java @@ -1,11 +1,11 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskSetHome extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskUseAbility.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskUseAbility.java similarity index 90% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskUseAbility.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskUseAbility.java index c94324660..6c180ae03 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskUseAbility.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskUseAbility.java @@ -1,8 +1,6 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; -import java.util.ArrayList; import java.util.Iterator; -import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -10,25 +8,20 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; -import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.CraftingInventory; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; import mineplex.core.common.util.Callback; import mineplex.core.common.util.NautArrayList; import mineplex.core.common.util.NautHashMap; -import mineplex.core.common.util.UtilServer; import mineplex.core.task.TaskManager; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.event.ClansPlayerBuyItemEvent; import mineplex.game.clans.clans.event.ClansShopAddButtonEvent; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.TutorialTask; -import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskUseAbility extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskViewClanDetails.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskViewClanDetails.java similarity index 89% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskViewClanDetails.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskViewClanDetails.java index 9ece47104..d0af8ac05 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskViewClanDetails.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskViewClanDetails.java @@ -1,10 +1,10 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskViewClanDetails extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskWelcome.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskWelcome.java similarity index 84% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskWelcome.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskWelcome.java index 9b058b619..1100966bc 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TaskWelcome.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TaskWelcome.java @@ -1,6 +1,6 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; -import mineplex.game.clans.tutorials.TutorialTask; +import mineplex.game.clans.legacytutorial.TutorialTask; public class TaskWelcome extends TutorialTask { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TutorialGettingStarted.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TutorialGettingStarted.java similarity index 65% rename from Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TutorialGettingStarted.java rename to Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TutorialGettingStarted.java index 6e924c468..99c2cb4e5 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorials/gettingstarted/TutorialGettingStarted.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/legacytutorial/gettingstarted/TutorialGettingStarted.java @@ -1,10 +1,11 @@ -package mineplex.game.clans.tutorials.gettingstarted; +package mineplex.game.clans.legacytutorial.gettingstarted; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.donation.DonationManager; import mineplex.core.packethandler.PacketHandler; @@ -14,9 +15,9 @@ import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.playtime.Playtime; import mineplex.game.clans.economy.GoldManager; +import mineplex.game.clans.legacytutorial.Tutorial; +import mineplex.game.clans.legacytutorial.TutorialManager; import mineplex.game.clans.spawn.Spawn; -import mineplex.game.clans.tutorials.Tutorial; -import mineplex.game.clans.tutorials.TutorialManager; public class TutorialGettingStarted extends Tutorial { @@ -52,34 +53,34 @@ public class TutorialGettingStarted extends Tutorial public void onFinished(final Player player) { player.resetPlayerTime(); - player.teleport(Spawn.getEastSpawn()); + player.teleport(Spawn.getNorthSpawn()); } @Override protected void onFinishedDelay(Player player) { - _manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); - _manager.sendTutorialMsg(player, C.cYellowB + "CONGRATULATIONS"); - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, C.cWhite + "You have completed the Clans basic tutorial and have been awarded " + C.cAqua + "30,000 Gold"); - _manager.sendTutorialMsg(player, C.cWhite + "You can now begin your adventure, but do take a moment to read the signs around spawn for more information!"); - _manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, C.cYellowB + "CONGRATULATIONS"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cWhite + "You have completed the Clans basic tutorial and have been awarded " + C.cAqua + "30,000 Gold"); + UtilPlayer.message(player, C.cWhite + "You can now begin your adventure, but do take a moment to read the signs around spawn for more information!"); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); } @Override public void onBegin(final Player player) { - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, C.cYellowB + "Getting Started"); - _manager.sendTutorialMsg(player, C.cWhite + " Welcome to Clans! " + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cYellowB + "Getting Started"); + UtilPlayer.message(player, C.cWhite + " Welcome to Clans! " + "In this game mode you are able to create a clan, invite your friends to play with you, build a base, and wage war against others! " + "When you finish the tutorial, you will be awarded " + C.cAqua + "30,000 Gold"); - _manager.sendTutorialMsg(player, " "); - _manager.sendTutorialMsg(player, C.cDGreenB + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, " "); + UtilPlayer.message(player, C.cDGreenB + C.Strike + "---------------------------------------------"); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/ClansMessageManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/ClansMessageManager.java new file mode 100644 index 000000000..ac9a0332f --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/ClansMessageManager.java @@ -0,0 +1,65 @@ +package mineplex.game.clans.message; + +import java.util.HashMap; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniPlugin; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; + +public class ClansMessageManager extends MiniPlugin +{ + private static final Message BLANK_MESSAGE = new Message("", "", 20); + + private HashMap _playerMessageMap; + + public ClansMessageManager(JavaPlugin plugin) + { + super("Message", plugin); + + _playerMessageMap = new HashMap<>(); + } + + @EventHandler + public void tick(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + _playerMessageMap.forEach((player, message) ->{ + message.increment(); + if (message.shouldSend()) + { + message.send(player); + } + }); + } + + public void setMessage(Player player, String title, String description, int ticksBetween, boolean displayNow) + { + Message message = new Message(title, description, ticksBetween); + _playerMessageMap.put(player, message); + if (displayNow) message.send(player); + } + + public void removePlayer(Player player) + { + removePlayer(player, true); + } + + public void removePlayer(Player player, boolean sendBlankMessage) + { + BLANK_MESSAGE.send(player); + _playerMessageMap.remove(player); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) + { + removePlayer(event.getPlayer(), false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/Message.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/Message.java new file mode 100644 index 000000000..56910d733 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/message/Message.java @@ -0,0 +1,47 @@ +package mineplex.game.clans.message; + +import org.bukkit.entity.Player; + +import mineplex.core.common.util.UtilTextMiddle; + +public class Message +{ + private int _ticksBetweenMessage; + private int _ticks; + + private String _title; + private String _description; + + public Message(String title, String description, int ticksBetweenMessage) + { + _title = title; + _description = description; + _ticksBetweenMessage = ticksBetweenMessage; + _ticks = 0; + } + + protected void send(Player player) + { + UtilTextMiddle.display(_title, _description, player); + } + + public int getTicks() + { + return _ticks; + } + + public int getTicksBetweenMessage() + { + return _ticksBetweenMessage; + } + + public void increment() + { + _ticks++; + } + + public boolean shouldSend() + { + return _ticks % _ticksBetweenMessage == 0; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopItem.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopItem.java index 71edd59bf..3ba9eaff8 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopItem.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopItem.java @@ -3,6 +3,8 @@ package mineplex.game.clans.shop; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import mineplex.core.common.util.C; + public enum ClansShopItem { // PvP Shop @@ -75,7 +77,9 @@ public enum ClansShopItem NETHER_BRICK(50, 10, Material.NETHER_BRICK, 1), QUARTZ_BLOCK(75, 15, Material.QUARTZ_BLOCK, 1), CLAY(30, 6, Material.CLAY, 1), - GOLD_TOKEN(50000, 50000, Material.GOLD_RECORD, 1, (byte) 0, "Gold Token"); + GOLD_TOKEN(50000, 50000, Material.GOLD_RECORD, 1, (byte) 0, "Gold Token"), + OUTPOST(100000, 0, Material.BEACON, 1, (byte) 0, C.cBlue + "Outpost"), + CANNON(50000, 0, Material.SPONGE, 1, (byte) 1, C.cBlue + "Cannon"); private int _buyPrice; private int _sellPrice; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopPage.java index 459a18701..f32673b0e 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ClansShopPage.java @@ -86,12 +86,12 @@ public abstract class ClansShopPage> extends Sh public void addShopItem(int index, ClansShopItem item, String displayName) { - addShopItem(index, item, (byte) 0, displayName, 1); + addShopItem(index, item, (byte) item.getData(), displayName, 1); } public void addShopItem(int index, ClansShopItem item) { - addShopItem(index, item, (byte) 0); + addShopItem(index, item, (byte) item.getData()); } public void addShopItem(int index, ClansShopItem item, byte data) diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/PvpItem.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/PvpItem.java index 1dd6c2183..a62f2ad89 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/PvpItem.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/PvpItem.java @@ -29,7 +29,7 @@ public class PvpItem extends ShopItem super(type, data, name, new String[] { C.cWhite + " ", LEFT_CLICK_BUY, - C.cWhite + "Costs " + C.cGreen + (buyPrice == 0 ? "Free" : buyPrice + "g"), + C.cWhite + "Costs " + C.cGreen + (buyPrice == 0 ? "Free (Tutorial)" : buyPrice + "g"), C.cWhite + " ", UtilItem.isArmor(type) || UtilItem.isTool(type) ? "" : C.cYellow + "Shift Left-Click" + C.cWhite + " to Buy " + C.cGreen + bulkCount, UtilItem.isArmor(type) || UtilItem.isTool(type) ? "" : C.cWhite + "Costs " + C.cGreen + (buyPrice * bulkCount) + "g", C.cWhite + " ", diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ShopItemButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ShopItemButton.java index 5b879737a..9ea38cf70 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ShopItemButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/ShopItemButton.java @@ -133,6 +133,8 @@ public class ShopItemButton> implements IButton GoldManager.notify(player, "You cannot afford that item! Please relog to update your gold count."); _page.playDenySound(player); } + + _page.refresh(); } }, player, cost); } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/energy/EnergyShopButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/energy/EnergyShopButton.java index cd548e9fe..fb2550d38 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/energy/EnergyShopButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/energy/EnergyShopButton.java @@ -1,22 +1,16 @@ package mineplex.game.clans.shop.energy; -import org.bukkit.Bukkit; -import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import mineplex.core.common.CurrencyType; -import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilTime; -import mineplex.core.donation.DonationManager; -import mineplex.core.energy.Energy; -import mineplex.core.shop.ShopBase; +import mineplex.core.common.util.UtilServer; import mineplex.core.shop.item.IButton; import mineplex.core.shop.page.ConfirmationPage; import mineplex.game.clans.clans.ClanEnergyManager; import mineplex.game.clans.clans.ClanInfo; -import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.PreEnergyShopBuyEvent; public class EnergyShopButton implements IButton { @@ -38,6 +32,11 @@ public class EnergyShopButton implements IButton @Override public void onClick(final Player player, ClickType clickType) { + if (UtilServer.CallEvent(new PreEnergyShopBuyEvent(player, _energyToPurchase, _cost)).isCancelled()) + { + return; + } + _page.getShop().openPageForPlayer(player, new ConfirmationPage( _page.getPlugin(), _page.getShop(), _page.getClientManager(), _page.getDonationManager(), new Runnable() { diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/PvpPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/PvpPage.java index f06045627..b36ea0510 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/PvpPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/PvpPage.java @@ -1,10 +1,13 @@ package mineplex.game.clans.shop.pvp; import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.C; import mineplex.core.donation.DonationManager; +import mineplex.core.itemstack.ItemBuilder; import mineplex.game.clans.clans.ClansManager; -import mineplex.game.clans.shop.ClansShopPage; import mineplex.game.clans.shop.ClansShopItem; +import mineplex.game.clans.shop.ClansShopPage; +import mineplex.game.clans.shop.pvp.tnt.TNTGenShop; public class PvpPage extends ClansShopPage { @@ -54,9 +57,14 @@ public class PvpPage extends ClansShopPage addShopItem(33, ClansShopItem.BOW, "Standard Bow"); addShopItem(34, ClansShopItem.ARROW, (byte) 0, "Arrows", 16); + addShopItem(52 - 9, ClansShopItem.CANNON, C.cBlue + "Cannon"); + addShopItem(53 - 9, ClansShopItem.OUTPOST, C.cBlue + "Outpost"); + addShopItem(51, ClansShopItem.ENCHANTMENT_TABLE, "Class Shop"); addShopItem(52, ClansShopItem.TNT, "TNT"); - addShopItem(53, ClansShopItem.TNT_GENERATOR, "TNT Generator"); + addButton(53, new ItemBuilder(ClansShopItem.TNT_GENERATOR.getMaterial()).setTitle(C.cAqua + "Manage TNT Generator").build(), (player, click) -> + new TNTGenShop(_plugin, _clientManager, _donationManager).attemptShopOpen(player) + ); } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenPage.java new file mode 100644 index 000000000..eaed63bc0 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenPage.java @@ -0,0 +1,154 @@ +package mineplex.game.clans.shop.pvp.tnt; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.event.EventHandler; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilUI; +import mineplex.core.donation.DonationManager; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.tntGenerator.TntGenerator; +import mineplex.game.clans.clans.tntGenerator.TntGeneratorManager; +import mineplex.game.clans.economy.GoldManager; +import mineplex.game.clans.shop.ClansShopItem; + +public class TNTGenPage extends ShopPageBase +{ + public TNTGenPage(ClansManager plugin, TNTGenShop shop, CoreClientManager clientManager, DonationManager donationManager, org.bukkit.entity.Player player) + { + super(plugin, shop, clientManager, donationManager, "TNT Generator", player); + + buildPage(); + } + + @Override + protected void buildPage() + { + ClanInfo clan = _plugin.getClan(_player); + + if (clan == null) + { + _player.closeInventory(); + _player.playSound(_player.getLocation(), Sound.NOTE_BASS, 1, 1); + UtilPlayer.message(_player, F.main("Clans", "You must be in a clan to manage a TNT Generator.")); + return; + } + + if (clan.getGenerator() == null) + { + addButton(13, new ItemBuilder(Material.BREWING_STAND_ITEM).setTitle(C.cRed + "Buy TNT Generator").setLore(" ", C.cYellow + ClansShopItem.TNT_GENERATOR.getBuyPrice() + " Gold").build(), (player, click) -> { + clearPage(); + buildPage(); + + // Check if generator is still null + // Prevents someone from buying a generator at the same time as another clan member does. + if (clan.getGenerator() != null) + { + _player.playSound(_player.getLocation(), Sound.NOTE_BASS, 1, 1); + UtilPlayer.message(_player, F.main("Clans", "Your clan already has a TNT Generator.")); + return; + } + + if (_donationManager.Get(player).getGold() >= ClansShopItem.TNT_GENERATOR.getBuyPrice()) + { + GoldManager.getInstance().deductGold(success -> { + UtilPlayer.message(player, F.main("Clans", "You purchased a " + F.elem("TNT Generator") + " for your Clan. You can now access it from the " + F.elem("PvP Shop") + ".")); + clan.inform(F.main("Clans", F.elem(player.getName()) + " purchased a " + F.elem("TNT Generator") + " for the Clan. You can now access it from the " + F.elem("PvP Shop") + "."), player.getName()); + + TntGenerator generator = new TntGenerator(player.getUniqueId().toString()); + clan.setGenerator(generator); + _plugin.getClanDataAccess().updateGenerator(clan, null); + }, player, ClansShopItem.TNT_GENERATOR.getBuyPrice()); + } + else + { + UtilPlayer.message(player, F.main("Clans", "You can not afford to purchase a " + F.elem("TNT Generator") + " for your Clan.")); + _player.playSound(player.getLocation(), Sound.NOTE_BASS, 1, 1); + } + + clearPage(); + buildPage(); + }); + } + else + { + TntGenerator generator = clan.getGenerator(); + + String nextTnt = "Never"; + + if (generator.getStock() < 3) + { + nextTnt = UtilTime.MakeStr((TntGeneratorManager.SECONDS_PER_TNT - generator.getTicks()) * 1000); + } + + addButton(13, new ItemBuilder(Material.BREWING_STAND_ITEM) + .setTitle(C.cGreen + "TNT Generator") + .setLore( + " ", + C.cWhite + "Purchased by " + F.elem(clan.getMembers().get(generator.getBuyer()).getPlayerName()), + " ", + C.cWhite + "TNT Available: " + F.elem(Integer.valueOf(generator.getStock())), + " ", + C.cWhite + "Next TNT: " + F.elem(nextTnt)).build(), (player, click) -> { + clearPage(); + buildPage(); + }); + + if (generator.getStock() == 0) + { + return; + } + + int[] indices = UtilUI.getIndicesFor(generator.getStock(), 2); + + for (int index : indices) + { + addButton(index, new ItemBuilder(Material.TNT).setTitle(C.cGreen + "Retrieve TNT").setLore(" ", "Click to collect this TNT.").build(), (player, click) -> { + clearPage(); + buildPage(); + + if (generator.getStock() <= 0) + { + UtilPlayer.message(player, F.main("Clans", "Your " + F.elem("TNT Generator") + " no longer contains this piece of TNT.")); + _player.playSound(player.getLocation(), Sound.NOTE_BASS, 1, 1); + return; + } + + if (UtilInv.HasSpace(player, Material.TNT, 1)) + { + UtilPlayer.message(player, F.main("Clans", "You have successfully collected TNT from your " + F.elem("TNT Generator") + ".")); + clan.inform(F.main("Clans", F.elem(player.getName()) + " has collected TNT from the Clan's " + F.elem("TNT Generator") + "."), player.getName()); + player.getInventory().addItem(new ItemStack(Material.TNT, 1)); + generator.setStock(generator.getStock() - 1); + _player.playSound(player.getLocation(), Sound.NOTE_PLING, 1, 1); + } + else + { + UtilPlayer.message(player, F.main("Clans", "You do not have enough sufficient space in your inventory to collect TNT.")); + _player.playSound(player.getLocation(), Sound.NOTE_BASS, 1, 1); + } + + clearPage(); + buildPage(); + + }); + } + } + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenShop.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenShop.java new file mode 100644 index 000000000..4e54909a4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/shop/pvp/tnt/TNTGenShop.java @@ -0,0 +1,22 @@ +package mineplex.game.clans.shop.pvp.tnt; + +import org.bukkit.entity.Player; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.shop.ShopBase; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.game.clans.clans.ClansManager; + +public class TNTGenShop extends ShopBase +{ + public TNTGenShop(ClansManager plugin, CoreClientManager clientManager, mineplex.core.donation.DonationManager donationManager) + { + super(plugin, clientManager, donationManager, "TNT Generator"); + } + + @Override + protected ShopPageBase> buildPagesFor(Player player) + { + return new TNTGenPage(getPlugin(), this, getClientManager(), getDonationManager(), player); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/Spawn.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/Spawn.java index a04d444d0..aa44d5d2f 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/Spawn.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/Spawn.java @@ -39,10 +39,10 @@ import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilTime.TimeUnit; +import mineplex.core.common.weight.WeightSet; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.game.clans.clans.ClansManager; -import mineplex.core.common.weight.WeightSet; import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; import mineplex.minecraft.game.classcombat.item.event.WebTossEvent; import mineplex.minecraft.game.core.condition.Condition.ConditionType; @@ -74,8 +74,8 @@ public class Spawn extends MiniPlugin super("Clan Spawn Zones", plugin); _instance = this; - _spawns = new WeightSet(getEastSpawn(), getWestSpawn()); - _shops = new WeightSet(getNorthTown(), getSouthTown()); + _spawns = new WeightSet(getNorthSpawn(), getSouthSpawn()); + _shops = new WeightSet(getEastTown(), getWestTown()); _clansManager = clansManager; } @@ -281,10 +281,7 @@ public class Spawn extends MiniPlugin event.setRespawnLocation(getSpawnLocation()); } - /** - * Ensure player spawns into a Spawn location if it's their first time on the server. - * @param event - */ + /* @EventHandler public void onPlayerFirstJoin(PlayerJoinEvent event) { @@ -293,6 +290,7 @@ public class Spawn extends MiniPlugin teleport(event.getPlayer(), getSpawnLocation(), 2); // Teleport player to spawn after 2-tick delay to prevent on-join bug } } + */ /** * Prevent creatures from spawning inside Spawn @@ -458,34 +456,34 @@ public class Spawn extends MiniPlugin return Bukkit.getWorld("world"); } - public static Location getSouthTown() + public static Location getWestTown() { - return new Location(getSpawnWorld(), -6, 70, 295); + return new Location(getSpawnWorld(), -440.91, 63, 23.08); } - public static Location getSouthTownCenter() + public static Location getWestTownCenter() { - return new Location(getSpawnWorld(), -6, 70, 312); + return new Location(getSpawnWorld(), -425, 72, 8); } - public static Location getNorthTown() + public static Location getEastTown() { - return new Location(getSpawnWorld(), 2, 66, -325); + return new Location(getSpawnWorld(), 440.91, 63, -23.08); } - public static Location getNorthTownCenter() + public static Location getEastTownCenter() { - return new Location(getSpawnWorld(), 7, 75, -311); + return new Location(getSpawnWorld(), 425, 72, -8); } - public static Location getEastSpawn() + public static Location getNorthSpawn() { - return new Location(getSpawnWorld(), 304.5, 210, 6.5); + return new Location(getSpawnWorld(), 8.5, 200, -393.5); } - public static Location getWestSpawn() + public static Location getSouthSpawn() { - return new Location(getSpawnWorld(), -295.5, 207, 6.5); + return new Location(getSpawnWorld(), 8.5, 200, 390.5); } public boolean isCombatTagged(Player player) @@ -493,7 +491,7 @@ public class Spawn extends MiniPlugin return _clansManager.getCondition().HasCondition(player, ConditionType.CUSTOM, COMBAT_TAG_NAME); } - private void teleport(final Player player, final Location location, int delay) + public void teleport(final Player player, final Location location, int delay) { Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { @Override @@ -525,16 +523,21 @@ public class Spawn extends MiniPlugin if (UtilTime.elapsed(_songEastLast, _songEastLength)) { - getEastSpawn().getWorld().playEffect(getEastSpawn(), Effect.RECORD_PLAY, 2258); //Blocks + getNorthSpawn().getWorld().playEffect(getNorthSpawn(), Effect.RECORD_PLAY, 2258); //Blocks _songEastLast = System.currentTimeMillis(); } if (UtilTime.elapsed(_songWestLast, _songWestLength)) { - getWestSpawn().getWorld().playEffect(getWestSpawn(), Effect.RECORD_PLAY, 2259); //Chirp + getSouthSpawn().getWorld().playEffect(getSouthSpawn(), Effect.RECORD_PLAY, 2259); //Chirp _songWestLast = System.currentTimeMillis(); } } + + public ClansManager getClansManager() + { + return _clansManager; + } } diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelButton.java index 27e0e51b0..6e6dc9b87 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelButton.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelButton.java @@ -58,6 +58,11 @@ public class TravelButton implements IButton return; } + if (_location == null) + { + return; + } + if (player.getLocation().distance(_location) <= 64) { return; diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelPage.java index d6babf2a1..6140d1ad2 100644 --- a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelPage.java +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/spawn/travel/TravelPage.java @@ -12,7 +12,6 @@ import org.bukkit.inventory.meta.ItemMeta; import mineplex.core.account.CoreClientManager; import mineplex.core.common.util.C; -import mineplex.core.common.util.F; import mineplex.core.common.util.UtilBlock; import mineplex.core.donation.DonationManager; import mineplex.core.itemstack.ItemBuilder; @@ -23,6 +22,8 @@ import mineplex.game.clans.clans.ClanInfo; import mineplex.game.clans.clans.ClanRole; import mineplex.game.clans.clans.ClansManager; import mineplex.game.clans.clans.gui.ClanIcon; +import mineplex.game.clans.clans.siege.outpost.Outpost; +import mineplex.game.clans.shop.ClansShopItem; import mineplex.game.clans.spawn.Spawn; public class TravelPage extends ShopPageBase @@ -37,45 +38,54 @@ public class TravelPage extends ShopPageBase @Override protected void buildPage() { - addTravelLocation(Spawn.getEastSpawn(), getPlayer().getLocation().distance(Spawn.getEastSpawn()) <= 64 ? Material.SKULL_ITEM : Material.IRON_SWORD, (getPlayer().getLocation().distance(Spawn.getEastSpawn()) <= 64 ? C.cRedB : C.cGreenB) + "East Spawn", new String[] { + addTravelLocation(Spawn.getNorthSpawn(), getPlayer().getLocation().distance(Spawn.getNorthSpawn()) <= 64 ? Material.SKULL_ITEM : Material.IRON_SWORD, (getPlayer().getLocation().distance(Spawn.getNorthSpawn()) <= 64 ? C.cRedB : C.cGreenB) + "North Spawn", new String[] { C.cWhite + "Spawns are locations where", C.cWhite + "you respawn after dying.", " ", C.cWhite + "You cannot be attacked here,", C.cWhite + "as they are Safe Zones.", - getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? " " : "", - getPlayer().getLocation().distance(Spawn.getEastSpawn()) <= 64 ? C.cRed + "You are already here." : "", - }, 14 + 10, getPlayer().getLocation().distance(Spawn.getEastSpawn()) <= 64 ? (byte) 3 : (byte) 0); + getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? " " : "", + getPlayer().getLocation().distance(Spawn.getNorthSpawn()) <= 64 ? C.cRed + "You are already here." : "", + }, 4, getPlayer().getLocation().distance(Spawn.getNorthSpawn()) <= 64 ? (byte) 3 : (byte) 0); - addTravelLocation(Spawn.getWestSpawn(), getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? Material.SKULL_ITEM : Material.IRON_SWORD, (getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? C.cRedB : C.cGreenB) + "West Spawn", new String[] { + addTravelLocation(Spawn.getSouthSpawn(), getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? Material.SKULL_ITEM : Material.IRON_SWORD, (getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? C.cRedB : C.cGreenB) + "South Spawn", new String[] { C.cWhite + "Spawns are locations where", C.cWhite + "you respawn after dying.", " ", C.cWhite + "You cannot be attacked here,", C.cWhite + "as they are Safe Zones.", - getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? " " : "", - getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? C.cRed + "You are already here." : "", - }, 12 + 8, getPlayer().getLocation().distance(Spawn.getWestSpawn()) <= 64 ? (byte) 3 : (byte) 0); + getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? " " : "", + getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? C.cRed + "You are already here." : "", + }, 22 + 9 + 9, getPlayer().getLocation().distance(Spawn.getSouthSpawn()) <= 64 ? (byte) 3 : (byte) 0); - addTravelLocation(Spawn.getNorthTown(), ClanIcon.CASTLE.getMaterial(), C.cDGreenB + "North Shop", new String[] { + addTravelLocation(Spawn.getWestTown(), ClanIcon.CASTLE.getMaterial(), C.cDGreenB + "West Shop", new String[] { C.cWhite + "Shops are locations where you", C.cWhite + "can buy and sell all sorts of goods.", " ", C.cWhite + "You cannot be attacked here,", C.cWhite + "as they are Safe Zones.", - }, 4, ClanIcon.CASTLE.getData()); + }, 12 + 8, ClanIcon.CASTLE.getData()); - addTravelLocation(Spawn.getSouthTown(), ClanIcon.CASTLE.getMaterial(), C.cDGreenB + "South Shop", new String[] { + addTravelLocation(Spawn.getEastTown(), ClanIcon.CASTLE.getMaterial(), C.cDGreenB + "East Shop", new String[] { C.cWhite + "Shops are locations where you", C.cWhite + "can buy and sell all sorts of goods.", " ", C.cWhite + "You cannot be attacked here,", C.cWhite + "as they are Safe Zones.", - }, 22 + 9 + 9, ClanIcon.CASTLE.getData()); + }, 14 + 10, ClanIcon.CASTLE.getData()); + + final ClanInfo clan = _plugin.getClan(getPlayer()); + Outpost outpost = _plugin.getSiegeManager().getOutpostManager().Get(clan); + + addTravelLocation(outpost == null ? null : outpost.getCoreLocation().clone().add(0, 1, 0), ClansShopItem.OUTPOST.getMaterial(), (outpost == null ? C.cRedB : C.cDGreenB) + "Outpost", new String[] { + C.cWhite + "Teleport to your Clan's currently", + C.cWhite + "active Outpost.", + " ", + (outpost == null ? C.cRed + "Your Clan does not have an Outpost." : ""), + }, 8, ClanIcon.CASTLE.getData()); - final ClanInfo clan = getPlugin().getClan(getPlayer()); final ItemStack item = new ItemStack(Material.BED, 1); ItemMeta meta = item.getItemMeta(); diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/texttutorial/ClassTutorial.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/texttutorial/ClassTutorial.java new file mode 100644 index 000000000..d6e3b3e79 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/texttutorial/ClassTutorial.java @@ -0,0 +1,14 @@ +package mineplex.game.clans.texttutorial; + +import mineplex.core.texttutorial.tutorial.Phase; +import mineplex.core.texttutorial.tutorial.Tutorial; + +public class ClassTutorial extends Tutorial +{ + public ClassTutorial() + { + super("Class Guide", "Clans.TextTutorial.Class", 0); + + addPhase(new Phase(null, "Classes", new String[] { "" })); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/Tutorial.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/Tutorial.java new file mode 100644 index 000000000..1771b70be --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/Tutorial.java @@ -0,0 +1,400 @@ +package mineplex.game.clans.tutorial; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilFirework; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextBottom; +import mineplex.core.hologram.Hologram; +import mineplex.core.hologram.HologramManager; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.message.ClansMessageManager; +import mineplex.game.clans.tutorial.objective.Objective; +import mineplex.game.clans.tutorial.objective.ObjectiveListener; + +public abstract class Tutorial implements Listener, ObjectiveListener +{ + private HashMap _playerSessionMap; + + private JavaPlugin _plugin; + private HologramManager _hologram; + private ClansMessageManager _message; + private String _name; + private String _taskIdentifier; + private TutorialWorldManager _worldManager; + + // GUI Data + private Material _guiMaterial; + private byte _guiData; + + private List _objectives; + + public Tutorial(JavaPlugin plugin, ClansMessageManager message, HologramManager hologram, String name, String taskIdentifier, Material guiMaterial, byte data) + { + _plugin = plugin; + _message = message; + _hologram = hologram; + _name = name; + _taskIdentifier = taskIdentifier; + + _guiMaterial = guiMaterial; + _guiData = data; + + _playerSessionMap = new HashMap<>(); + _objectives = new ArrayList<>(); + } + + protected void addObjective(Objective objective) + { + _objectives.add(objective); + objective.addListener(this); + } + + public void start(Player player) + { + System.out.println(String.format("Tutorial> [%s] started tutorial [%s]", player.getName(), getName())); + + TutorialSession session = new TutorialSession(); + TutorialRegion region = _worldManager == null ? null : _worldManager.getNextRegion(); + session.setRegion(region); + + _playerSessionMap.put(player, session); + + onStart(player); + + // Start at first objective! + setObjective(player, 0); + + + _objectives.forEach(objective -> objective.setup(player, region)); + } + + private void setObjective(Player player, int objective) + { + if (_objectives.size() <= objective) + throw new IndexOutOfBoundsException("Invalid objective index: " + objective + ", size: " + _objectives.size()); + + _playerSessionMap.get(player).setObjectiveIndex(objective); + _objectives.get(objective).start(player); + } + + public boolean isInTutorial(Player player) + { + return _playerSessionMap.containsKey(player); + } + + public JavaPlugin getPlugin() + { + return _plugin; + } + + public String getName() + { + return _name; + } + + public Material getGuiMaterial() + { + return _guiMaterial; + } + + public byte getGuiData() + { + return _guiData; + } + + public ClansMessageManager getMessage() + { + return _message; + } + + public final String getTaskIdentifier() + { + return "clans.tutorial." + _taskIdentifier; + } + + @Override + public void onObjectiveFinish(Player player, Objective objective) + { + int index = _objectives.indexOf(objective); + + assert index != -1; + + if (index + 1 >= _objectives.size()) + { + finish(player); + } + else + { + setObjective(player, index + 1); + } + } + + @Override + public void onObjectiveStart(Player player, Objective objective) + { + } + + @Override + public void onObjectivePlayerUpdate(Player player, Objective objective) + { + } + + protected final void finish(Player player) + { + _objectives.forEach(objective -> objective.clean(player, getRegion(player))); + + removePlayer(player); + + System.out.println(String.format("Tutorial> [%s] finished tutorial [%s]", player.getName(), getName())); + + playFinishEffects(player.getLocation()); + onFinish(player); + } + + private void quit(Player player) + { + _objectives.forEach(objective -> objective.clean(player, getRegion(player))); + + removePlayer(player); + + System.out.println(String.format("Tutorial> [%s] quit tutorial [%s]", player.getName(), getName())); + + onQuit(player); + } + + private void removePlayer(Player player) + { + TutorialSession session = _playerSessionMap.remove(player); + + if (session != null) + { + if (session.getRegion() != null) + { + _worldManager.returnRegion(session.getRegion()); + } + + if (session.getSpawnHologram() != null) + session.getSpawnHologram().stop(); + + session.getHolograms().forEach(Hologram::stop); + } + } + + public Set getPlayers() + { + return _playerSessionMap.keySet(); + } + + /** + * Called when the player finishes the tutorial + */ + protected abstract void onFinish(Player player); + + /** + * Called when the player starts the tutorial + */ + protected abstract void onStart(Player player); + + /** + * Called when a player quits the tutorial or leaves the game in the tutorial + */ + protected abstract void onQuit(Player player); + + public void unregisterAll() + { + HandlerList.unregisterAll(this); + _objectives.forEach(Objective::unregisterAll); + } + + public List getScoreboardLines(Player player) + { + ArrayList lines = new ArrayList<>(); + TutorialSession session = _playerSessionMap.get(player); + if (session != null) + { + lines.add(" "); + + int objectiveIndex = session.getObjectiveIndex(); + Objective currentObjective = _objectives.get(objectiveIndex); + lines.add(C.cGreenB + currentObjective.getName(player)); + lines.add(" "); + currentObjective.addScoreboardLines(player, lines); + } + return lines; + } + + public void setWorldManager(TutorialWorldManager worldManager) + { + _worldManager = worldManager; + } + + public TutorialWorldManager getWorldManager() + { + return _worldManager; + } + + public TutorialRegion getRegion(Player player) + { + if(player == null || !player.isOnline() || _playerSessionMap == null || _playerSessionMap.get(player) == null) return null; + return _playerSessionMap.get(player).getRegion(); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) + { + if (isInTutorial(event.getPlayer())) + { + quit(event.getPlayer()); + } + } + + @EventHandler + public void onKick(PlayerKickEvent event) + { + if (isInTutorial(event.getPlayer())) + { + quit(event.getPlayer()); + } + } + + @EventHandler + public void onHungerChange(FoodLevelChangeEvent event) + { + if (event.getEntity() instanceof Player && isInTutorial(((Player) event.getEntity()))) + { + event.setFoodLevel(20); + } + } + + @EventHandler + public void displayDescription(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + return; + + for (Map.Entry entry : _playerSessionMap.entrySet()) + { + String prefix = entry.getValue().incrementAndGetColorTick() % 2 == 0 ? C.cWhite : C.cGreen; + Objective objective = _objectives.get(entry.getValue().getObjectiveIndex()); + UtilTextBottom.display(prefix + objective.getDescription(entry.getKey()), entry.getKey()); + } + } + + @EventHandler + public void displayText(UpdateEvent event) + { + if (event.getType() != UpdateType.SEC) + { + return; + } + + for (Map.Entry entry : _playerSessionMap.entrySet()) + { + Player player = entry.getKey(); + Objective objective = _objectives.get(entry.getValue().getObjectiveIndex()); + + if (entry.getValue().incrementAndGetTextSeconds() < 20) + { + // 20 second delay between displaying. + return; + } + + objective.displayChatMessages(player); + } + } + + public void addHologram(Player player, Location location, String... text) + { + if (_playerSessionMap.containsKey(player)) + { + Hologram hologram = new Hologram(_hologram, location, text); + _playerSessionMap.get(player).getHolograms().add(hologram); + hologram.start(); + } + } + + public void setSpawnHologram(Player player, Location location, String... text) + { + if (_playerSessionMap.containsKey(player)) + { + TutorialSession session = _playerSessionMap.get(player); + if (session.getSpawnHologram() == null && !session.isRemovedHologram()) + { + Hologram hologram = new Hologram(_hologram, location, text); + session.setSpawnHologram(hologram); + hologram.start(); + } + else + { + session.getSpawnHologram().setText(text); + } + } + } + + public void removeSpawnHologram(Player player) + { + if (_playerSessionMap.containsKey(player)) + { + TutorialSession session = _playerSessionMap.get(player); + if (session.getSpawnHologram() != null) + { + session.getSpawnHologram().stop(); + session.setSpawnHologram(null); + } + + session.setRemovedHologram(true); + } + } + + public TutorialSession getTutorialSession(Player player) + { + return _playerSessionMap.get(player); + } + + private void playFinishEffects(Location location) + { + // Firework + UtilFirework.launchFirework( + location, + FireworkEffect.Type.STAR, + Color.GREEN, + true, + true, + null, + 1 + ); + + // Particles + UtilParticle.PlayParticle(UtilParticle.ParticleType.HAPPY_VILLAGER, + location, 0.5F, 0.5F, 0.5F, 1, 3, UtilParticle.ViewDist.LONG); + UtilParticle.PlayParticle(UtilParticle.ParticleType.ENCHANTMENT_TABLE, + location, 0.5F, 0.5F, 0.5F, 1, 3, UtilParticle.ViewDist.LONG); + UtilParticle.PlayParticle(UtilParticle.ParticleType.HEART, + location, 0.5F, 0.5F, 0.5F, 1, 3, UtilParticle.ViewDist.LONG); + UtilParticle.PlayParticle(UtilParticle.ParticleType.NOTE, + location, 0.5F, 0.5F, 0.5F, 1, 3, UtilParticle.ViewDist.LONG); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialManager.java new file mode 100644 index 000000000..826fbccc1 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialManager.java @@ -0,0 +1,186 @@ +package mineplex.game.clans.tutorial; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; + +import mineplex.core.MiniPlugin; +import mineplex.core.account.CoreClientManager; +import mineplex.core.chat.Chat; +import mineplex.core.chat.FilterPriority; +import mineplex.core.common.events.PlayerRecieveBroadcastEvent; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.donation.DonationManager; +import mineplex.core.hologram.HologramManager; +import mineplex.core.npc.NpcManager; +import mineplex.core.scoreboard.ScoreboardManager; +import mineplex.core.scoreboard.elements.ScoreboardElement; +import mineplex.core.task.TaskManager; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.message.ClansMessageManager; +import mineplex.game.clans.tutorial.command.TutorialCommand; +import mineplex.game.clans.tutorial.gui.TutorialShop; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.plugin.java.JavaPlugin; + +public class TutorialManager extends MiniPlugin implements ScoreboardElement +{ + private CoreClientManager _clientManager; + private DonationManager _donationManager; + private ClansMessageManager _clansMessageManager; + + private EnumMap _tutorialMap; + private EnumMap _shopMap; // Don't need to do anything with shops currently + + public TutorialManager(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager, Chat chat, HologramManager hologram, ClansManager clansManager, NpcManager npcManager, TaskManager taskManager) + { + super("Clans Tutorial", plugin); + + _clientManager = clientManager; + _donationManager = donationManager; + _clansMessageManager = new ClansMessageManager(plugin); + + _tutorialMap = new EnumMap(TutorialType.class); + _shopMap = new EnumMap(TutorialType.class); + + addTutorial(TutorialType.MAIN, new ClansMainTutorial(plugin, clansManager, _clansMessageManager, hologram, npcManager, taskManager)); + + chat.AddFilter(event -> { + if (inTutorial(event.getPlayer())) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not allowed to speak while in a tutorial.")); + + return Boolean.TRUE; + } + + Iterator recipients = event.getRecipients().iterator(); + + while (recipients.hasNext()) + { + Player recipient = recipients.next(); + + if (inTutorial(recipient)) + { + recipients.remove(); + } + } + + return Boolean.FALSE; + }, FilterPriority.HIGH); + } + + @EventHandler + public void broadcast(PlayerRecieveBroadcastEvent event) + { + if (!inTutorial(event.getPlayer())) + { + return; + } + + if (!event.getMessage().startsWith(C.cBlue + "Event>")) + { + return; + } + + event.setCancelled(true); + } + + @Override + public void addCommands() + { + addCommand(new TutorialCommand(this)); + } + + private void addTutorial(TutorialType type, Tutorial tutorial) + { + if (_tutorialMap.containsKey(type)) + { + _tutorialMap.remove(type).unregisterAll(); + } + + _tutorialMap.put(type, tutorial); + _shopMap.put(type, new TutorialShop(this, _clientManager, _donationManager, tutorial)); + getPlugin().getServer().getPluginManager().registerEvents(tutorial, getPlugin()); + } + + public boolean inTutorial(Player player) + { + return getTutorial(player) != null; + } + + public Tutorial getTutorial(Player player) + { + for (Tutorial tutorial : _tutorialMap.values()) + { + if (tutorial.isInTutorial(player)) + return tutorial; + } + + return null; + } + + public void finishTutorial(Player player) + { + Tutorial tutorial = getTutorial(player); + if (tutorial != null) + { + tutorial.finish(player); + } + } + + public boolean startTutorial(Player player, TutorialType type) + { + if (inTutorial(player)) + { + UtilPlayer.message(player, F.main("Tutorial", "You are already in a tutorial")); + return false; + } + + if (_tutorialMap.containsKey(type)) + { + UtilPlayer.message(player, F.main("Tutorial", "Starting Tutorial: " + type.name())); + _tutorialMap.get(type).start(player); + return true; + } + + return false; + } + + public void openTutorialMenu(Player player, TutorialType type) + { + if (_shopMap.containsKey(type)) + { + _shopMap.get(type).attemptShopOpen(player); + } + } + + public ClansMessageManager getMessageManager() + { + return _clansMessageManager; + } + + public Tutorial getTutorial(TutorialType type) + { + return _tutorialMap.get(type); + } + + @Override + public List getLines(ScoreboardManager manager, Player player, List out) + { + Tutorial tutorial = getTutorial(player); + + if (tutorial != null) + { + out.clear(); + return tutorial.getScoreboardLines(player); + } + + return new ArrayList(0); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialRegion.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialRegion.java new file mode 100644 index 000000000..3e42a1f17 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialRegion.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.tutorial; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; + +import mineplex.core.common.block.DataLocationMap; +import mineplex.core.common.block.schematic.Schematic; + +public class TutorialRegion +{ + private final Schematic _schematic; + private final Location _origin; + private DataLocationMap _locationMap; + + protected TutorialRegion(Schematic schematic, Location origin) + { + _origin = origin; + _schematic = schematic; + + pasteSchematic(); + } + + public Location getOrigin() + { + return _origin; + } + + public DataLocationMap getLocationMap() + { + return _locationMap; + } + + private void pasteSchematic() + { + _locationMap = _schematic.paste(getOrigin(), false); + } + + /** + * Clear the schematic area. This shouldn't be needed + */ + @Deprecated + private void clearSchematic() + { + for (int x = 0; x < _schematic.getWidth(); x++) + { + for (int y = 0; y < _schematic.getHeight(); y++) + { + for (int z = 0; z < _schematic.getLength(); z++) + { + Block b = _origin.clone().add(x, y, z).getBlock(); + if (b.getType() != Material.AIR) + { + b.setTypeIdAndData(0, (byte) 0, false); + } + } + } + } + } + + protected void reset() + { + long start = System.currentTimeMillis(); + System.out.println("TutorialRegion starting reset..."); + pasteSchematic(); + System.out.println("TutorialRegion finished reset! Took " + (System.currentTimeMillis() - start) + "ms"); + + } + + @Override + public String toString() + { + return "TutorialRegion[" + _origin.toString() + "]"; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialSession.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialSession.java new file mode 100644 index 000000000..271db3e05 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialSession.java @@ -0,0 +1,118 @@ +package mineplex.game.clans.tutorial; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Location; + +import mineplex.core.hologram.Hologram; + +public class TutorialSession +{ + private final long _startTime; + private int _objectiveIndex; + private TutorialRegion _region; + private List _hologramList = new ArrayList<>(); + private Location _homeLocation; + private int _colorTick; + private int _textSeconds; + private Location _mapTargetLocation; + private Hologram _spawnHologram; + private boolean _removedHologram; + + public TutorialSession() + { + _startTime = System.currentTimeMillis(); + } + + public List getHolograms() + { + return _hologramList; + } + + public int getObjectiveIndex() + { + return _objectiveIndex; + } + + public void setObjectiveIndex(int objectiveIndex) + { + _objectiveIndex = objectiveIndex; + } + + public TutorialRegion getRegion() + { + return _region; + } + + public void setRegion(TutorialRegion region) + { + _region = region; + } + + public Location getHomeLocation() + { + return _homeLocation; + } + + public void setHomeLocation(Location homeLocation) + { + _homeLocation = homeLocation; + } + + public int incrementAndGetColorTick() + { + return ++_colorTick; + } + + public void setTextSeconds(int seconds) + { + _textSeconds = seconds; + } + + public int incrementAndGetTextSeconds() + { + _textSeconds++; + return _textSeconds; + } + + public void setMapTargetLocation(Location location) + { + _mapTargetLocation = location; + } + + public Location getMapTargetLocation() + { + return _mapTargetLocation; + } + + public long getStartTime() + { + return _startTime; + } + + public long getElapsedTime() + { + return System.currentTimeMillis() - _startTime; + } + + public boolean isRemovedHologram() + { + return _removedHologram; + } + + public void setRemovedHologram(boolean removedHologram) + { + _removedHologram = removedHologram; + } + + public void setSpawnHologram(Hologram spawnHologram) + { + _spawnHologram = spawnHologram; + } + + public Hologram getSpawnHologram() + { + return _spawnHologram; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialType.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialType.java new file mode 100644 index 000000000..984114613 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialType.java @@ -0,0 +1,6 @@ +package mineplex.game.clans.tutorial; + +public enum TutorialType +{ + MAIN +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialWorldManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialWorldManager.java new file mode 100644 index 000000000..40ac68fc6 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/TutorialWorldManager.java @@ -0,0 +1,107 @@ +package mineplex.game.clans.tutorial; + +import java.io.File; +import java.io.IOException; +import java.util.Stack; + +import org.bukkit.Bukkit; +import org.bukkit.Difficulty; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.block.schematic.Schematic; +import mineplex.core.common.block.schematic.UtilSchematic; +import mineplex.core.common.generator.VoidGenerator; +import mineplex.game.clans.tutorial.TutorialRegion; + +public class TutorialWorldManager extends MiniPlugin +{ + public static final int BLOCKS_BETWEEN_TUTORIALS = 1200; + + private final World _tutorialWorld; + private final Schematic _schematic; + private Stack _regionStack; + private TutorialRegion _centerRegion; + + public TutorialWorldManager(JavaPlugin plugin, String worldName, String schematicName) throws IOException + { + super("Tutorial World", plugin); + + log("Creating Tutorial World"); + WorldCreator creator = new WorldCreator(worldName); + creator.generator(new VoidGenerator()); + _tutorialWorld = Bukkit.createWorld(creator); + _tutorialWorld.setDifficulty(Difficulty.EASY); + _tutorialWorld.setGameRuleValue("doDaylightCycle", "false"); + _tutorialWorld.setTime(6000); + _tutorialWorld.setAutoSave(false); + _tutorialWorld.setAmbientSpawnLimit(0); + _tutorialWorld.setMonsterSpawnLimit(0); + _tutorialWorld.setWaterAnimalSpawnLimit(0); + log("Tutorial World Created!"); + + log("Loading schematic - " + schematicName); + _schematic = UtilSchematic.loadSchematic(new File(schematicName)); + log("Finished loading schematic"); + + log("Populating Region Stack..."); + populateRegionStack(); + log("Finished loading Tutorial World Manager!"); + } + + private void populateRegionStack() + { + _regionStack = new Stack<>(); + + // Populate the stack with 100 available tutorial regions + for (int x = 0; x < 10; x++) + { + for (int z = 0; z < 10; z++) + { + long time = System.currentTimeMillis(); + double xLoc = (x) * BLOCKS_BETWEEN_TUTORIALS; // 1000x1000 regions + double zLoc = (z) * BLOCKS_BETWEEN_TUTORIALS; + + TutorialRegion region = new TutorialRegion(_schematic, new Location(_tutorialWorld, xLoc, 30, zLoc)); + if (x == 0 && z == 0) _centerRegion = region; + _regionStack.add(region); + System.out.println("Finished Generating Region: " + ((x * 10) + z) + ". Took " + (System.currentTimeMillis() - time) + " ms"); + } + } + } + + /** + * Get the next TutorialRegion in the stack. This region is prepared and ready for use in a tutorial + * @return + */ + public TutorialRegion getNextRegion() + { + return _regionStack.pop(); + } + + /** + * Notify the TutorialWorldManager that this TutorialRegion is no longer needed and should be cleaned up. + * The TutorialRegion should not be used after calling this method + */ + public void returnRegion(TutorialRegion region) + { + region.reset(); + _regionStack.push(region); + log("Returned " + region.toString()); + } + + public World getTutorialWorld() + { + return _tutorialWorld; + } + + public TutorialRegion getCenterRegion() + { + return _centerRegion; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/FinishCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/FinishCommand.java new file mode 100644 index 000000000..954db2c0d --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/FinishCommand.java @@ -0,0 +1,23 @@ +package mineplex.game.clans.tutorial.command; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.game.clans.tutorial.TutorialManager; + +public class FinishCommand extends CommandBase +{ + public FinishCommand(TutorialManager plugin) + { + super(plugin, Rank.JNR_DEV, "finish", "end"); + } + + @Override + public void Execute(Player caller, String[] args) + { + Plugin.finishTutorial(caller); + + + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/StartCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/StartCommand.java new file mode 100644 index 000000000..2e100d21b --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/StartCommand.java @@ -0,0 +1,41 @@ +package mineplex.game.clans.tutorial.command; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.TutorialType; + +public class StartCommand extends CommandBase +{ + public StartCommand(TutorialManager plugin) + { + super(plugin, Rank.DEVELOPER, "start"); + } + + @Override + public void Execute(Player caller, String[] args) + { + if (args == null || args.length != 1) + { + UtilPlayer.message(caller, F.main("Tutorial", "/tutorial start ")); + return; + } + + TutorialType type = null; + + for (TutorialType check : TutorialType.values()) + { + if (check.name().equalsIgnoreCase(args[0])) + type = check; + } + + if (type != null) + Plugin.openTutorialMenu(caller, type); + else + UtilPlayer.message(caller, F.main("Tutorial", "Invalid Tutorial " + F.elem(args[0]))); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/TutorialCommand.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/TutorialCommand.java new file mode 100644 index 000000000..c9722a1bf --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/command/TutorialCommand.java @@ -0,0 +1,27 @@ +package mineplex.game.clans.tutorial.command; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.command.MultiCommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.tutorial.TutorialManager; + +public class TutorialCommand extends MultiCommandBase +{ + public TutorialCommand(TutorialManager plugin) + { + super(plugin, Rank.JNR_DEV, "tutorial", "tut"); + + AddCommand(new StartCommand(plugin)); + AddCommand(new FinishCommand(plugin)); + } + + @Override + protected void Help(Player caller, String[] args) + { + UtilPlayer.message(caller, F.main("Tutorial", "/tutorial start ")); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialSelectPage.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialSelectPage.java new file mode 100644 index 000000000..6265bd797 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialSelectPage.java @@ -0,0 +1,43 @@ +package mineplex.game.clans.tutorial.gui; + +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.donation.DonationManager; +import mineplex.core.shop.item.ShopItem; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.game.clans.tutorial.Tutorial; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.gui.button.DeclineButton; +import mineplex.game.clans.tutorial.gui.button.StartButton; + +public class TutorialSelectPage extends ShopPageBase +{ + public TutorialSelectPage(TutorialManager plugin, TutorialShop shop, CoreClientManager clientManager, DonationManager donationManager, Player player) + { + super(plugin, shop, clientManager, donationManager, shop.getTutorial().getName(), player, 45); + + buildPage(); + } + + @Override + protected void buildPage() + { + Tutorial tutorial = getShop().getTutorial(); + + String name = tutorial.getName(); + Material material = tutorial.getGuiMaterial(); + byte data = tutorial.getGuiData(); + + ShopItem infoItem = new ShopItem(material, data, name, new String[0], 0, false, false); + addItem(13, infoItem); + + ShopItem startItem = new ShopItem(Material.EMERALD_BLOCK, "Start " + tutorial.getName(), new String[0], 0, false, false); + addButton(27 + 6, startItem, new StartButton(tutorial)); + + ShopItem declineButton = new ShopItem(Material.REDSTONE_BLOCK, "Cancel", new String[0], 0, false, false); + addButton(27 + 2, declineButton, new DeclineButton()); + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialShop.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialShop.java new file mode 100644 index 000000000..29a8c62f7 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/TutorialShop.java @@ -0,0 +1,33 @@ +package mineplex.game.clans.tutorial.gui; + +import org.bukkit.entity.Player; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.donation.DonationManager; +import mineplex.core.shop.ShopBase; +import mineplex.core.shop.page.ShopPageBase; +import mineplex.game.clans.tutorial.Tutorial; +import mineplex.game.clans.tutorial.TutorialManager; + +public class TutorialShop extends ShopBase +{ + private final Tutorial _tutorial; + + public TutorialShop(TutorialManager plugin, CoreClientManager clientManager, DonationManager donationManager, Tutorial tutorial) + { + super(plugin, clientManager, donationManager, tutorial.getName()); + + _tutorial = tutorial; + } + + @Override + protected ShopPageBase> buildPagesFor(Player player) + { + return new TutorialSelectPage(getPlugin(), this, getClientManager(), getDonationManager(), player); + } + + public Tutorial getTutorial() + { + return _tutorial; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/DeclineButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/DeclineButton.java new file mode 100644 index 000000000..e1b283fae --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/DeclineButton.java @@ -0,0 +1,15 @@ +package mineplex.game.clans.tutorial.gui.button; + +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import mineplex.core.shop.item.IButton; + +public class DeclineButton implements IButton +{ + @Override + public void onClick(Player player, ClickType clickType) + { + player.closeInventory(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/StartButton.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/StartButton.java new file mode 100644 index 000000000..8461ea669 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/gui/button/StartButton.java @@ -0,0 +1,28 @@ +package mineplex.game.clans.tutorial.gui.button; + +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; + +import mineplex.core.shop.item.IButton; +import mineplex.game.clans.tutorial.Tutorial; + +public class StartButton implements IButton +{ + private final Tutorial _tutorial; + + public StartButton(Tutorial tutorial) + { + _tutorial = tutorial; + } + + @Override + public void onClick(Player player, ClickType clickType) + { + if (!_tutorial.isInTutorial(player)) + { + _tutorial.start(player); + } + + player.closeInventory(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapManager.java new file mode 100644 index 000000000..b7e9d9a98 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapManager.java @@ -0,0 +1,680 @@ +package mineplex.game.clans.tutorial.map; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.craftbukkit.v1_8_R3.CraftChunk; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.ItemSpawnEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.base.Objects; +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Iterables; +import com.google.common.collect.Multisets; + +import mineplex.core.MiniPlugin; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; + +import net.minecraft.server.v1_8_R3.Block; +import net.minecraft.server.v1_8_R3.BlockPosition; +import net.minecraft.server.v1_8_R3.Blocks; +import net.minecraft.server.v1_8_R3.IBlockData; +import net.minecraft.server.v1_8_R3.MaterialMapColor; +import net.minecraft.server.v1_8_R3.PersistentCollection; + +public class TutorialMapManager extends MiniPlugin +{ + private ClansMainTutorial _tutorial; + private int _blocksScan = 16; + private Comparator> _comparator; + private int _halfMapSize = 64; + private int[][] _heightMap; + private boolean _loadWorld = true; + private HashMap _map = new HashMap(); + private short _mapId = (short) UtilMath.r(Short.MAX_VALUE); + private ArrayList> _scanList = new ArrayList>(); + private World _world; + private int _centerX; + private int _centerZ; + private int _scale = 1; + private int _minX; + private int _minZ; + + public TutorialMapManager(JavaPlugin plugin, ClansMainTutorial tutorial, World world, int minX, int minZ, int maxX, int maxZ) + { + super("TutorialMapManager", plugin); + + _centerX = minX + ((maxX - minX) / 2); + _centerZ = minZ + ((maxZ - minZ) / 2); + _centerX = (int) (Math.round(_centerX / 16D) * 16); + _centerZ = (int) (Math.round(_centerZ / 16D) * 16); + _tutorial = tutorial; + _minX = minX; + _minZ = minZ; + + _heightMap = new int[(_halfMapSize * 2) + 16][]; + + _comparator = new Comparator>() + { + + @Override + public int compare(Entry o1, Entry o2) + { + // Render the places outside the map first to speed up visual errors fixing + int outsideMap = Boolean.compare(o1.getValue() < -_halfMapSize, o2.getValue() < -_halfMapSize); + + if (outsideMap != 0) + { + return -outsideMap; + } + + double dist1 = 0; + double dist2 = 0; + + for (Player player : UtilServer.getPlayers()) + { + dist1 += getDistance(o1, player.getLocation().getX(), player.getLocation().getZ()); + dist2 += getDistance(o2, player.getLocation().getX(), player.getLocation().getZ()); + } + + if (dist1 != dist2) + { + return Double.compare(dist1, dist2); + } + + dist1 = getDistance(o1, 0, 0); + dist2 = getDistance(o2, 0, 0); + + return Double.compare(dist1, dist2); + + } + }; + + for (int x = -_halfMapSize; x < _halfMapSize; x += _blocksScan) + { + for (int z = -_halfMapSize - 16; z < _halfMapSize; z += (z < -_halfMapSize ? 16 : _blocksScan)) + { + _scanList.add(new HashMap.SimpleEntry(x, z)); + } + } + + for (int s = 1; s <= 2; s++) + { + if (s == 2) + { + s = getScale(); + + if (s == 1) + break; + } + + int size = (_halfMapSize * 2) / s; + Byte[][] bytes = new Byte[size][]; + + for (int i = 0; i < size; i++) + { + bytes[i] = new Byte[size]; + } + + _map.put(s, bytes); + } + + for (int i = 0; i < _heightMap.length; i++) + { + _heightMap[i] = new int[_heightMap.length]; + } + + _world = world; + + try + { + File foundFile = null; + + for (File f : new File("world/data").listFiles()) + { + if (f.getName().startsWith("map_")) + { + foundFile = f; + break; + } + } + + if (foundFile == null) + { + PersistentCollection collection = ((CraftWorld) _world).getHandle().worldMaps; + Field f = collection.getClass().getDeclaredField("d"); + f.setAccessible(true); + ((HashMap) f.get(collection)).put("map", (short) 0); + } + + MapView view = Bukkit.createMap(_world); + _mapId = view.getId(); + setupRenderer(view); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + rebuildScan(); + } + + private void setupRenderer(MapView view) + { + for (MapRenderer renderer : view.getRenderers()) + { + view.removeRenderer(renderer); + } + + view.addRenderer(new TutorialMapRenderer(_tutorial, _minX, _minZ)); + } + + public int getScale() + { + return _scale; + } + + public int getX() + { + return _centerX; + } + + public int getZ() + { + return _centerZ; + } + + @EventHandler + public void preventMapInItemFrame(PlayerInteractEntityEvent event) + { + if (!(event.getRightClicked() instanceof ItemFrame)) + return; + + ItemStack item = event.getPlayer().getItemInHand(); + + if (item == null || item.getType() != Material.MAP || item.getDurability() < _mapId || item.getDurability() != _mapId) + return; + + event.setCancelled(true); + } + + /** + * Get the center of the map. + */ + public int calcMapCenter(int zoom, int cord) + { + int mapSize = _halfMapSize / zoom; // This is how large the map is in pixels + + int mapCord = cord / zoom; // This is pixels from true center of map, not held map + + int fDiff = mapSize - -mapCord; + int sDiff = mapSize - mapCord; + + double chunkBlock = cord & 0xF; + cord -= chunkBlock; + chunkBlock /= zoom; + + /*if ((fDiff < 64 || sDiff < 64) && (Math.abs(fDiff - sDiff) > 1)) + { + cord += (fDiff > sDiff ? Math.floor(chunkBlock) : Math.ceil(chunkBlock)); + } + else*/ + { + cord += (int) Math.floor(chunkBlock) * zoom; + } + + while ((fDiff < 64 || sDiff < 64) && (Math.abs(fDiff - sDiff) > 1)) + { + int change = (fDiff > sDiff ? -zoom : zoom); + cord += change; + + mapCord = cord / zoom; + + fDiff = mapSize - -mapCord; + sDiff = mapSize - mapCord; + } + + return cord; + } + + private void colorWorldHeight(int zoom, int startingX, int startingZ) + { + if (zoom == 0) + zoom = 1; + + Byte[][] map = _map.get(zoom); + + for (int x = startingX; x < startingX + _blocksScan; x += zoom) + { + double d0 = 0; + + // Prevents ugly lines for the first line of Z + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int hX = x + addX + _halfMapSize; + int hZ = (startingZ - zoom) + addZ + _halfMapSize; + + if (hX >= _halfMapSize * 2 || hZ >= _halfMapSize * 2) + { + continue; + } + + d0 += _heightMap[hX + 16][hZ + 16] / (zoom * zoom); + } + } + + for (int z = startingZ; z < startingZ + _blocksScan; z += zoom) + { + // Water depth colors not included + double d1 = 0; + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int hX = x + addX + _halfMapSize; + int hZ = z + addZ + _halfMapSize; + + if (hX >= _halfMapSize * 2 || hZ >= _halfMapSize * 2) + { + continue; + } + + d1 += _heightMap[hX + 16][hZ + 16] / (zoom * zoom); + } + } + + double d2 = (d1 - d0) * 4.0D / (zoom + 4) + ((x + z & 0x1) - 0.5D) * 0.4D; + byte b0 = 1; + + d0 = d1; + + if (d2 > 0.6D) + { + b0 = 2; + } + else if (d2 > 1.2D) + { + b0 = 3; + } + else if (d2 < -0.6D) + { + b0 = 0; + } + + int origColor = map[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] - 1; + + /*if (color < 4) + { + d2 = waterDepth * 0.1D + (k1 + j2 & 0x1) * 0.2D; + b0 = 1; + if (d2 < 0.5D) + { + b0 = 2; + } + + if (d2 > 0.9D) + { + b0 = 0; + } + }*/ + + byte color = (byte) (origColor + b0); + map[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] = color; + } + } + } + + private void drawWorldScale(int zoom, int startingX, int startingZ) + { + Byte[][] first = _map.get(1); + Byte[][] second = _map.get(zoom); + + for (int x = startingX; x < startingX + _blocksScan; x += zoom) + { + for (int z = startingZ; z < startingZ + _blocksScan; z += zoom) + { + HashMultiset hashmultiset = HashMultiset.create(); + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int pX = x + addX + _halfMapSize; + int pZ = z + addZ + _halfMapSize; + + if (pX >= first.length || pZ >= first.length) + { + continue; + } + + Byte b = first[pX][pZ]; + + if (b == null) + continue; + + hashmultiset.add(b); + } + } + + Byte color = Iterables.getFirst(Multisets.copyHighestCountFirst(hashmultiset), (byte) 0); + + second[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] = color; + } + } + } + + @EventHandler + public void dropItem(ItemSpawnEvent event) + { + ItemStack item = event.getEntity().getItemStack(); + + if (item != null && item.getType() == Material.MAP && item.getDurability() == _mapId) + { + event.getEntity().remove(); + } + } + + private double getDistance(double x1, double z1, double x2, double z2) + { + x1 = (x1 - x2); + z1 = (z1 - z2); + + return (x1 * x1) + (z1 * z1); + } + + private double getDistance(Entry entry, double x1, double z1) + { + return getDistance(x1 + _centerX, z1 + _centerZ, entry.getKey() + (_blocksScan / 2), + entry.getValue() + (_blocksScan / 2)); + } + + public Byte[][] getMap(int scale) + { + return _map.get(scale); + } + + public int getMapSize() + { + return _halfMapSize; + } + + @EventHandler + public void preventMapMoveInventories(InventoryClickEvent event) + { + Inventory inv = event.getClickedInventory(); + + if (inv == null) + return; + + // Yeah, the loop looks a little weird.. + for (ItemStack item : new ItemStack[] + { + event.getCurrentItem(), + event.getCursor() + }) + { + if (item == null || item.getType() != Material.MAP || item.getDurability() != _mapId) + continue; + + if (inv.getHolder() instanceof Player ? !event.isShiftClick() : Objects.equal(event.getCurrentItem(), item)) + continue; + + event.setCancelled(true); + + UtilPlayer.message(event.getWhoClicked(), + F.main("Inventory", "You cannot move " + F.item("Clans Map") + " between inventories.")); + return; + } + } + + private void rebuildScan() + { + for (int x = -_halfMapSize; x < _halfMapSize; x += _blocksScan) + { + for (int z = -_halfMapSize - 16; z < _halfMapSize; z += (z < -_halfMapSize ? 16 : _blocksScan)) + { + _scanList.add(new HashMap.SimpleEntry(x, z)); + } + } + + if (!_loadWorld) + { + Iterator> itel = _scanList.iterator(); + + while (itel.hasNext()) + { + Entry entry = itel.next(); + boolean removeEntry = true; + + for (Player player : UtilServer.getPlayers()) + { + if (Math.sqrt(getDistance(entry, player.getLocation().getX(), player.getLocation().getZ())) < 200) + { + removeEntry = false; + break; + } + } + + if (removeEntry) + { + itel.remove(); + } + } + } + + Collections.sort(_scanList, _comparator); + } + + @EventHandler + public void renderMap(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTEST) + return; + + if (_scanList.isEmpty()) + { + if (_loadWorld) + { + _loadWorld = false; + } + + if (UtilServer.getPlayers().length == 0) + return; + + rebuildScan(); + } + else if (_scanList.size() % 20 == 0) + { + Collections.sort(_scanList, _comparator); + } + + if (_scanList.isEmpty()) + return; + + Entry entry = _scanList.remove(0); + + int startingX = entry.getKey(); + int startingZ = entry.getValue(); + + boolean outsideMap = startingZ < -_halfMapSize; + + scanWorldMap(startingX, startingZ, !outsideMap); + + if (outsideMap) + { + return; + } + + for (int s = 1; s <= 2; s++) + { + if (s == 2) + { + s = getScale(); + + if (s == 1) + break; + } + + if (s == 13 && _loadWorld) + continue; + + if (!outsideMap) + { + drawWorldScale(s, startingX, startingZ); + } + + colorWorldHeight(s, startingX, startingZ); + } + + colorWorldHeight(0, startingX, startingZ); + } + + public void scanWorldMap(int startingX, int startingZ, boolean setColors) + { + Byte[][] map = _map.get(1); + + for (int beginX = startingX; beginX < startingX + _blocksScan; beginX += 16) + { + for (int beginZ = startingZ - (startingZ > -_halfMapSize ? 16 : 0); beginZ < startingZ + + (setColors ? _blocksScan : 16); beginZ += 16) + { + Chunk chunk = _world.getChunkAt((beginX + _centerX) / 16, (beginZ + _centerZ) / 16); + boolean loaded = false; + + if (!chunk.isLoaded()) + { + if (_loadWorld) + { + loaded = chunk.load(); + } + else + { + continue; + } + } + + net.minecraft.server.v1_8_R3.Chunk nmsChunk = ((CraftChunk) chunk).getHandle(); + + for (int x = beginX; x < beginX + 16; x++) + { + for (int z = beginZ; z < beginZ + 16; z++) + { + int color = 0; + + if (!nmsChunk.isEmpty()) + { + int k3 = x & 0xF; + int l3 = z & 0xF; + + int l4 = nmsChunk.b(k3, l3) + 1; + IBlockData iblockdata = Blocks.AIR.getBlockData(); + + if (l4 > 1) + { + do + { + l4--; + iblockdata = nmsChunk.getBlockData(new BlockPosition(k3, l4, l3)); + } + while (iblockdata.getBlock().g(iblockdata) == MaterialMapColor.b && (l4 > 0)); + + if ((l4 > 0) && (iblockdata.getBlock().getMaterial().isLiquid())) + { + int j5 = l4 - 1; + Block block1; + do + { + block1 = nmsChunk.getType(new BlockPosition(k3, j5--, l3)); + } + while ((j5 > 0) && (block1.getMaterial().isLiquid())); + } + } + + _heightMap[x + _halfMapSize + 16][z + _halfMapSize + 16] = l4; + + if (setColors) + { + // color = block.f(i5).M; + IBlockData data = nmsChunk.getBlockData(new BlockPosition(k3, l4, l3)); + color = data.getBlock().g(data).M; + + color = (byte) ((color * 4) + 1); + } + } + + if (setColors && beginZ >= startingZ) + { + map[x + _halfMapSize][z + _halfMapSize] = (byte) color; + } + } + + if (loaded) + { + chunk.unload(); + } + } + } + } + } + + public void setMap(Player player) + { + for (ItemStack item : UtilInv.getItems(player)) + { + if (item.getType() == Material.MAP && item.getDurability() == _mapId) + { + return; + } + } + + ItemStack item = new ItemBuilder(Material.MAP, 1, _mapId).setTitle("Clans Map").build(); + + int slot = player.getInventory().firstEmpty(); + + if (slot >= 0) + { + ItemStack mapSlot = player.getInventory().getItem(8); + + if (mapSlot == null || mapSlot.getType() == Material.AIR) + { + slot = 8; + } + + player.getInventory().setItem(slot, item); + } + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapRenderer.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapRenderer.java new file mode 100644 index 000000000..1132dd4ac --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/map/TutorialMapRenderer.java @@ -0,0 +1,243 @@ +package mineplex.game.clans.tutorial.map; + +import java.awt.*; +import java.util.List; + +import mineplex.core.recharge.Recharge; +import mineplex.game.clans.tutorial.TutorialManager; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.TutorialType; +import mineplex.game.clans.tutorial.TutorialWorldManager; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.map.MapCanvas; +import org.bukkit.map.MapCursor; +import org.bukkit.map.MapCursorCollection; +import org.bukkit.map.MapPalette; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; + +public class TutorialMapRenderer extends MapRenderer +{ + private ClansMainTutorial _tutorial; + private int _minX; + private int _minZ; + + public TutorialMapRenderer(ClansMainTutorial tutorialManager, int minX, int minZ) + { + super(true); + + _tutorial = tutorialManager; + _minX = minX; + _minZ = minZ; + } + + @Override + public void render(MapView mapView, MapCanvas canvas, Player player) + { + TutorialMapManager tutorialMap = _tutorial.getMapManager(); + int zoom = tutorialMap.getScale(); + + Byte[][] map = tutorialMap.getMap(zoom); + + int centerX = 0; + int centerZ = 0; + + // We have this cooldown to squeeze out every single bit of performance from the server. + if (Recharge.Instance.use(player, "Draw Map", 4000, false, false)) + { + TutorialRegion region = _tutorial.getWorldManager().getCenterRegion(); + MinMaxArea shops = getArea(region, ClansMainTutorial.Bounds.SHOPS); + MinMaxArea fields = getArea(region, ClansMainTutorial.Bounds.FIELDS); + MinMaxArea spawn = getArea(region, ClansMainTutorial.Bounds.SPAWN); + MinMaxArea claim = getArea(region, ClansMainTutorial.Bounds.LAND_CLAIM); + MinMaxArea enemy = getArea(region, ClansMainTutorial.Bounds.ENEMY_LAND); + + for (int mapX = 0; mapX < 128; mapX++) + { + for (int mapZ = 0; mapZ < 128; mapZ++) + { + int blockX = centerX + (mapX - 64); + int blockZ = centerZ + (mapZ - 64); + + int pixelX = blockX + (map.length / 2); + int pixelZ = blockZ + (map.length / 2); + + int xRegion = mapX + _minX - 6; + int zRegion = mapZ + _minZ; + + Byte color = 0; + + + if (!(pixelX < 0 || pixelZ < 0 || pixelX >= map.length || pixelZ >= map.length) + && map[pixelX][pixelZ] != null) + { + color = map[pixelX][pixelZ]; + + if (!((color <= -113 || color >= 0) && color <= 127)) + color = (byte) 0; + + blockX *= zoom; + blockZ *= zoom; + + color = attemptDraw(false, color, Color.WHITE, new Color(50, 150, 255), xRegion, zRegion, shops, mapX, mapZ); + color = attemptDraw(false, color, Color.WHITE, new Color(255, 120, 0), xRegion, zRegion, fields, mapX, mapZ); + color = attemptDraw(false, color, Color.WHITE, new Color(0, 255, 100), xRegion, zRegion, spawn, mapX, mapZ); + color = attemptDraw(true, color, Color.CYAN, null, xRegion, zRegion, claim, mapX, mapZ); + color = attemptDraw(true, color, Color.RED, null, xRegion, zRegion, enemy, mapX, mapZ); + } + + /* TODO Figure out if you want to colorize this pixel + { + color = MapPalette.matchColor(r, g, b); + }*/ + + canvas.setPixel(mapX, mapZ, color); + } + } + + player.sendMap(mapView); + } + + MapCursorCollection cursors = canvas.getCursors(); + + while (cursors.size() > 0) + + { + cursors.removeCursor(cursors.getCursor(0)); + } + + Location l = player.getLocation().clone(); + l.setX((((int)l.getX()) % TutorialWorldManager.BLOCKS_BETWEEN_TUTORIALS) + (l.getX() - ((int) l.getX()))); + l.setZ((((int)l.getZ()) % TutorialWorldManager.BLOCKS_BETWEEN_TUTORIALS) + (l.getZ() - ((int) l.getZ()))); + + double mapX = (l.getX() - tutorialMap.getX()) / zoom; + double mapZ = (l.getZ() - tutorialMap.getZ()) / zoom; + + if (mapX > -64 && mapX < 64 && mapZ > -64 && mapZ < 64) + { + byte b0 = (byte) (int) Math.min(127, (double) (mapX * 2.0F) + 0.5D); + byte b1 = (byte) (int) Math.max(-127, (double) (mapZ * 2.0F) + 0.5D); + + byte rotation = (byte) (int) ((l.getYaw() * 16D) / 360D); + + MapCursor cursor = new MapCursor(b0, b1, (byte) (rotation & 0xF), MapCursor.Type.WHITE_POINTER.getValue(), true); + + cursors.addCursor(cursor); + } + + // Add Tutorial Markers + TutorialSession session = _tutorial.getTutorialSession(player); + if (session != null) + { + if (session.getMapTargetLocation() != null) + { + Location point = session.getMapTargetLocation().clone(); + point.setX((((int)point.getX()) % TutorialWorldManager.BLOCKS_BETWEEN_TUTORIALS) + (point.getX() - ((int) point.getX()))); + point.setZ((((int)point.getZ()) % TutorialWorldManager.BLOCKS_BETWEEN_TUTORIALS) + (point.getZ() - ((int) point.getZ()))); + mapX = (point.getX() - tutorialMap.getX()) / zoom; + mapZ = (point.getZ() - tutorialMap.getZ()) / zoom; + + // To make these appear at the edges of the map, just change it from 64 to something like 128 for double the map size + if (mapX > -64 && mapX < 64 && mapZ > -64 && mapZ < 64) + { + byte b0 = (byte) (int) Math.min(127, (double) (mapX * 2.0F) + 0.5D); + byte b1 = (byte) (int) Math.max(-127, (double) (mapZ * 2.0F) + 0.5D); + + byte cursorType = 4; // http://i.imgur.com/wpH6PT8.png + // Those are byte 5 and 6 + byte rotation = (byte) ((int) Math.floor(System.currentTimeMillis() / 1000D) % 16); + + MapCursor cursor = new MapCursor(b0, b1, rotation, cursorType, true); + + cursors.addCursor(cursor); + } + } + } + } + + private byte attemptDraw(boolean colorAll, byte color, Color color1, Color color2, int xRegion, int zRegion, MinMaxArea area, int mapX, int mapZ) + { + if (xRegion >= area.MinX && xRegion <= area.MaxX && zRegion >= area.MinZ && zRegion <= area.MaxZ) + { + if (xRegion == area.MinX || xRegion == area.MaxX || zRegion == area.MinZ || zRegion == area.MaxZ) + { + // Outer Ring + Color cColor = MapPalette.getColor(color); + double clans = colorAll ? 1 : 0.8;// 0.65; + + //Use clanColor2 no matter what for admins + Color drawColor = color1; + if (color2 != null) + { + drawColor = color2; + clans = 1; + } + + double base = 1 - clans; + + int r = (int) ((cColor.getRed() * base) + (drawColor.getRed() * clans)); + int b = (int) ((cColor.getBlue() * base) + (drawColor.getBlue() * clans)); + int g = (int) ((cColor.getGreen() * base) + (drawColor.getGreen() * clans)); + + color = MapPalette.matchColor(r, g, b); + } + else + { + // Inside + Color cColor = MapPalette.getColor(color); + + double clans = 0.065; + + //Stripes + boolean checker = (mapX + (mapZ % 4)) % 4 == 0; + Color drawColor = color1; +// if (colorAll) +// { +// clans = 0.8; +// } + if (checker && color2 != null && !colorAll) + { + drawColor = color2; + clans = 1; + } + + double base = 1 - clans; + + if (clans != 1 && (color == 0 || color == 1 || color == 2 || color == 3)) + return color; + + int r = (int) ((cColor.getRed() * base) + (drawColor.getRed() * clans)); + int b = (int) ((cColor.getBlue() * base) + (drawColor.getBlue() * clans)); + int g = (int) ((cColor.getGreen() * base) + (drawColor.getGreen() * clans)); + + color = MapPalette.matchColor(r, g, b); + } + } + + return color; + } + + private MinMaxArea getArea(TutorialRegion region, ClansMainTutorial.Bounds bounds) + { + MinMaxArea area = new MinMaxArea(); + List shopLocations = region.getLocationMap().getGoldLocations(bounds.getDataLocColor()); + area.MinX = Math.min(shopLocations.get(0).getBlockX(), shopLocations.get(1).getBlockX()); + area.MaxX = Math.max(shopLocations.get(0).getBlockX(), shopLocations.get(1).getBlockX()); + area.MinZ = Math.min(shopLocations.get(0).getBlockZ(), shopLocations.get(1).getBlockZ()); + area.MaxZ = Math.max(shopLocations.get(0).getBlockZ(), shopLocations.get(1).getBlockZ()); + + return area; + } + + private class MinMaxArea + { + public int MinX; + public int MaxX; + public int MinZ; + public int MaxZ; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/Objective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/Objective.java new file mode 100644 index 000000000..a5488a5a5 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/Objective.java @@ -0,0 +1,337 @@ +package mineplex.game.clans.tutorial.objective; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.NautHashMap; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.game.clans.tutorial.Tutorial; +import mineplex.game.clans.tutorial.TutorialRegion; + +/** + * An Objective represents a set of goals that need to be completed to move on to the next Objective in the quest + */ +public abstract class Objective implements Listener +{ + private Plugin _plugin; + private JavaPlugin _javaPlugin; + private String _name; + private String _description; + private String _extraDescription; + private boolean _displayStartMessage; + private int _startMessageDelay; + private boolean _displayFinishMessage; + private int _finishMessageDelay; + + private NautHashMap _active; + private List _listeners; + + public Objective(Plugin plugin, JavaPlugin javaPlugin, String name, String description, String extraDescription) + { + _plugin = plugin; + _javaPlugin = javaPlugin; + _name = name; + _description = description; + _extraDescription = extraDescription; + _displayStartMessage = false; + _displayFinishMessage = false; + _startMessageDelay = 60; + _finishMessageDelay = 1; + + _active = new NautHashMap<>(); + _listeners = new LinkedList<>(); + + javaPlugin.getServer().getPluginManager().registerEvents(this, javaPlugin); + } + + public Objective(Plugin plugin, JavaPlugin javaPlugin, String name, String description) + { + this(plugin, javaPlugin, name, description, null); + } + + public Plugin getPlugin() + { + return _plugin; + } + + public JavaPlugin getJavaPlugin() + { + return _javaPlugin; + } + + /** + * Get the name of this Objective + */ + public String getName(Player player) + { + return _name; + } + + /** + * Get the description of this Objective + */ + public String getDescription(Player player) + { + return _description; + } + + /** + * Get the extra description for this Objective + * Extra description should be any additional useful information that isn't required to complete the objective + */ + public String getExtraDescription(Player player) + { + return _extraDescription; + } + + /** + * Add an ObjectiveListener to this Objective + * @param listener + */ + public void addListener(ObjectiveListener listener) + { + _listeners.add(listener); + } + + /** + * Remove all ObjectiveListeners from this Objective + */ + public void clearListeners() + { + _listeners.clear(); + } + + protected abstract void customStart(Player player); + + /** + * Start this Objective for a player + * @param player + */ + public void start(Player player) + { + System.out.println(String.format("Tutorial> [%s] started objective [%s]", player.getName(), getName(player))); + + Data data = createDataObject(player); + _active.put(player.getUniqueId(), data); + + _listeners.forEach(listener -> listener.onObjectiveStart(player, this)); + + if (_displayStartMessage) + Bukkit.getServer().getScheduler().runTaskLater(getJavaPlugin(), () -> showStartMessage(player), _startMessageDelay); + + customStart(player); + } + + /** + * Leave this objective for a specific player + * This does not count as completing the object + * @param player + */ + public final void leave(Player player) + { + customLeave(player); + + _active.remove(player.getUniqueId()); + + getGoals().forEach(goal -> goal.leave(player)); + } + + protected abstract void customLeave(Player player); + + /** + * Returns a new Data object for use in the active map + * @param player + * @return + */ + protected abstract Data createDataObject(Player player); + + /** + * Called by ObjectiveGoals, used to notify this Objective that a goal has been completed + * @param goal + * @param player + */ + protected abstract void completeGoal(ObjectiveGoal goal, Player player); + + /** + * Called when a player is finished the tutorial + * @param player + * @param region + */ + public void clean(Player player, TutorialRegion region) + { + List> goals = getGoals(); + if (goals != null) + goals.forEach(goal -> goal.clean(player, region)); + + _active.remove(player.getUniqueId()); + } + + /** + * Called when a player starts the tutorial + * @param player + * @param region + */ + public void setup(Player player, TutorialRegion region) + { + List> goals = getGoals(); + if (goals != null) + goals.forEach(goal -> goal.setup(player, region)); + } + + /** + * Returns a list of all the ObjectiveGoals used by this Objective + * Can return null + */ + protected abstract List> getGoals(); + + protected final void finish(Player player) + { + System.out.println(String.format("Tutorial> [%s] finished objective [%s]", player.getName(), getName(player))); + + _active.remove(player.getUniqueId()); + + if (_displayFinishMessage) + Bukkit.getServer().getScheduler().runTaskLater(getJavaPlugin(), () -> showFinishMessage(player), _finishMessageDelay); + + player.playSound(player.getEyeLocation(), Sound.LEVEL_UP, 1f, 1f); + + customFinish(player); + + _listeners.forEach(listener -> listener.onObjectiveFinish(player, this)); + } + + protected final void notifyUpdate(Player player) + { + _listeners.forEach(listener -> listener.onObjectivePlayerUpdate(player, this)); + } + + protected abstract void customFinish(Player player); + + public boolean contains(Player player) + { + return contains(player.getUniqueId()); + } + + public boolean contains(UUID uuid) + { + return _active.containsKey(uuid); + } + + protected final List getActive() + { + return new LinkedList(_active.keySet()); + } + + protected final Player[] getActivePlayers() + { + Set uuidSet = _active.keySet(); + Player[] players = new Player[uuidSet.size()]; + + int index = 0; + for (UUID uuid : uuidSet) + { + players[index] = UtilPlayer.searchExact(uuid); + index++; + } + return players; + } + + public Data getData(Player player) + { + return _active.get(player.getUniqueId()); + } + + /** + * Unregister all listeners associated with this Objective + */ + public final void unregisterAll() + { + HandlerList.unregisterAll(this); + + List> goals = getGoals(); + if (goals != null) goals.forEach(HandlerList::unregisterAll); + } + + public abstract void addScoreboardLines(Player player, List lines); + + private void showStartMessage(Player player) + { + UtilTextMiddle.display(C.cAqua + "Next Tutorial Section", getName(player), 20, 60, 20, player); + } + + private void showFinishMessage(Player player) + { + UtilTextMiddle.display(C.cGreen + "Tutorial Section Completed", getName(player), 20, 60, 20, player); + } + + public void displayChatMessages(Player player) + { + if (getPlugin().getTutorialSession(player) == null) + { + return; + } + + for (int i = 0; i < 1; i++) + { + UtilPlayer.message(player, ""); + } + + ObjectiveGoal goal = getLatestGoal(player); + String name = goal == null ? getName(player) : goal.getName(player); + String extra = getExtraDescription(player); +// UtilPlayer.message(player, C.cGold + C.Strike + "---------------------------------------------"); + UtilPlayer.message(player, C.cPurpleB + name); + if (extra != null) + { + UtilPlayer.message(player, ""); + UtilPlayer.message(player, C.cGray + " " + extra); + } + UtilPlayer.message(player, ""); + UtilPlayer.message(player, C.cGreen + getDescription(player)); +// UtilPlayer.message(player, C.cGold + C.Strike + "---------------------------------------------"); + getPlugin().getTutorialSession(player).setTextSeconds(0); + } + + public void setDisplayStartMessage(boolean displayStartMessage) + { + _displayStartMessage = displayStartMessage; + } + + public abstract ObjectiveGoal getLatestGoal(Player player); + + public void setDisplayFinishMessage(boolean displayFinishMessage) + { + _displayFinishMessage = displayFinishMessage; + } + + public int getStartMessageDelay() + { + return _startMessageDelay; + } + + public void setStartMessageDelay(int startMessageDelay) + { + _startMessageDelay = startMessageDelay; + } + + public int getFinishMessageDelay() + { + return _finishMessageDelay; + } + + public void setFinishMessageDelay(int finishMessageDelay) + { + _finishMessageDelay = finishMessageDelay; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveData.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveData.java new file mode 100644 index 000000000..9d6f8ca00 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveData.java @@ -0,0 +1,5 @@ +package mineplex.game.clans.tutorial.objective; + +public class ObjectiveData +{ +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveGoal.java new file mode 100644 index 000000000..7a66d0a41 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveGoal.java @@ -0,0 +1,232 @@ +package mineplex.game.clans.tutorial.objective; + +import java.util.*; + +import mineplex.core.common.util.UtilFirework; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import org.bukkit.*; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.TutorialRegion; + +public abstract class ObjectiveGoal > implements Listener +{ + private T _objective; + + private HashSet _active; + private HashSet _removeList; + private String _name; + private String _description; + private String _extraDescription; + private boolean _displayStartMessage; + private int _startMessageDelay; + private boolean _displayFinishMessage; + private int _finishMessageDelay; + private DyeColor _fireworkLocations; + + public ObjectiveGoal(T objective, String name, String description) + { + this(objective, name, description, null, null); + } + + public ObjectiveGoal(T objective, String name, String description, String extraDescription, DyeColor fireworkLocs) + { + _objective = objective; + + _active = new HashSet<>(); + _removeList = new HashSet<>(); + _name = name; + _description = description; + _extraDescription = extraDescription; + _displayStartMessage = true; + _startMessageDelay = 1;//40; + _displayFinishMessage = false; + _finishMessageDelay = 1; + _fireworkLocations = fireworkLocs; + } + + public String getName(Player player) + { + return _name; + } + + public String getDescription(Player player) + { + return _description; + } + + public String getExtraDescription(Player player) + { + return _extraDescription; + } + + public Set getActivePlayers() + { + return _active; + } + + public boolean contains(Player player) + { + if (player == null || !player.isOnline()) + { + return false; + } + + return _active.contains(player.getUniqueId()); + } + + public final void start(Player player) + { + System.out.println(String.format("Tutorial> [%s] started objective goal [%s]", player.getName(), getName(player))); + + _active.add(player.getUniqueId()); + + if (_displayStartMessage) + { + Bukkit.getServer().getScheduler().runTaskLater(_objective.getJavaPlugin(), () -> displayStartMessage(player), _startMessageDelay); + } + + customStart(player); + } + + protected abstract void customStart(Player player); + + protected abstract void customFinish(Player player); + + protected void customLeave(Player player) { } + + protected void leave(Player player) + { + if (_active.contains(player.getUniqueId())) + { + System.out.println(String.format("Tutorial> [%s] left objective goal [%s]", player.getName(), getName(player))); + + _removeList.add(player.getUniqueId()); + } + + customLeave(player); + } + + protected void finish(Player player) + { + if (_active.contains(player.getUniqueId())) + { + System.out.println(String.format("Tutorial> [%s] finished objective goal [%s]", player.getName(), getName(player))); + + if (getObjective().getPlugin().getTutorialSession(player) != null) + getObjective().getPlugin().getTutorialSession(player).setTextSeconds(0); + + _removeList.add(player.getUniqueId()); + + if (_displayFinishMessage) + { + Bukkit.getServer().getScheduler().runTaskLater(_objective.getJavaPlugin(), () -> displayFinishMessage(player), _finishMessageDelay); + } + + player.playSound(player.getEyeLocation(), Sound.ORB_PICKUP, 1f, 1f); + + customFinish(player); + + _objective.completeGoal(this, player); + } + } + + /** + * Called when a player starts the tutorial with this goal + */ + protected void setup(Player player, TutorialRegion region) + { + + } + + /** + * Called when a player finishes the tutorial with this goal + */ + protected void clean(Player player, TutorialRegion region) + { + _removeList.add(player.getUniqueId()); + } + + public T getObjective() + { + return _objective; + } + + protected void displayFinishMessage(Player player) + { + UtilTextMiddle.display(C.cGreen + "Completed Objective", getName(player), player); + } + + protected void displayStartMessage(Player player) + { + if (player == null || !player.isOnline()) + { + return; + } + + UtilTextMiddle.display(C.cYellow + "New Objective", getName(player), player); + + _objective.displayChatMessages(player); + } + + public void setDisplayStartMessage(boolean displayStartMessage) + { + _displayStartMessage = displayStartMessage; + } + + public void setDisplayFinishMessage(boolean displayFinishMessage) + { + _displayFinishMessage = displayFinishMessage; + } + + public void setStartMessageDelay(int startMessageDelay) + { + _startMessageDelay = startMessageDelay; + } + + public void setFinishMessageDelay(int finishMessageDelay) + { + _finishMessageDelay = finishMessageDelay; + } + + @EventHandler + public void update(UpdateEvent event) + { + if (!event.getType().equals(UpdateType.SEC_05)) return; + if (_fireworkLocations == null) return; + + for (UUID id : getActivePlayers()) + { + if (Bukkit.getPlayer(id) == null) continue; + List locations = getObjective().getPlugin().getRegion(Bukkit.getPlayer(id)).getLocationMap().getSpongeLocations(_fireworkLocations); + if (locations == null) continue; + for (Location loc : locations) + { + UtilFirework.playFirework(loc, FireworkEffect.Type.BURST, Color.AQUA, true, true); + } + } + } + + @EventHandler + public void activeCleaner(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + for (UUID uuid : _removeList) + { + _active.remove(uuid); + } + + _removeList.clear(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveListener.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveListener.java new file mode 100644 index 000000000..59564fd3c --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/ObjectiveListener.java @@ -0,0 +1,23 @@ +package mineplex.game.clans.tutorial.objective; + +import org.bukkit.entity.Player; + +public interface ObjectiveListener +{ + /** + * Called when a player starts an objective + */ + public void onObjectiveStart(Player player, Objective objective); + + /** + * Called when a player progresses in an objective + * For example, in an OrderedObjective this will be called when the player + * moves to the next ObjectiveGoal + */ + public void onObjectivePlayerUpdate(Player player, Objective objective); + + /** + * Called when a player finishes an objective + */ + public void onObjectiveFinish(Player player, Objective objective); +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjective.java new file mode 100644 index 000000000..450d3b167 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjective.java @@ -0,0 +1,133 @@ +package mineplex.game.clans.tutorial.objective; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.Tutorial; +import net.md_5.bungee.api.ChatColor; + +public abstract class OrderedObjective extends Objective +{ + private List> _goals; + + public OrderedObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description, String extraDescription) + { + super(plugin, javaPlugin, name, description, extraDescription); + + _goals = new ArrayList<>(); + } + + public OrderedObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description) + { + this(plugin, javaPlugin, name, description, null); + } + + protected void addGoal(ObjectiveGoal goal) + { + _goals.add(goal); + + getJavaPlugin().getServer().getPluginManager().registerEvents(goal, getJavaPlugin()); + } + + @Override + protected OrderedObjectiveData createDataObject(Player player) + { + return new OrderedObjectiveData(); + } + + @Override + protected void completeGoal(ObjectiveGoal goal, Player player) + { + int index = _goals.indexOf(goal); + + OrderedObjectiveData data = getData(player); + assert index == data.getIndex(); + + if (data == null || data.getIndex() + 1 >= _goals.size()) + { + finish(player); + } + else + { + setGoal(player, data.getIndex() + 1); + notifyUpdate(player); + } + } + + @Override + public String getDescription(Player player) + { + OrderedObjectiveData data = getData(player); + int index = data == null ? 0 : data.getIndex(); + return _goals.get(index).getDescription(player); + } + + @Override + public String getExtraDescription(Player player) + { + OrderedObjectiveData data = getData(player); + int index = data == null ? 0 : data.getIndex(); + return _goals.get(index).getExtraDescription(player); + } + + @Override + public ObjectiveGoal getLatestGoal(Player player) + { + OrderedObjectiveData data = getData(player); + int index = data == null ? 0 : data.getIndex(); + return _goals.get(index); + } + + @Override + protected void customStart(Player player) + { + setGoal(player, 0); + } + + @Override + protected void customLeave(Player player) + { + + } + + private void setGoal(Player player, int index) + { + OrderedObjectiveData data = getData(player); // Should never be null! + ObjectiveGoal nextGoal = _goals.get(index); + data.setIndex(index); + nextGoal.start(player); + } + + @Override + protected List> getGoals() + { + return _goals; + } + + @Override + public void addScoreboardLines(Player player, List lines) + { + if (contains(player)) + { + OrderedObjectiveData data = getData(player); +// lines.add(" " + getName()); + + for (int i = 0; i < _goals.size(); i++) + { + String prefix; + + if (i > data.getIndex()) + prefix = ChatColor.RED.toString(); + else if (i == data.getIndex()) + prefix = ">" + ChatColor.YELLOW.toString(); + else + prefix = ChatColor.GREEN.toString(); + + lines.add(" " + prefix + _goals.get(i).getName(player)); + } + } + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjectiveData.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjectiveData.java new file mode 100644 index 000000000..55fdd79dc --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/OrderedObjectiveData.java @@ -0,0 +1,21 @@ +package mineplex.game.clans.tutorial.objective; + +public class OrderedObjectiveData extends ObjectiveData +{ + private int _index; + + public OrderedObjectiveData() + { + _index = 0; + } + + public int getIndex() + { + return _index; + } + + public void setIndex(int index) + { + _index = index; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/SingleObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/SingleObjective.java new file mode 100644 index 000000000..78e47d648 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/SingleObjective.java @@ -0,0 +1,61 @@ +package mineplex.game.clans.tutorial.objective; + +import java.util.List; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.C; +import mineplex.game.clans.tutorial.Tutorial; + +public abstract class SingleObjective extends Objective +{ + private final ObjectiveData _nullData; + + public SingleObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description, String extraDescription) + { + super(plugin, javaPlugin, name, description, extraDescription); + + _nullData = new ObjectiveData(); + } + + public SingleObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description) + { + this(plugin, javaPlugin, name, description, null); + } + + @Override + protected ObjectiveData createDataObject(Player player) + { + return _nullData; + } + + @Override + protected void completeGoal(ObjectiveGoal goal, Player player) + { + // Do Nothing + } + + @Override + public ObjectiveGoal getLatestGoal(Player player) + { + return null; + } + + @Override + protected List> getGoals() + { + return null; + } + + @Override + public void addScoreboardLines(Player player, List lines) + { + /* + if (contains(player)) + { + lines.add(" " + C.cRed + getName(player)); + } + */ + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjective.java new file mode 100644 index 000000000..f145c2270 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjective.java @@ -0,0 +1,124 @@ +package mineplex.game.clans.tutorial.objective; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.Tutorial; +import net.md_5.bungee.api.ChatColor; + +public abstract class UnorderedObjective extends Objective +{ + private List> _goals; + + public UnorderedObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description, String extraDescription) + { + super(plugin, javaPlugin, name, description, extraDescription); + + _goals = new ArrayList<>(); + } + + public UnorderedObjective(Plugin plugin, JavaPlugin javaPlugin, String name, String description) + { + this(plugin, javaPlugin, name, description, null); + } + + protected void addGoal(ObjectiveGoal goal) + { + _goals.add(goal); + + getJavaPlugin().getServer().getPluginManager().registerEvents(goal, getJavaPlugin()); + } + + @Override + protected UnorderedObjectiveData createDataObject(Player player) + { + return new UnorderedObjectiveData(_goals.size()); + } + + @Override + protected void completeGoal(ObjectiveGoal goal, Player player) + { + int index = _goals.indexOf(goal); + + UnorderedObjectiveData data = getData(player); + data.setComplete(index); + + if (data.isComplete()) + { + finish(player); + } + else + { + notifyUpdate(player); + } + } + + @Override + public String getDescription(Player player) + { + UnorderedObjectiveData data = getData(player); + if (data == null) return super.getDescription(player); + int index = data.getFirstIncompleteIndex(); + return index == -1 ? super.getDescription(player) : _goals.get(index).getDescription(player); + } + + @Override + public String getExtraDescription(Player player) + { + UnorderedObjectiveData data = getData(player); + if (data == null) return super.getExtraDescription(player); + int index = data.getFirstIncompleteIndex(); + return index == -1 ? super.getExtraDescription(player) : _goals.get(index).getExtraDescription(player); + } + + @Override + public ObjectiveGoal getLatestGoal(Player player) + { + UnorderedObjectiveData data = getData(player); + if (data == null) return null; + int index = data.getFirstIncompleteIndex(); + return index == -1 ? null : _goals.get(index); + } + + @Override + protected void customStart(Player player) + { + _goals.forEach(goal -> goal.start(player)); + } + + @Override + protected void customLeave(Player player) + { + + } + + @Override + protected List> getGoals() + { + return _goals; + } + + @Override + public void addScoreboardLines(Player player, List lines) + { + if (contains(player)) + { + UnorderedObjectiveData data = getData(player); +// lines.add(" " + getName()); + + for (int i = 0; i < _goals.size(); i++) + { + String prefix; + if (data.isComplete(i)) + prefix = ChatColor.GREEN.toString(); + else + prefix = ChatColor.RED.toString(); + + lines.add(" " + prefix + _goals.get(i).getName(player)); + } + } + } +} \ No newline at end of file diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjectiveData.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjectiveData.java new file mode 100644 index 000000000..1d3bf705c --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/objective/UnorderedObjectiveData.java @@ -0,0 +1,48 @@ +package mineplex.game.clans.tutorial.objective; + +public class UnorderedObjectiveData extends ObjectiveData +{ + private boolean[] _tasks; + + public UnorderedObjectiveData(int taskSize) + { + _tasks = new boolean[taskSize]; + } + + public boolean isComplete() + { + boolean complete = true; + for (int i = 0; i < _tasks.length; i++) + { + complete = complete && _tasks[i]; + } + return complete; + } + + public void setComplete(int taskId) + { + _tasks[taskId] = true; + } + + public boolean isComplete(int taskId) + { + return _tasks[taskId]; + } + + public int getFirstIncompleteIndex() + { + for (int i = 0; i < _tasks.length; i++) + { + if (_tasks[i] == false) + return i; + } + + return -1; + } + + public boolean[] getTasks() + { + return _tasks; + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/ClansMainTutorial.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/ClansMainTutorial.java new file mode 100644 index 000000000..a7080e3d9 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/ClansMainTutorial.java @@ -0,0 +1,614 @@ +package mineplex.game.clans.tutorial.tutorials.clans; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilFirework; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.hologram.HologramManager; +import mineplex.core.npc.NpcManager; +import mineplex.core.task.TaskManager; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.clans.event.ClansPlayerBuyItemEvent; +import mineplex.game.clans.clans.event.ClansPlayerSellItemEvent; +import mineplex.game.clans.clans.event.PreEnergyShopBuyEvent; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import mineplex.game.clans.economy.GoldManager; +import mineplex.game.clans.message.ClansMessageManager; +import mineplex.game.clans.spawn.Spawn; +import mineplex.game.clans.tutorial.Tutorial; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.TutorialWorldManager; +import mineplex.game.clans.tutorial.map.TutorialMapManager; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClassesObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.EnergyObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FieldsObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FinalObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.PurchaseItemsObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ShopsObjective; + +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Effect; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.collect.Lists; +//import mineplex.game.clans.tutorial.tutorials.clans.repository.TutorialRepository; + +public class ClansMainTutorial extends Tutorial +{ + // The distance from which the gate opens when a player approaches. + private static final int GATE_OPEN_DISTANCE = 15; + + private TutorialMapManager _mapManager; + private List _fireworks; +// private TutorialRepository _repository; + private TaskManager _taskManager; + + + private List _items = Lists.newArrayList( + Material.SMOOTH_BRICK, + Material.TORCH, + Material.IRON_DOOR, + Material.IRON_DOOR_BLOCK + ); + + + public ClansMainTutorial(JavaPlugin plugin, ClansManager clansManager, ClansMessageManager message, HologramManager hologram, NpcManager npcManager, TaskManager taskManager) + { + super(plugin, message, hologram, "Clans Tutorial", "main", Material.DIAMOND_SWORD, (byte) 0); + + _fireworks = new ArrayList(); + + try + { + setWorldManager(new TutorialWorldManager(plugin, "main_tutorial", "schematic/ClansTutorial.schematic")); + } + catch (IOException e) + { + e.printStackTrace(); + } + + _mapManager = new TutorialMapManager(plugin, this, getWorldManager().getTutorialWorld(), -10, 0, 117, 127); + _taskManager = taskManager; + +// _repository = new TutorialRepository(ClansManager.getInstance().getClientManager()); + + addObjective(new ClanObjective(this, plugin)); + addObjective(new AttackEnemyObjective(this, clansManager, plugin)); + addObjective(new ShopsObjective(this, npcManager, plugin)); + addObjective(new PurchaseItemsObjective(this, plugin)); + addObjective(new ClassesObjective(this, plugin)); + addObjective(new FieldsObjective(this, plugin)); + addObjective(new EnergyObjective(this, plugin)); + addObjective(new FinalObjective(this, plugin)); + } + + @Override + protected void onFinish(Player player) + { + _fireworks.add(player); + UtilTextMiddle.display(C.cYellow + "Congratulations", "You have completed the Tutorial!", 10, 60, 10, player); + + Bukkit.getScheduler().runTaskLater(getPlugin(), () -> { + _fireworks.remove(player); + getMessage().removePlayer(player); + + player.teleport(Spawn.getNorthSpawn()); + UtilInv.Clear(player); + + ClansManager.getInstance().getItemMapManager().setMap(player); + }, 20 * 10L); + + player.setWalkSpeed(0.2F); + + //ClansManager.getInstance().getPvpTimer().unpause(player); + + if (!_taskManager.hasCompletedTask(player, getTaskIdentifier())) + { + _taskManager.completedTask(new Callback() + { + @Override + public void run(Boolean data) + { + + GoldManager.getInstance().addGold(player, 32000); + UtilPlayer.message(player, F.main("Clans", "You have earned " + F.elem(32000 + " Gold") + " for finishing the tutorial!")); + } + }, player, getTaskIdentifier()); + } + + /* + ClansManager.getInstance().runAsync(() -> { + _repository.SetTimesPlayed(player.getUniqueId(), _repository.GetTimesPlayed(player.getUniqueId()) + 1); + + final int times = _repository.GetTimesPlayed(player.getUniqueId()); + + if (_repository.GetTimesPlayed(player.getUniqueId()) == 1) + { + ClansManager.getInstance().runSync(() -> { + if (times == 1) + { + GoldManager.getInstance().addGold(player, 32000); + UtilPlayer.message(player, F.main("Clans", "You have earned " + F.elem(32000 + " Gold") + " for finishing the tutorial!")); + } + + UtilInv.give(player, Material.COOKIE); + }); + } + }); + */ + } + + @Override + protected void onStart(Player player) + { + TutorialRegion region = getRegion(player); + + player.teleport(getSpawn(region)); + spawnFences(region, DyeColor.BLACK); // Fields + spawnFences(region, DyeColor.BROWN); // Shops + spawnFences(region, DyeColor.RED); // Middle + + player.setGameMode(GameMode.SURVIVAL); + player.getInventory().clear(); + player.getInventory().setArmorContents(new ItemStack[4]); + player.setHealth(20); + player.setFoodLevel(20); + + //ClansManager.getInstance().getPvpTimer().pause(player); + + // Spawn Holograms + setSpawnHologram(player, + getPoint(region, ClansMainTutorial.Point.SPAWN).add(0, 1.5, -3), + C.cGoldB + "Welcome to the Clans Tutorial!", + " ", + "This will teach you the basics of Clans.", + "It will take about 5 minutes to complete.", + "You must complete it before playing Clans.", + " ", + "Starting in " + C.cGreen + "10 Seconds"); + + player.setWalkSpeed(0); + + addHologram(player, + getPoint(region, ClansMainTutorial.Point.SPAWN).add(0, 1.5, -23), + "Jump Off!"); + + ClanInfo clan = ClansManager.getInstance().getClan(player); + if (clan != null) + { + ClansManager.getInstance().getClanDataAccess().delete(clan, null); + } + } + + @Override + protected void onQuit(Player player) + { + _fireworks.remove(player); + } + + public Location getPoint(TutorialRegion region, Point point) + { + return region.getLocationMap().getGoldLocations(point.getDataLocColor()).get(0).clone(); + } + + public boolean isIn(Location location, TutorialRegion region, Bounds bounds) + { + if (region.getOrigin().getWorld() != location.getWorld()) + return false; + + List locs = region.getLocationMap().getGoldLocations(bounds.getDataLocColor()); + return UtilAlg.inBoundingBox(location, locs.get(0), locs.get(1)); + } + + public boolean isIn(Player player, Bounds bounds) + { + if(player == null || !player.isOnline()) return false; + TutorialRegion region = getRegion(player); + + if (region != null) + { + if (player.getLocation() == null) return false; + return isIn(player.getLocation(), region, bounds); + } + + return false; + } + + public Location getCenter(TutorialRegion region, Bounds bounds) + { + List locs = region.getLocationMap().getGoldLocations(bounds.getDataLocColor()); + return UtilAlg.getMidpoint(locs.get(0), locs.get(1)); + } + + public Location getSpawn(TutorialRegion region) + { + Location location = region.getLocationMap().getGoldLocations(Point.SPAWN.getDataLocColor()).get(0).clone(); + location.setYaw(180); + return location; + } + + public enum Bounds + { + LAND_CLAIM(DyeColor.LIGHT_BLUE), + // Should be 16x16 + ENEMY_LAND(DyeColor.RED), + // Should be 16x16 + SPAWN(DyeColor.GREEN), + // Spawn Platform + FIELDS(DyeColor.PURPLE), + // Boulders for ores to spawn in? + SHOPS(DyeColor.YELLOW), + // Little shop areas similar to Shops in clans map + ENEMY_ATTACK_AREA(DyeColor.BLACK), + NPC_DIE_AREA(DyeColor.BLUE), + NPC_SHOOT_AREA(DyeColor.BROWN); + // Gray Wool - Cannon Location + // Magenta Wool - Spawn + // Lime Wool - Farming Shop + // Purple Wool - Pvp Shop + // Light Gray Wool - Energy Shop + + private DyeColor _dataLocColor; + + Bounds(DyeColor dataLocColor) + { + _dataLocColor = dataLocColor; + } + + public DyeColor getDataLocColor() + { + return _dataLocColor; + } + } + + public enum Point + { + SPAWN(DyeColor.MAGENTA), + FARMING_SHOP(DyeColor.LIME), + PVP_SHOP(DyeColor.PINK), + ENERGY_SHOP(DyeColor.SILVER), + MINING_SHOP(DyeColor.ORANGE), + CANNON(DyeColor.GRAY), + NPC_1(DyeColor.CYAN), + NPC_2(DyeColor.WHITE); + + private DyeColor _dataLocColor; + + Point(DyeColor dataLocColor) + { + _dataLocColor = dataLocColor; + } + + public DyeColor getDataLocColor() + { + return _dataLocColor; + } + } + + @EventHandler + public void dropItem(PlayerDropItemEvent event) + { + if (isInTutorial(event.getPlayer())) + { + event.setCancelled(true); + } + } + + @EventHandler + public void breakBlock(BlockBreakEvent event) + { + if (isInTutorial(event.getPlayer())) + { + event.setCancelled(true); + } + } + + @EventHandler + public void blockDamage(EntityDamageEvent event) + { + if (event.getEntity() instanceof Player) + { + if (isInTutorial((Player) event.getEntity())) + event.setCancelled(true); + } + } + + // Fences + // Black = fields + // Brown = shops + public void spawnFence(Block startBlock) + { + Block block = startBlock; + int count = 0; + while ((block.getType() == Material.AIR || block.getType() == Material.FENCE) && count < 100) + { + block.setType(Material.FENCE); + + block = block.getRelative(BlockFace.UP); + count++; + } + } + + public void destroyFence(Block startBlock) + { + Block block = startBlock; + int count = 0; + while (block.getType() == Material.FENCE && count < 100) + { + block.setType(Material.AIR); + + block = block.getRelative(BlockFace.UP); + count++; + } + } + + public void spawnFences(TutorialRegion region, DyeColor dataLoc) + { + List locations = region.getLocationMap().getIronLocations(dataLoc); + locations.stream().map(Location::getBlock).forEach(this::spawnFence); + } + + public void destroyFences(TutorialRegion region, DyeColor dataLoc) + { + List locations = region.getLocationMap().getIronLocations(dataLoc); + locations.stream().map(Location::getBlock).forEach(this::destroyFence); + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void teleport(ClansCommandPreExecutedEvent event) + { + if (event.getArguments().length < 1) + { + return; + } + + if (!isInTutorial(event.getPlayer())) + { + return; + } + + if (event.getArguments()[0].equalsIgnoreCase("join") + || event.getArguments()[0].equalsIgnoreCase("leave") + || event.getArguments()[0].equalsIgnoreCase("stuck") + || event.getArguments()[0].equalsIgnoreCase("promote") + || event.getArguments()[0].equalsIgnoreCase("demote") + || event.getArguments()[0].equalsIgnoreCase("invite") + || event.getArguments()[0].equalsIgnoreCase("kick") + || event.getArguments()[0].equalsIgnoreCase("neutral") + || event.getArguments()[0].equalsIgnoreCase("enemy") + || event.getArguments()[0].equalsIgnoreCase("ally") + || event.getArguments()[0].equalsIgnoreCase("trust") + || event.getArguments()[0].equalsIgnoreCase("unclaim") + || event.getArguments()[0].equalsIgnoreCase("claim") + || event.getArguments()[0].equalsIgnoreCase("delete") + || event.getArguments()[0].equalsIgnoreCase("disband") + || event.getArguments()[0].equalsIgnoreCase("admin") + || event.getArguments()[0].equalsIgnoreCase("x")) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not allowed to run this command during the Tutorial.")); + event.setCancelled(true); + } + + } + + @EventHandler + public void checkInRegion(UpdateEvent event) + { + if (event.getType() != UpdateType.SEC) + return; + + for (Player player : getPlayers()) + { + if (player == null || !player.isOnline()) continue; + if (player.getLocation().getWorld() != getWorldManager().getTutorialWorld()) + { + TutorialRegion region = getRegion(player); + player.teleport(getSpawn(region)); + } + } + } + + @EventHandler + public void fireworkUpdate(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) return; + + for (Player player : _fireworks) + { + if (player == null || !player.isOnline()) continue; + UtilFirework.spawnRandomFirework(UtilAlg.getRandomLocation(player.getLocation(), 10)); + } + } + + @EventHandler + public void onJoin(PlayerJoinEvent event) + { +// ClansManager.getInstance().runAsync(() -> { +// if (_repository.GetTimesPlayed(event.getPlayer().getUniqueId()) == 0) +// { +// ClansManager.getInstance().runSync(() -> start(event.getPlayer())); +// } +// }); + + if (!_taskManager.hasCompletedTask(event.getPlayer(), getTaskIdentifier())) + { + start(event.getPlayer()); + } + else if (!event.getPlayer().hasPlayedBefore() || !event.getPlayer().getLocation().getWorld().equals(Spawn.getSpawnWorld())) + { + Spawn.getInstance().teleport(event.getPlayer(), Spawn.getInstance().getSpawnLocation(), 2); + } + } + + @EventHandler + public void preventMovement(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + return; + + for (Player player : getPlayers()) + { + TutorialSession session = getTutorialSession(player); + long time = session.getElapsedTime(); + if (time <= 10000) // 10 seconds + { +// player.teleport(getSpawn(session.getRegion())); + + String secondsLeft = UtilTime.convertString(10000 - time, 0, UtilTime.TimeUnit.SECONDS); + setSpawnHologram(player, + getPoint(session.getRegion(), ClansMainTutorial.Point.SPAWN).add(0, 1.5, -3), + C.cGoldB + "Welcome to the Clans Tutorial!", + " ", + "This will teach you the basics of Clans.", + "It will take about 5 minutes to complete.", + "You must complete it before playing Clans.", + " ", + "Starting in " + C.cGreen + secondsLeft); + } + else if (!session.isRemovedHologram()) + { + removeSpawnHologram(player); + player.setWalkSpeed(0.2F); + } + } + } + + public void performGateCheck(Player player, DyeColor key) + { + if(player == null || !player.isOnline()) return; + Location exact = getRegion(player).getLocationMap().getIronLocations(key).get(0); + if(exact == null) return; + Location fence = UtilAlg.getAverageLocation(getRegion(player).getLocationMap().getIronLocations(key)); + + if (exact.getBlock().getType() == Material.AIR) + { + // Gates are already open. + return; + } + + if (player.getLocation().distanceSquared(fence) <= (GATE_OPEN_DISTANCE * GATE_OPEN_DISTANCE)) + { + // Within the correct blocks of the gates. + destroyFences(getRegion(player), key); + } + } + + public TutorialMapManager getMapManager() + { + return _mapManager; + } + + @EventHandler (priority = EventPriority.LOWEST) + public void onClick(ClansButtonClickEvent event) { + if(isInTutorial(event.getPlayer())) + event.setCancelled(true); + } + + @EventHandler (priority = EventPriority.LOWEST) + public void onShop(ClansPlayerBuyItemEvent event) + { + if(isInTutorial(event.getPlayer())) + event.setCancelled(true); + } + + @EventHandler (priority = EventPriority.LOWEST) + public void onSell(ClansPlayerSellItemEvent event) + { + if(isInTutorial(event.getPlayer())) + event.setCancelled(true); + } + + @EventHandler + public void energyBuy(PreEnergyShopBuyEvent event) + { + if (isInTutorial(event.getPlayer())) + { + event.setCancelled(true); + } + } + + @EventHandler + public void blockBreak(BlockDamageEvent event) + { + if (!isInTutorial(event.getPlayer())) + { + return; + } + + if (!isInBuildArea(event.getPlayer(), event.getBlock())) + { + return; + } + + + if (_items.contains(event.getBlock().getType())) + { + event.getBlock().breakNaturally(); + + event.getBlock().getWorld().playEffect(event.getBlock().getLocation(), Effect.TILE_BREAK, event.getBlock().getTypeId(), 18); + + event.getPlayer().playSound(event.getBlock().getLocation(), Sound.LAVA_POP, 1.f, 1.f); + } + } + + + + + @EventHandler (priority = EventPriority.HIGHEST) + public void blockPlace(BlockPlaceEvent event) + { + if (!isInTutorial(event.getPlayer())) + { + return; + } + + if (isInBuildArea(event.getPlayer(), event.getBlock())) + { + event.setCancelled(false); + } + else + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not allowed to place blocks here.")); + event.setCancelled(true); + } + } + + public boolean isInBuildArea(Player player, Block block) + { + TutorialRegion region = getRegion(player); + return isIn(block.getLocation(), region, ClansMainTutorial.Bounds.LAND_CLAIM); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/AttackEnemyObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/AttackEnemyObjective.java new file mode 100644 index 000000000..2b6449d02 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/AttackEnemyObjective.java @@ -0,0 +1,211 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import mineplex.core.common.DefaultHashMap; +import mineplex.core.common.util.C; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.siege.weapon.Cannon; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.HoldItemGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.BlowUpWallGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.ClanInfoGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.GetMapGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.LoadCannonGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.MountCannonGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.StealEnemyPotatoesGoal; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.entity.Zombie; +import org.bukkit.event.EventHandler; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.Vector; + +public class AttackEnemyObjective extends OrderedObjective +{ + private Map _cannon; + + private DefaultHashMap> _shooters; + + public AttackEnemyObjective(ClansMainTutorial clansMainTutorial, ClansManager clansManager, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Enemy Clans Tutorial", "Attack and raid this enemy!"); + + _cannon = new HashMap<>(); + _shooters = new DefaultHashMap<>(username -> new ArrayList<>()); + + addGoal(new GetMapGoal(this)); + addGoal(new HoldItemGoal( + this, Material.MAP, + "Identify Enemy on Map", + "Find the Red Square on your Map.", + "Look at your map to help find where the Enemy Clan is. It's marked by " + + "a " + C.cRed + "Red Square" + C.mBody + ".", + 40 + )); + addGoal(new ClanInfoGoal(this)); + addGoal(new MountCannonGoal(this, clansManager)); + addGoal(new LoadCannonGoal(this)); + addGoal(new BlowUpWallGoal(this)); + addGoal(new StealEnemyPotatoesGoal(this)); + + setStartMessageDelay(60); + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getPlugin().getCenter(session.getRegion(), ClansMainTutorial.Bounds.ENEMY_LAND)); + + addShooter("Chiss", getPlugin().getPoint(getPlugin().getRegion(player), ClansMainTutorial.Point.NPC_2), player); + addShooter("defek7", getPlugin().getPoint(getPlugin().getRegion(player), ClansMainTutorial.Point.NPC_1), player); + } + + private void addShooter(String name, Location location, Player active) + { + System.out.println("Adding shooter " + _shooters.get(active.getName()).size() + 1); + + Zombie shooter = location.getWorld().spawn(location.add(.5, 0, .8), Zombie.class); + + shooter.setCustomName(name); + shooter.setCustomNameVisible(true); + + UtilEnt.Vegetate(shooter); + + shooter.teleport(location); + shooter.setHealth(shooter.getMaxHealth()); + + shooter.getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); + shooter.getEquipment().setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1)); + shooter.getEquipment().setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + shooter.getEquipment().setHelmet(new ItemStack(Material.GOLD_HELMET, 1)); + + _shooters.get(active.getName()).add(shooter); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() == UpdateType.FASTER) + { + for (Player player : getActivePlayers()) + { + _shooters.get(player.getName()).forEach(shooter -> { + shooter.setHealth(shooter.getMaxHealth()); + + shooter.getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); + shooter.getEquipment().setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1)); + shooter.getEquipment().setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + shooter.getEquipment().setHelmet(new ItemStack(Material.GOLD_HELMET, 1)); + + if (player.getLocation().distance(shooter.getLocation()) > 16) + { + return; + } + + UtilEnt.LookAt(shooter, player.getEyeLocation()); + + if (Recharge.Instance.usable(player, "ShotBy" + shooter.getUniqueId().toString())) + { + Arrow arrow = shooter.shootArrow(); + + arrow.setVelocity(UtilAlg.getTrajectory(arrow.getLocation(), player.getEyeLocation()).multiply(1.6)); + + Recharge.Instance.use(player, "ShotBy" + shooter.getUniqueId().toString(), 500 + UtilMath.r(2000), false, false); + } + }); + + EnclosedObject kill = new EnclosedObject<>(Boolean.FALSE); + + _shooters.get(player.getName()).forEach(shooter -> { + if (player.getLocation().distance(shooter.getLocation()) < 5) + { + kill.Set(Boolean.TRUE); + } + }); + + if (kill.Get().booleanValue()) + { + _shooters.get(player.getName()).forEach(shooter -> { + UtilParticle.PlayParticle(ParticleType.LARGE_SMOKE, shooter.getLocation().add(0, .5, 0), new Vector(0d, 0d, 0d), 0.2f, 15, ViewDist.MAX, player); + UtilParticle.PlayParticle(ParticleType.SMOKE, shooter.getLocation().add(0, .5, 0), new Vector(0d, 0d, 0d), 0.2f, 15, ViewDist.MAX, player); + player.playSound(player.getLocation(), Sound.LAVA_POP, 1.0f, 1.0f); + shooter.remove(); + }); + + _shooters.get(player.getName()).clear(); + } + + if (player.getHealth() <= 6) + { + player.setHealth(6); + } + } + } + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + public void clean(Player player, TutorialRegion region) + { + super.clean(player, region); + + System.out.println("Clearing shooters"); + + _shooters.get(player.getName()).forEach(shooter -> { + shooter.remove(); + }); + + _shooters.get(player.getName()).clear(); + } + + @Override + protected void customFinish(Player player) + { + System.out.println("Clearing shooters"); + + _shooters.get(player.getName()).forEach(shooter -> { + shooter.remove(); + }); + + _shooters.get(player.getName()).clear(); + } + + public Map getCannons() + { + return _cannon; + } + + public DefaultHashMap> getShooters() + { + return _shooters; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClanObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClanObjective.java new file mode 100644 index 000000000..2374ae9bd --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClanObjective.java @@ -0,0 +1,39 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan.*; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.BlowUpWallGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy.StealEnemyPotatoesGoal; + +public class ClanObjective extends OrderedObjective +{ + public ClanObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Clans Tutorial", "Create clan with /c create "); + + addGoal(new LeaveSpawnGoal(this)); + addGoal(new CreateClanGoal(this)); + addGoal(new ClanManagementGoal(this)); + addGoal(new ClaimLandGoal(this)); + addGoal(new BuildHouseGoal(this)); + addGoal(new SetHomeGoal(this)); + + // Wait 1 second because the player is logging in/loading + setStartMessageDelay(20); + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClassesObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClassesObjective.java new file mode 100644 index 000000000..671596940 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ClassesObjective.java @@ -0,0 +1,44 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes.EquipDefaultBuildGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes.OpenClassManagerGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes.UseBullsChargeGoal; + +public class ClassesObjective extends OrderedObjective +{ + public ClassesObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Classes Tutorial", "Learn to use our fully customizable classes"); + + addGoal(new EquipDefaultBuildGoal(this)); + addGoal(new OpenClassManagerGoal(this)); + addGoal(new UseBullsChargeGoal(this)); + + setStartMessageDelay(60); + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(null); + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/EnergyObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/EnergyObjective.java new file mode 100644 index 000000000..ecced2abd --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/EnergyObjective.java @@ -0,0 +1,42 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.energy.BuyEnergyGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.energy.ExplainEnergyGoal; + +public class EnergyObjective extends OrderedObjective +{ + public EnergyObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Energy Tutorial", "A Clan requires Energy to maintain all of it's territory."); + + addGoal(new ExplainEnergyGoal(this)); + addGoal(new BuyEnergyGoal(this)); + + setStartMessageDelay(60); + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getPlugin().getPoint(session.getRegion(), ClansMainTutorial.Point.ENERGY_SHOP)); + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FieldsObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FieldsObjective.java new file mode 100644 index 000000000..7ff835cc3 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FieldsObjective.java @@ -0,0 +1,56 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.C; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.HoldItemGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields.GoToFieldsGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields.MineDiamondsGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields.SellDiamondsGoal; + +public class FieldsObjective extends OrderedObjective +{ + public FieldsObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Fields Tutorial", "Get various resources by mining for them in the fields"); + + addGoal(new HoldItemGoal( + this, + Material.MAP, + "Identify Fields on Map", + "Find the Orange Striped Area on your Map", + "Fields are marked by " + C.cGold + "Orange Stripes" + C.mBody + ".", + 80L + )); + addGoal(new GoToFieldsGoal(this)); + addGoal(new MineDiamondsGoal(this)); + addGoal(new SellDiamondsGoal(this)); + +// setStartMessageDelay(60); + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getPlugin().getCenter(session.getRegion(), ClansMainTutorial.Bounds.FIELDS)); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FinalObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FinalObjective.java new file mode 100644 index 000000000..9ea92b621 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/FinalObjective.java @@ -0,0 +1,42 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.finalobj.DisbandClanGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.finalobj.TpClanHomeGoal; + +public class FinalObjective extends OrderedObjective +{ + public FinalObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Clans Tutorial 2", "Finalize your knowledge of Clans"); + + addGoal(new TpClanHomeGoal(this)); // IMPLEMENTED + addGoal(new DisbandClanGoal(this)); // IMPLEMENTED + + setStartMessageDelay(60); + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(null); + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/PurchaseItemsObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/PurchaseItemsObjective.java new file mode 100644 index 000000000..b86ab328e --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/PurchaseItemsObjective.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilFirework; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import org.bukkit.*; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.UnorderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops.PurchaseGoal; + +import java.util.List; +import java.util.UUID; + +public class PurchaseItemsObjective extends UnorderedObjective +{ + public PurchaseItemsObjective(ClansMainTutorial clansMainTutorial, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Purchase Items Tutorial", "Purchase Items from Shop"); + + addGoal(new PurchaseGoal( + this, + Material.IRON_HELMET, + "Purchase Iron Helmet", + "Buy an Iron Helmet from the PvP Gear NPC", + "The shops sell everything you could ever need and more. Buy armour from the " + C.cYellow + "PvP NPC." + )); + addGoal(new PurchaseGoal(this, Material.IRON_CHESTPLATE, "Purchase Iron Chestplate", + "Buy an Iron Chestplate")); + addGoal(new PurchaseGoal(this, Material.IRON_LEGGINGS, "Purchase Iron Leggings", + "Buy Iron Leggings")); + addGoal(new PurchaseGoal(this, Material.IRON_BOOTS, "Purchase Iron Boots", + "Buy Iron Boots")); + addGoal(new PurchaseGoal(this, Material.IRON_AXE, "Purchase Iron Axe", + "Buy an Iron Axe")); +// addGoal(new PurchaseGoal(this, Material.IRON_PICKAXE, "Purchase Iron Pickaxe", "Talk to the Pvp Gear NPC and purchase an Iron Pickaxe")); + + setStartMessageDelay(60); + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getPlugin().getPoint(session.getRegion(), ClansMainTutorial.Point.PVP_SHOP)); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void update(UpdateEvent event) { + if(!event.getType().equals(UpdateType.SEC_05)) return; + + for (Player player : getActivePlayers()) + { + if (player == null || !player.isOnline()) continue; + List locations = getPlugin().getRegion(player).getLocationMap().getSpongeLocations(DyeColor.BROWN); + if (locations == null) continue; + for(Location loc : locations) + { + UtilFirework.playFirework(loc, FireworkEffect.Type.BURST, Color.AQUA, true, true); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ShopsObjective.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ShopsObjective.java new file mode 100644 index 000000000..84090b451 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/ShopsObjective.java @@ -0,0 +1,119 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.npc.Npc; +import mineplex.core.npc.NpcManager; +import mineplex.database.tables.records.NpcsRecord; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.OrderedObjective; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.HoldItemGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops.GoToShopsGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops.SellPotatoesGoal; + +public class ShopsObjective extends OrderedObjective +{ + private HashMap> _npcMap; + private NpcManager _npcManager; + + public ShopsObjective(ClansMainTutorial clansMainTutorial, NpcManager npcManager, JavaPlugin javaPlugin) + { + super(clansMainTutorial, javaPlugin, "Shops Tutorial", "Learn your way around our shops"); + + _npcMap = new HashMap<>(); + _npcManager = npcManager; + + addGoal(new HoldItemGoal( + this, + Material.MAP, + "Identify Shops on Map", + "Find the Blue Striped Area on your map", + "Shops are marked on the map by the " + C.cDAqua + "Blue Stripes" + C.mBody + ".", + 60L + )); + addGoal(new GoToShopsGoal(this)); + addGoal(new SellPotatoesGoal(this)); + + setStartMessageDelay(60); + } + + @Override + public void clean(Player player, TutorialRegion region) + { + super.clean(player, region); + + if (_npcMap.containsKey(player.getUniqueId())) + { + _npcMap.get(player.getUniqueId()).forEach(npc -> _npcManager.removeFakeNpc(npc)); + } + } + + @Override + protected void customLeave(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @Override + protected void customStart(Player player) + { + super.customStart(player); + + TutorialRegion region = getPlugin().getRegion(player); + + + ArrayList npcs = new ArrayList<>(); + // Spawn NPC's + Location pvpGear = getPlugin().getPoint(region, ClansMainTutorial.Point.PVP_SHOP); + Location energyShop = getPlugin().getPoint(region, ClansMainTutorial.Point.ENERGY_SHOP); + Location farmingShop = getPlugin().getPoint(region, ClansMainTutorial.Point.FARMING_SHOP); + Location miningShop = getPlugin().getPoint(region, ClansMainTutorial.Point.MINING_SHOP); + npcs.add(spawnNpc(pvpGear, "Pvp Gear")); + npcs.add(spawnNpc(energyShop, "Energy Shop")); + npcs.add(spawnNpc(farmingShop, "Organic Produce")); + npcs.add(spawnNpc(miningShop, "Mining Shop")); + _npcMap.put(player.getUniqueId(), npcs); + + TutorialSession session = getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getPlugin().getCenter(session.getRegion(), ClansMainTutorial.Bounds.SHOPS)); + + } + + private Npc spawnNpc(Location location, String name) + { + NpcsRecord npcsRecord = new NpcsRecord(); + npcsRecord.setServer(_npcManager.getServerName()); + npcsRecord.setName(name); + npcsRecord.setWorld(location.getWorld().getName()); + npcsRecord.setX(location.getX()); + npcsRecord.setY(location.getY()); + npcsRecord.setZ(location.getZ()); + npcsRecord.setRadius(0D); + npcsRecord.setEntityType(EntityType.VILLAGER.name()); + npcsRecord.setAdult(true); + + Npc npc = new Npc(_npcManager, npcsRecord); + _npcManager.spawnNpc(npc); + _npcManager.addFakeNpc(npc); + return npc; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/HoldItemGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/HoldItemGoal.java new file mode 100644 index 000000000..dde20c741 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/HoldItemGoal.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.DefaultHashMap; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.objective.Objective; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; + +public class HoldItemGoal extends ObjectiveGoal> +{ + private DefaultHashMap> _ticksHeld = new DefaultHashMap<>(key -> new EnclosedObject<>(Integer.valueOf(0))); + private Material _material; + private long _holdTicks; + + public HoldItemGoal(Objective objective, Material material, String name, String description, String helpText, int startDelay, long holdTicks) + { + super(objective, name, description, helpText, null); + + _material = material; + _holdTicks = holdTicks; +// setStartMessageDelay(startDelay); + } + + public HoldItemGoal(Objective objective, Material material, String name, String description, String helpText, long holdTicks) + { + this(objective, material, name, description, helpText, 120, holdTicks); + } + + @Override + protected void customStart(Player player) + { + + } + + @Override + protected void customFinish(Player player) + { + _ticksHeld.remove(player.getName()); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + getActivePlayers().forEach(uuid -> + { + Player player = Bukkit.getPlayer(uuid); + + if (player != null && player.isOnline()) + { + if (player.getItemInHand() == null || player.getItemInHand().getType() != _material) + { + return; + } + + _ticksHeld.get(player.getName()).Set(Integer.valueOf(_ticksHeld.get(player.getName()).Get().intValue() + 1)); + + if (_ticksHeld.get(player.getName()).Get().intValue() >= 80) + { + finish(player); + } + } + }); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/BlowUpWallGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/BlowUpWallGoal.java new file mode 100644 index 000000000..23488e15a --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/BlowUpWallGoal.java @@ -0,0 +1,125 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + +import java.util.HashMap; + +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.entity.Zombie; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.fallingblock.FallingBlocks; +import mineplex.game.clans.clans.siege.events.SiegeWeaponExplodeEvent; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; + +public class BlowUpWallGoal extends ObjectiveGoal +{ + public BlowUpWallGoal(AttackEnemyObjective objective) + { + super( + objective, + "Blow up the Enemy Base", + "Left-Click to shoot TNT at the Enemy Base", + "TNT Cannons will rotate to the direction you are looking. Simply look at the Enemy Base, wait for it to rotate, and then FIRE!", + DyeColor.MAGENTA + ); + } + + @Override + protected void customStart(Player player) + { + TutorialSession session = getObjective().getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getObjective().getPlugin().getCenter(session.getRegion(), ClansMainTutorial.Bounds.ENEMY_ATTACK_AREA)); + } + + @EventHandler + public void siegeWeaponExplode(SiegeWeaponExplodeEvent event) + { + Player shooter = event.getProjectile().getShooter(); + + if (!contains(shooter)) + { + if (getObjective().getPlugin().isInTutorial(shooter)) + { + UtilPlayer.message(shooter, F.main("Clans", "No cheating! (:")); + event.setCancelled(true); + } + + return; + } + + Location center = event.getProjectile().getLocation(); + + TutorialRegion region = getObjective().getPlugin().getRegion(shooter); + + if (getObjective().getPlugin().isIn(center, region, ClansMainTutorial.Bounds.ENEMY_ATTACK_AREA)) + { + double radius = 5.2; + + HashMap blockList = new HashMap(); + int iR = (int) radius + 1; + + for (int x = -iR; x <= iR; x++) + { + for (int z = -iR; z <= iR; z++) + { + for (int y = -iR; y <= iR; y++) + { + Block curBlock = center.getBlock().getRelative(x, y, z); + + double offset = UtilMath.offset(center, curBlock.getLocation()); + + if (offset <= radius) + { + blockList.put(curBlock, Double.valueOf(offset)); + } + } + } + } + + blockList.forEach((block, dist) -> { + + if (block.getType() == Material.SMOOTH_BRICK + || block.getType() == Material.SMOOTH_STAIRS + || block.getType() == Material.IRON_DOOR_BLOCK) + + if (Math.random() < 0.2 + (dist.doubleValue() / 2.55) || dist.doubleValue() < 1.75) + { + block.setType(Material.AIR, false); + + if (block.getType() != Material.IRON_DOOR_BLOCK && block.getType().name().endsWith("BANNER")) + FallingBlocks.Instance.Spawn(block.getLocation(), block.getType(), block.getData(), center); + } + }); + + event.setCancelled(true); + finish(shooter); + } + else + { + UtilPlayer.message(shooter, F.main("Clans", "You missed! Try to hit the enemy's front wall, that should make a nice big hole!")); + UtilInv.give(shooter, Material.TNT); + event.setCancelled(true); + } + } + + @Override + protected void customFinish(Player player) + { + getObjective().getCannons().remove(player.getName()).kill(); //Kill cannon after goal complete + + getObjective().getShooters().get(player.getName()).forEach(Zombie::remove); + + getObjective().getShooters().get(player.getName()).clear(); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/ClanInfoGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/ClanInfoGoal.java new file mode 100644 index 000000000..f240f5c2a --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/ClanInfoGoal.java @@ -0,0 +1,92 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilTime; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClanRole; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.ClansPlayer; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.core.repository.tokens.ClanToken; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import java.sql.Timestamp; +import java.util.UUID; + + +public class ClanInfoGoal extends ObjectiveGoal +{ + public ClanInfoGoal(AttackEnemyObjective objective) + { + super( + objective, + "Lookup Enemy Details", + "View info about the enemy clan by typing '/c EnemyClan'", + "You can lookup details about your enemy before going for an " + + "attack! This can give you a crucial advantage before " + + "you fight.", + null + ); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onClanInfo(ClansCommandPreExecutedEvent event) + { + if (contains(event.getPlayer())) + { + if(event.getArguments().length < 1) return; + + event.setCancelled(true); + + if (!event.getArguments()[0].equalsIgnoreCase("EnemyClan")) + { + event.getPlayer().sendMessage(F.main("Clans", "That clan does not exist.")); + return; + } + + ClanToken token = new ClanToken(); + token.Name = "EnemyClan"; + token.Description = "Chiss"; + token.Home = ""; + token.Admin = false; + token.Energy = 4320; + token.Id = -1; + token.Kills = UtilMath.random.nextInt(100); + token.Murder = UtilMath.random.nextInt(100); + token.Deaths = UtilMath.random.nextInt(100); + token.WarWins = UtilMath.random.nextInt(100); + token.WarLosses = UtilMath.random.nextInt(100); + token.DateCreated = new Timestamp(System.currentTimeMillis() - (UtilTime.TimeUnit.DAYS.getMilliseconds() * 10)); + token.LastOnline = new Timestamp(System.currentTimeMillis() - (UtilTime.TimeUnit.DAYS.getMilliseconds() * 1)); + + ClanInfo clan = new ClanInfo(ClansManager.getInstance(), token); + + ClansPlayer chiss = new ClansPlayer("Chiss", UUID.fromString("1d2bfe61-7ebd-445d-ba7d-8354a0ffd1ea"), ClanRole.LEADER); + ClansPlayer jon = new ClansPlayer("defek7", UUID.fromString("89d463f7-23ec-470a-8244-457f0c8d861c"), ClanRole.MEMBER); + chiss.setOnline(true); + jon.setOnline(true); + + clan.getMembers().put(chiss.getUuid(), chiss); + clan.getMembers().put(jon.getUuid(), jon); + + ClansManager.getInstance().getClanShop().openClanWho(event.getPlayer(), clan); + finish(event.getPlayer()); + + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/GetMapGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/GetMapGoal.java new file mode 100644 index 000000000..c1301087f --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/GetMapGoal.java @@ -0,0 +1,57 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.C; +import mineplex.game.clans.clans.map.events.PlayerGetMapEvent; +import mineplex.game.clans.clans.siege.weapon.Cannon; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; + +public class GetMapGoal extends ObjectiveGoal +{ + public GetMapGoal(AttackEnemyObjective objective) + { + super( + objective, + "Get a Map", + "Type '/map' to get a Map", + "You can get a Map any time you need one. The map will show you who " + + "owns the land around the map. Your clan is " + C.cAqua + "blue" + + C.mBody + ", your allies are " + C.cGreen + "green" + C.mBody + ", " + + "and your enemies are " + C.cRed + "red" + C.mBody + ".", + null + ); + +// setStartMessageDelay(120); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onGetMap(PlayerGetMapEvent event) + { + if (getObjective().getPlugin().isInTutorial(event.getPlayer())) + { + event.setCancelled(true); + getObjective().getPlugin().getMapManager().setMap(event.getPlayer()); + + if (contains(event.getPlayer())) + { + finish(event.getPlayer()); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/LoadCannonGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/LoadCannonGoal.java new file mode 100644 index 000000000..81ca051c6 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/LoadCannonGoal.java @@ -0,0 +1,46 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.UtilInv; +import mineplex.game.clans.clans.siege.events.LoadSiegeWeaponEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; + +public class LoadCannonGoal extends ObjectiveGoal +{ + public LoadCannonGoal(AttackEnemyObjective objective) + { + super( + objective, + "Load the Cannon", + "Right-Click while on the Cannon, and insert your TNT", + "TNT Cannons require TNT to be able to shoot. You can also change the range your cannon fires in the Cannon Menu.", + null + ); + } + + @Override + protected void customStart(Player player) + { + UtilInv.give(player, Material.TNT); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onSiegeWeaponLoad(LoadSiegeWeaponEvent event) + { + if (!contains(event.getPlayer())) + { + return; + } + + finish(event.getPlayer()); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/MountCannonGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/MountCannonGoal.java new file mode 100644 index 000000000..c7bf9a287 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/MountCannonGoal.java @@ -0,0 +1,70 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.siege.events.MountSiegeWeaponEvent; +import mineplex.game.clans.clans.siege.weapon.Cannon; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial.Point; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; + +import org.bukkit.DyeColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +public class MountCannonGoal extends ObjectiveGoal +{ + private ClansManager _clansManager; + + public MountCannonGoal(AttackEnemyObjective objective, ClansManager clansManager) + { + super( + objective, + "Get on the Cannon", + "Right-Click on the Cannon", + "You cannot break blocks in enemy territory, however you can blow them up! " + + "TNT Cannons are the best way to do destroy enemy bases!", + DyeColor.BLACK + ); + + _clansManager = clansManager; + } + + @Override + protected void customStart(Player player) + { + getObjective().getCannons().put(player.getName(), _clansManager.getSiegeManager().spawnCannon(player, getObjective().getPlugin().getPoint(getObjective().getPlugin().getRegion(player), Point.CANNON), false)); + getObjective().getCannons().get(player.getName()).SetForcedVelocity(0.4, 2.45); + getObjective().getCannons().get(player.getName()).setInvincible(true); + + TutorialSession session = getObjective().getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getObjective().getPlugin().getPoint(session.getRegion(), ClansMainTutorial.Point.CANNON)); + } + + @Override + protected void clean(Player player, TutorialRegion region) + { + // This cannon could be removed from the tutorial already in BlowUpWallGoal, we need to check if its null + Cannon cannon = getObjective().getCannons().remove(player.getName()); + if (cannon != null) + cannon.kill(); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onSiegeWeaponMount(MountSiegeWeaponEvent event) + { + if (!contains(event.getPlayer())) + { + return; + } + + finish(event.getPlayer()); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/StealEnemyPotatoesGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/StealEnemyPotatoesGoal.java new file mode 100644 index 000000000..1f4261568 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/attackenemy/StealEnemyPotatoesGoal.java @@ -0,0 +1,129 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.attackenemy; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import mineplex.core.common.util.UtilBlock; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.entity.EntityInteractEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; + +import mineplex.core.common.DefaultHashMap; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; + +public class StealEnemyPotatoesGoal extends ObjectiveGoal +{ + private DefaultHashMap _playersMap = new DefaultHashMap<>(uuid -> new AtomicInteger()); + + public StealEnemyPotatoesGoal(AttackEnemyObjective objective) + { + super( + objective, + "Steal Potatoes", + "Steal potatoes from the Enemy Clan’s base", + "Raiding enemy bases is one of the best parts of Clans! There's nothing better than looting Legendary weapons from enemies!", + DyeColor.PURPLE + ); + } + + @Override + public String getDescription(Player player) + { + int count = _playersMap.get(player.getUniqueId()).get(); + return "Steal potatoes from the Enemy Clan’s base " + count + "/10"; + } + + @Override + protected void customStart(Player player) + { + _playersMap.put(player.getUniqueId(), new AtomicInteger(0)); + + TutorialSession session = getObjective().getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getObjective().getPlugin().getCenter(session.getRegion(), ClansMainTutorial.Bounds.ENEMY_LAND)); + + UtilBlock.getInRadius( + getObjective().getPlugin().getRegion(player).getLocationMap().getSpongeLocations(DyeColor.MAGENTA).get(0), 5). + keySet().stream().filter(block -> block.getType().name().contains("IRON_DOOR")).forEach(block -> + block.setType(Material.AIR) + ); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onEntityInteract(EntityInteractEvent event) + { + if (!(event.getEntity() instanceof Player)) + { + return; + } + + if (!getObjective().getPlugin().isInTutorial((Player) event.getEntity())) + { + return; + } + + if (event.getBlock().getType() == Material.SOIL && event.getEntity() instanceof Creature) + { + event.setCancelled(true); + } + } + + @EventHandler + public void onBlockBreak(BlockDamageEvent event) + { + if (!contains(event.getPlayer()) || event.getBlock().getType() != Material.POTATO) + return; + + TutorialRegion region = getObjective().getPlugin().getRegion(event.getPlayer()); + if (getObjective().getPlugin().isIn(event.getBlock().getLocation().add(0, 1, 0), region, ClansMainTutorial.Bounds.ENEMY_LAND)) + { + event.setCancelled(true); + event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.5, 0.5), new ItemStack(Material.POTATO_ITEM)); + event.getBlock().setType(Material.AIR); + + Bukkit.getServer().getScheduler().runTaskLater(getObjective().getJavaPlugin(), new Runnable() + { + @Override + public void run() + { + if (contains(event.getPlayer())) + { + event.getBlock().setType(Material.POTATO); + } + } + }, 20 * 10); + } + } + + @EventHandler + public void onItemPickup(PlayerPickupItemEvent event) + { + if (!contains(event.getPlayer())) + return; + + if (event.getItem().getItemStack().getType() == Material.POTATO_ITEM) + { + int count = _playersMap.get(event.getPlayer().getUniqueId()).incrementAndGet(); + if (count == 10) + finish(event.getPlayer()); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/BuildHouseGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/BuildHouseGoal.java new file mode 100644 index 000000000..4c26307cb --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/BuildHouseGoal.java @@ -0,0 +1,94 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import java.util.List; + +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +import com.google.common.collect.Lists; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; + +public class BuildHouseGoal extends ObjectiveGoal +{ + private List _items = Lists.newArrayList( + new ItemStack(Material.SMOOTH_BRICK, 54), + new ItemStack(Material.TORCH, 2), + new ItemStack(Material.IRON_DOOR, 1) + ); + + + public BuildHouseGoal(ClanObjective objective) + { + super( + objective, + "Build a House", + "Build a House (place all your blocks)", + "The first thing you should do on your land is build a house, even " + + "if it’s made of dirt! This will give you a safe place to store your loot!", + DyeColor.ORANGE + ); + } + + @Override + protected void customStart(Player player) + { + _items.forEach(item -> { + player.getInventory().addItem(item); + }); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler (priority = EventPriority.HIGHEST) + public void blockPlace(BlockPlaceEvent event) + { + if (!getObjective().getPlugin().isInTutorial(event.getPlayer())) + { + return; + } + + event.setCancelled(false); + + + if (getObjective().getPlugin().isInBuildArea(event.getPlayer(), event.getBlock())) + { + // Run 1 tick later because inventory doesn't get updated instantly + ClansManager.getInstance().runSync(() -> { + boolean ja = true; + for (ItemStack stack : event.getPlayer().getInventory().getContents()) + { + if (stack == null) + continue; + + for (ItemStack other : _items) + if (stack.getType() == other.getType()) + { + ja = false; + break; + } + } + + if (ja) // JA! + finish(event.getPlayer()); + }); + } + else + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You are not allowed to place blocks here.")); + event.setCancelled(true); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClaimLandGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClaimLandGoal.java new file mode 100644 index 000000000..93d82a088 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClaimLandGoal.java @@ -0,0 +1,76 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import java.util.List; + +import mineplex.core.common.util.C; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.event.PlayerPreClaimTerritoryEvent; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; +import org.bukkit.event.EventPriority; + +public class ClaimLandGoal extends ObjectiveGoal +{ + public ClaimLandGoal(ClanObjective objective) + { + super( + objective, + "Claim Land", + "Type '/c' to Claim Land using the Clan Menu", + "Clans are able to claim land for themselves. " + + "Once claimed, no one else can break or place blocks there! " + + "You must be inside the " + C.cAqua + "blue" + C.cGray + " outline to claim land.", + DyeColor.ORANGE + ); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + TutorialRegion region = getObjective().getPlugin().getRegion(player); + List blocks = region.getLocationMap().getGoldLocations(ClansMainTutorial.Bounds.LAND_CLAIM.getDataLocColor()); + UtilAlg.getBox(blocks.get(0).getBlock(), blocks.get(1).getBlock()).stream().filter(block -> block.getType() == Material.WOOL) + .forEach(block -> block.setType(Material.GLOWSTONE)); + } + + @EventHandler + public void onClaim(PlayerPreClaimTerritoryEvent event) + { + if (contains(event.getClaimer())) + { + if (getObjective().getPlugin().isIn(event.getClaimer(), ClansMainTutorial.Bounds.LAND_CLAIM)) + { + finish(event.getClaimer()); + } + else + { + UtilPlayer.message(event.getClaimer(), F.main("Tutorial", "You must claim the land inside the blue outline")); + } + + event.setCancelled(true); + } + } + + + @EventHandler (priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Territory)) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanDetailsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanDetailsGoal.java new file mode 100644 index 000000000..fed068ddf --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanDetailsGoal.java @@ -0,0 +1,63 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; +import org.bukkit.event.EventPriority; + +public class ClanDetailsGoal extends ObjectiveGoal +{ + public ClanDetailsGoal(ClanObjective objective) + { + super(objective, "View Clan Details", "View Clan Details with /c"); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @Override + public String getDescription(Player player) + { + ClanInfo clan = ClansManager.getInstance().getClan(player); + if (clan != null) + { + return "View Clan Details with /c " + clan.getName(); + } + else + { + return "View Clan Details"; + } + } + + @EventHandler + public void onClanInfo(ClansCommandExecutedEvent event) + { + if (contains(event.getPlayer())) + { + if (event.getCommand().equalsIgnoreCase("info")) + { + finish(event.getPlayer()); + } + } + } + + + @EventHandler (priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && (event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Who))) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanManagementGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanManagementGoal.java new file mode 100644 index 000000000..b74e7d678 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/ClanManagementGoal.java @@ -0,0 +1,60 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import mineplex.core.common.util.F; +import mineplex.game.clans.clans.ClanInfo; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; + +/** + * Created by Adam on 29/03/2016. + */ +public class ClanManagementGoal extends ObjectiveGoal +{ + public ClanManagementGoal(ClanObjective objective) + { + super( + objective, + "Open the Clan Menu", + "Type '/c' to open the Clan Menu", + "Clan Menu lets you do lots of Clans actions, and view information about your Clan. Take a moment to look at it all!", + null + ); + } + + @Override + protected void customStart(Player player) + { + player.sendMessage(F.main("Clans", "You can use the command /c to manage your clan.")); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onClanInfo(ClansCommandPreExecutedEvent event) + { + if (contains(event.getPlayer())) + { + if (event.getArguments() == null || event.getArguments().length == 0) + { + finish(event.getPlayer()); + } + } + } + + + @EventHandler (priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Energy)) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/CreateClanGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/CreateClanGoal.java new file mode 100644 index 000000000..693b7cda2 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/CreateClanGoal.java @@ -0,0 +1,61 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import mineplex.core.common.util.F; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClanCreationCompleteEvent; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; +import org.bukkit.event.EventPriority; + +public class CreateClanGoal extends ObjectiveGoal +{ + public CreateClanGoal(ClanObjective objective) + { + super( + objective, + "Create a Clan", + "Type '/c create ' to create a new Clan", + F.elem("Clans") + " are groups of players that can claim land, build fortresses, " + + "and fight epic battles. Together they will challenge other clans for " + + "control of the land.", + null + ); + } + + @Override + protected void customStart(Player player) + { + + if (ClansManager.getInstance().getClan(player) != null) + { + finish(player); + } + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void onClanCreate(ClanCreationCompleteEvent event) + { + if (contains(event.getFounder())) + { + finish(event.getFounder()); + ClansManager.getInstance().resetLeftTimer(event.getFounder().getUniqueId()); + } + } + + + @EventHandler (priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Create)) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/LeaveSpawnGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/LeaveSpawnGoal.java new file mode 100644 index 000000000..3de4a6674 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/LeaveSpawnGoal.java @@ -0,0 +1,79 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import java.util.HashSet; +import java.util.UUID; + +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; + +public class LeaveSpawnGoal extends ObjectiveGoal +{ + public LeaveSpawnGoal(ClanObjective objective) + { + super( + objective, + "Leave Spawn Island", + "Jump off Spawn Island", + F.elem("Spawn Island") + " is where you will respawn when you die. This area is " + + "a " + F.elem("Safe Zone") + ", meaning that players cannot hurt each other. " + + "From here, you can teleport to various places, as well as read some helpful " + + "hints.", + DyeColor.WHITE + ); + + // 2 seconds after start message + setStartMessageDelay(20 * 11); + } + + @Override + protected void setup(Player player, TutorialRegion region) + { + + } + + @Override + protected void customStart(Player player) + { + player.getInventory().clear(); + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void onCommand(ClansCommandPreExecutedEvent event) + { + if(contains(event.getPlayer())) event.setCancelled(true); + } + + @EventHandler + public void checkRegion(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + return; + + for (UUID uuid : getActivePlayers()) + { + Player player = Bukkit.getPlayer(uuid); + if(player == null || !player.isOnline()) continue; + if (!getObjective().getPlugin().isIn(player, ClansMainTutorial.Bounds.SPAWN)) + { + finish(Bukkit.getPlayer(uuid)); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/SetHomeGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/SetHomeGoal.java new file mode 100644 index 000000000..d8a8042f9 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/clan/SetHomeGoal.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.clan; + +import mineplex.core.common.util.UtilBlock; +import net.minecraft.server.v1_8_R3.EnumDirection; +import org.bukkit.DyeColor; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilWorld; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClanObjective; + +public class SetHomeGoal extends ObjectiveGoal +{ + public SetHomeGoal(ClanObjective objective) + { + super( + objective, + "Set Clan Home", + "Type '/c sethome' to set your Clan's Home", + "Your Clan Home is a special place in your base that you can teleport " + + "to from " + F.elem("Spawn Island") + " or at any time by typing " + F.elem("/c home") + ".", + DyeColor.ORANGE + ); + + setDisplayFinishMessage(false); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onSetHome(ClansCommandPreExecutedEvent event) + { + if (contains(event.getPlayer()) && event.getArguments().length == 1 && event.getArguments()[0].equalsIgnoreCase("sethome")) + { + event.setCancelled(true); //before checking if bed placed + + if (getObjective().getPlugin().isIn(event.getPlayer(), ClansMainTutorial.Bounds.LAND_CLAIM)) + { + boolean bedPlaced = UtilBlock.placeBed(event.getPlayer().getLocation(), BlockFace.valueOf(EnumDirection.fromAngle(event.getPlayer().getLocation().getYaw()).name()), false, false); + + if (!bedPlaced) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "This is not a suitable place for a bed.")); + return; + } + + // we need to save this for later when the player teleports home! + getObjective().getPlugin().getTutorialSession(event.getPlayer()).setHomeLocation(event.getPlayer().getLocation()); + + finish(event.getPlayer()); + + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You have successfully set your Clan's Home to " + UtilWorld.locToStrClean(event.getPlayer().getLocation()) + ".")); + } + else + { + UtilPlayer.message(event.getPlayer(), F.main("Tutorial", "You must set your home in your own land claim.")); + } + + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/EquipDefaultBuildGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/EquipDefaultBuildGoal.java new file mode 100644 index 000000000..9eb963c44 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/EquipDefaultBuildGoal.java @@ -0,0 +1,46 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClassesObjective; +import mineplex.minecraft.game.classcombat.Class.event.ClassEquipEvent; + +public class EquipDefaultBuildGoal extends ObjectiveGoal +{ + public EquipDefaultBuildGoal(ClassesObjective objective) + { + super( + objective, + "Equip Armor", + "Put on your Iron Armor", + "When you wear a full set of armor, it will equip a class! The Iron set makes you " + + "into a Knight. Each class has different skills and is strong in its own way.", + null + ); + +// setStartMessageDelay(120); + } + + @Override + protected void customStart(Player player) + { + + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void classEquip(ClassEquipEvent event) + { + if (contains(event.getUser())) + { + finish(event.getUser()); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/OpenClassManagerGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/OpenClassManagerGoal.java new file mode 100644 index 000000000..a67f38855 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/OpenClassManagerGoal.java @@ -0,0 +1,59 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes; + +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerInteractEvent; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilEvent; +import mineplex.core.common.util.UtilEvent.ActionType; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClassesObjective; + +public class OpenClassManagerGoal extends ObjectiveGoal +{ + public OpenClassManagerGoal(ClassesObjective objective) + { + super( + objective, "Open Class Manager", + "Right-Click on the Enchantment Table", + "Each class has lots of different skills, and you can pick which ones you want to " + + "equip! Right-Click on an " + F.elem("Enchanting Table") + " to have a look at " + + "this menu.", + DyeColor.CYAN + ); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void interact(PlayerInteractEvent event) + { + if (!contains(event.getPlayer())) + { + return; + } + + if (!UtilEvent.isAction(event, ActionType.R_BLOCK)) + { + return; + } + + if (!event.getClickedBlock().getType().equals(Material.ENCHANTMENT_TABLE)) + { + return; + } + + finish(event.getPlayer()); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/SelectBullsChargeGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/SelectBullsChargeGoal.java new file mode 100644 index 000000000..bc31e43e6 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/SelectBullsChargeGoal.java @@ -0,0 +1,66 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClassesObjective; +import mineplex.minecraft.game.classcombat.Class.ClientClass; +import mineplex.minecraft.game.classcombat.Class.IPvpClass; +import mineplex.minecraft.game.classcombat.Skill.ISkill; + +public class SelectBullsChargeGoal extends ObjectiveGoal +{ + public SelectBullsChargeGoal(ClassesObjective objective) + { + super(objective, "Open Class Manager", "Using the Class Manager, choose Bulls Charge for your Axe Skill"); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + getActivePlayers().forEach(uuid -> { + Player player = UtilPlayer.searchExact(uuid); + + if (player == null || !player.isOnline()) + { + return; + } + + ClientClass client = ClansManager.getInstance().getClassManager().Get(player); + + if (client.GetGameClass() != null) + { + IPvpClass gameClass = client.GetGameClass(); + + for (ISkill skill : gameClass.GetSkills()) + { + if (skill.GetName().toLowerCase().contains("bulls charge")) + { + finish(player); + break; + } + } + } + }); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/UseBullsChargeGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/UseBullsChargeGoal.java new file mode 100644 index 000000000..6c17de60c --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/classes/UseBullsChargeGoal.java @@ -0,0 +1,50 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.classes; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilEvent; +import mineplex.game.clans.clans.ClansManager; +import mineplex.minecraft.game.classcombat.Class.ClassManager; +import mineplex.minecraft.game.classcombat.Class.ClientClass; +import mineplex.minecraft.game.classcombat.Class.IPvpClass; +import mineplex.minecraft.game.classcombat.Class.event.ClassEquipEvent; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ClassesObjective; +import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class UseBullsChargeGoal extends ObjectiveGoal { + public UseBullsChargeGoal(ClassesObjective objective) { + super( + objective, + "Use Bulls Charge", + "Right-Click with Axe to use Bulls Charge", + "One of your default abilities as Knight is Bulls Charge. This ability will make " + + "you run faster for a short time, and deal extra damage to enemies.", + null + ); + } + + @Override + protected void customStart(Player player) { + ClientClass client = ClansManager.getInstance().getClassManager().Get(player); + + client.ResetSkills(player); + client.SetActiveCustomBuild(client.GetGameClass(), client.GetGameClass().getDefaultBuild()); + } + + @Override + protected void customFinish(Player player) { + } + + @EventHandler + public void checkSkill(SkillTriggerEvent event) { + if (contains(event.GetPlayer())) { + finish(event.GetPlayer()); + } + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/BuyEnergyGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/BuyEnergyGoal.java new file mode 100644 index 000000000..40ab1a5cc --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/BuyEnergyGoal.java @@ -0,0 +1,64 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.energy; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.game.clans.clans.ClansManager; +import org.bukkit.DyeColor; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.clans.event.EnergyPageBuildEvent; +import mineplex.game.clans.clans.event.PreEnergyShopBuyEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.EnergyObjective; + +public class BuyEnergyGoal extends ObjectiveGoal +{ + public BuyEnergyGoal(EnergyObjective objective) + { + super( + objective, + "Buy Energy", + "Buy Clan Energy from the Energy Shop", + "You can buy Clan Energy at the Shops.", + DyeColor.RED + ); + } + + @Override + protected void customStart(Player player) + { + ClansManager.getInstance().runSyncLater(() -> { + UtilPlayer.message(player, F.main("Clans", "WARNING: Clan Energy is running very low!")); + UtilTextMiddle.display("Clan Energy", "is running very low", 10, 100, 10, player); + + player.playSound(player.getLocation(), Sound.NOTE_BASS, 1.0f, 1.0f); + }, 3L); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void energyBuy(PreEnergyShopBuyEvent event) + { + if (contains(event.getPlayer())) + { + finish(event.getPlayer()); + event.getPlayer().closeInventory(); + } + } + + @EventHandler + public void energyBuild(EnergyPageBuildEvent event) + { + if (contains(event.getPlayer())) + { + event.setFree(true); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/ExplainEnergyGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/ExplainEnergyGoal.java new file mode 100644 index 000000000..f4267c521 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/energy/ExplainEnergyGoal.java @@ -0,0 +1,57 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.energy; + +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.EnergyObjective; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; + +public class ExplainEnergyGoal extends ObjectiveGoal +{ + public ExplainEnergyGoal(EnergyObjective objective) + { + super( + objective, + "Check your Clans Energy", + "Type '/c' to check your Clans Energy", + "Owning land isn’t free! You will need to buy Energy from the Shops to retain " + + "ownership of it. If your Clan Energy ever reaches 0, you will lose your " + + "land claims!", + null + ); + } + + @Override + protected void customStart(Player player) + { + player.playSound(player.getLocation(), Sound.NOTE_PLING, 1.0f, 1.0f); + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void onCommand(ClansCommandPreExecutedEvent event) + { + if(contains(event.getPlayer()) && event.getArguments().length == 0) + { + finish(event.getPlayer()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Energy)) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/GoToFieldsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/GoToFieldsGoal.java new file mode 100644 index 000000000..0e416501e --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/GoToFieldsGoal.java @@ -0,0 +1,75 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields; + +import java.util.UUID; + +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.UtilAlg; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FieldsObjective; + +public class GoToFieldsGoal extends ObjectiveGoal +{ + public GoToFieldsGoal(FieldsObjective objective) + { + super( + objective, + "Go to the Fields", + "Go to the Fields", + "The Fields are a very dangerous place where players come to fight and harvest " + + "resources!", + DyeColor.YELLOW + ); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void openGates(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTER) + { + return; + } + + for (UUID uuid : getActivePlayers()) + { + if(UtilPlayer.searchExact(uuid) == null) return; + + getObjective().getPlugin().performGateCheck(UtilPlayer.searchExact(uuid), DyeColor.RED); + } + } + + @EventHandler + public void checkRegion(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + return; + + for (UUID uuid : getActivePlayers()) + { + Player player = UtilPlayer.searchExact(uuid); + if(player == null || !player.isOnline()) continue; + if (getObjective().getPlugin().isIn(player, ClansMainTutorial.Bounds.FIELDS)) + { + finish(player); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/IdentifyFieldsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/IdentifyFieldsGoal.java new file mode 100644 index 000000000..a4c9186e4 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/IdentifyFieldsGoal.java @@ -0,0 +1,64 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.DefaultHashMap; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.clans.map.events.PlayerGetMapEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.objective.AttackEnemyObjective; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FieldsObjective; + +public class IdentifyFieldsGoal extends ObjectiveGoal +{ + private DefaultHashMap> _ticksHeld = new DefaultHashMap<>(key -> new EnclosedObject<>(Integer.valueOf(0))); + + public IdentifyFieldsGoal(FieldsObjective objective) + { + super(objective, "Identify The Fields", "By looking at your map, identify where the Fields are"); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + { + return; + } + + getActivePlayers().forEach(uuid -> { + Player player = Bukkit.getPlayer(uuid); + + if (player != null && player.isOnline()) + { + if (player.getItemInHand() == null || player.getItemInHand().getType() != Material.MAP) + { + return; + } + + _ticksHeld.get(player.getName()).Set(Integer.valueOf(_ticksHeld.get(player.getName()).Get().intValue() + 1)); + + if (_ticksHeld.get(player.getName()).Get().intValue() >= 80) + { + finish(player); + } + } + }); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/MineDiamondsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/MineDiamondsGoal.java new file mode 100644 index 000000000..aca99b031 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/MineDiamondsGoal.java @@ -0,0 +1,112 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields; + +import java.util.HashMap; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; + +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.TutorialRegion; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FieldsObjective; + +public class MineDiamondsGoal extends ObjectiveGoal +{ + private HashMap _playersMap; + + public MineDiamondsGoal(FieldsObjective objective) + { + super( + objective, + "Mine Diamonds", + "Mine Diamonds in the Fields", + "Mining in the Fields is a great way to make lots of money! The ores will " + + "regenerate over time. Be careful of enemies though!", + DyeColor.LIME + ); + + _playersMap = new HashMap<>(); + } + + @Override + protected void customStart(Player player) + { + player.getInventory().addItem(new ItemStack(Material.IRON_PICKAXE)); + + _playersMap.put(player.getUniqueId(), new AtomicInteger(0)); + } + + @Override + protected void customFinish(Player player) + { + _playersMap.remove(player.getUniqueId()); + } + + @Override + protected void customLeave(Player player) + { + _playersMap.remove(player.getUniqueId()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBlockBreak(BlockBreakEvent event) + { + if (!contains(event.getPlayer()) || event.getBlock().getType() != Material.DIAMOND_ORE) + return; + + TutorialRegion region = getObjective().getPlugin().getRegion(event.getPlayer()); + if (getObjective().getPlugin().isIn(event.getBlock().getLocation(), region, ClansMainTutorial.Bounds.FIELDS)) + { + event.setCancelled(true); + event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 1.5, 0.5), new ItemStack(Material.DIAMOND)); + event.getBlock().setType(Material.COBBLESTONE); + + Bukkit.getServer().getScheduler().runTaskLater(getObjective().getJavaPlugin(), new Runnable() + { + @Override + public void run() + { + if (contains(event.getPlayer())) + { + event.getBlock().setType(Material.DIAMOND_ORE); + } + } + }, 20 * 10); + } + } + + @EventHandler + public void onItemPickup(PlayerPickupItemEvent event) + { + if (!contains(event.getPlayer())) + return; + + if (event.getItem().getItemStack().getType() == Material.DIAMOND) + { + if(_playersMap.get(event.getPlayer().getUniqueId()) == null) return; + int count = _playersMap.get(event.getPlayer().getUniqueId()).incrementAndGet(); + if (count == 10) + finish(event.getPlayer()); + } + } + + @Override + public String getDescription(Player player) + { + AtomicInteger count = _playersMap.get(player.getUniqueId()); + if (count == null) + return "Search for some diamonds in the Fields and mine them"; + else + return "Mine Diamonds " + count.get() + "/10"; + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/SellDiamondsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/SellDiamondsGoal.java new file mode 100644 index 000000000..e1dd69eee --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/fields/SellDiamondsGoal.java @@ -0,0 +1,61 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.fields; + +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.event.ClansPlayerSellItemEvent; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FieldsObjective; +import org.bukkit.event.EventPriority; + +public class SellDiamondsGoal extends ObjectiveGoal +{ + public SellDiamondsGoal(FieldsObjective objective) + { + super( + objective, + "Sell Diamonds", + "Sell your Diamonds to the Mining Shop", + "Go back to the Shops and sell your precious diamonds!", + DyeColor.SILVER + ); + } + + @Override + protected void customStart(Player player) + { + TutorialSession session = getObjective().getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getObjective().getPlugin().getPoint(session.getRegion(), ClansMainTutorial.Point.MINING_SHOP)); + } + + @Override + protected void customFinish(Player player) + { + // Close Middle Gate + getObjective().getPlugin().destroyFences(getObjective().getPlugin().getRegion(player), DyeColor.RED); + + // Close Fields Gate + getObjective().getPlugin().destroyFences(getObjective().getPlugin().getRegion(player), DyeColor.BLACK); + } + + @EventHandler (priority = EventPriority.HIGH) + public void onSell(ClansPlayerSellItemEvent event) + { + if (contains(event.getPlayer())) + { + if (event.getItem().getType() == Material.DIAMOND) + { + event.setCancelled(false); + UtilInv.removeAll(event.getPlayer(), Material.DIAMOND, (byte) 0); + finish(event.getPlayer()); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/DisbandClanGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/DisbandClanGoal.java new file mode 100644 index 000000000..60a243659 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/DisbandClanGoal.java @@ -0,0 +1,64 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.finalobj; + +import mineplex.game.clans.clans.event.ClanDisbandedEvent; +import mineplex.game.clans.clans.gui.events.ClansButtonClickEvent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; + +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.tutorial.objective.Objective; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.ClansManager; +import mineplex.game.clans.clans.event.ClansCommandExecutedEvent; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FinalObjective; + +public class DisbandClanGoal extends ObjectiveGoal +{ + public DisbandClanGoal(FinalObjective objective) + { + super( + objective, + "Disband Clan", + "Type '/c' and Disband your Clan", + "Now that the tutorial is almost finished, let’s delete your Clan. Disbanding a " + + "Clan will delete it, and unclaim all of your land.", + null + ); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + ClansManager.getInstance().resetLeftTimer(player.getUniqueId()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void teleport(ClanDisbandedEvent event) + { + if (!contains(event.getDisbander())) + { + return; + } + event.setCancelled(true); + + UtilPlayer.message(event.getDisbander(), F.main("Clans", "You have disbanded your Tutorial Clan.")); + ClansManager.getInstance().getClanDataAccess().delete(ClansManager.getInstance().getClan(event.getDisbander()), null); + ClansManager.getInstance().resetLeftTimer(event.getDisbander().getUniqueId()); + finish(event.getDisbander()); + } + + + @EventHandler (priority = EventPriority.HIGHEST) + public void onClick(ClansButtonClickEvent event) { + if(contains(event.getPlayer()) && event.getButtonType().equals(ClansButtonClickEvent.ButtonType.Disband)) + event.setCancelled(false); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/TpClanHomeGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/TpClanHomeGoal.java new file mode 100644 index 000000000..18c5b08a3 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/finalobj/TpClanHomeGoal.java @@ -0,0 +1,91 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.finalobj; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.Callback; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.delayedtask.DelayedTask; +import mineplex.core.delayedtask.DelayedTaskClient; +import mineplex.game.clans.clans.event.ClansCommandPreExecutedEvent; +import mineplex.game.clans.tutorial.objective.Objective; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.tutorial.tutorials.clans.objective.FinalObjective; + +public class TpClanHomeGoal extends ObjectiveGoal +{ + public TpClanHomeGoal(FinalObjective objective) + { + super( + objective, + "Teleport to Clan Home", + "Type '/c home' to teleport to Clan Home", + "You can teleport back to your Clan Home at any time! If enemies break your bed, then you cannot teleport to it!", + null + ); + +// setStartMessageDelay(120); + } + + @Override + protected void customStart(Player player) + { + } + + @Override + protected void customFinish(Player player) + { + } + + @EventHandler + public void teleport(ClansCommandPreExecutedEvent event) + { + if (event.getArguments().length != 1 || !event.getArguments()[0].equalsIgnoreCase("home")) + { + return; + } + + if (!contains(event.getPlayer())) + { + return; + } + + DelayedTask.Instance.doDelay( + event.getPlayer(), + "Tutorial Home Teleport", + new Callback() + { + @Override + public void run(DelayedTaskClient data) + { + UtilPlayer.message(event.getPlayer(), F.main("Clans", "You have teleported to your Clan's Home.")); + event.getPlayer().teleport(getObjective().getPlugin().getTutorialSession(event.getPlayer()).getHomeLocation()); + finish(event.getPlayer()); + } + }, + new Callback() + { + @Override + public void run(DelayedTaskClient data) + { + UtilTextMiddle.display("", "Teleporting to Clan Home in " + F.time(UtilTime.MakeStr(Math.max(0, data.getTimeLeft("Tutorial Home Teleport")))), 0, 5, 0, data.getPlayer()); + } + }, + new Callback() + { + @Override + public void run(DelayedTaskClient data) + { + UtilPlayer.message(data.getPlayer(), F.main("Clans", "Teleport has been cancelled due to movement.")); + } + }, + 15 * 1000, // 15 second cooldown + false + ); + + event.setCancelled(true); + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/GoToShopsGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/GoToShopsGoal.java new file mode 100644 index 000000000..0177f3f9f --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/GoToShopsGoal.java @@ -0,0 +1,77 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops; + +import java.util.UUID; + +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAlg; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ShopsObjective; + +public class GoToShopsGoal extends ObjectiveGoal +{ + public GoToShopsGoal(ShopsObjective objective) + { + super( + objective, + "Go to the Shops", + "Walk to the Shops", + "The shops are the place where you can buy and sell all sorts of items! " + + "The Shops are a " + F.elem("Safe Zone") + ", meaning meaning that players cannot hurt each other.", + DyeColor.LIGHT_BLUE + ); + } + + @Override + protected void customStart(Player player) + { + + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void openGates(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTER) + { + return; + } + + for (UUID uuid : getActivePlayers()) + { + if(UtilPlayer.searchExact(uuid) == null) continue; + getObjective().getPlugin().performGateCheck(UtilPlayer.searchExact(uuid), DyeColor.BROWN); + } + } + + @EventHandler + public void checkRegion(UpdateEvent event) + { + if (event.getType() != UpdateType.FAST) + return; + + for (UUID uuid : getActivePlayers()) + { + Player player = UtilPlayer.searchExact(uuid); + if(player == null || !player.isOnline()) continue; + if (getObjective().getPlugin().isIn(player, ClansMainTutorial.Bounds.SHOPS)) + { + finish(player); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/PurchaseGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/PurchaseGoal.java new file mode 100644 index 000000000..a5ba6bc0a --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/PurchaseGoal.java @@ -0,0 +1,66 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.game.clans.clans.event.ClansPlayerBuyItemEvent; +import mineplex.game.clans.clans.event.ClansShopAddButtonEvent; +import mineplex.game.clans.tutorial.objective.Objective; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import org.bukkit.event.EventPriority; + +public class PurchaseGoal extends ObjectiveGoal +{ + private Material _material; + + public PurchaseGoal(Objective objective, Material material, String name, String description) + { + super(objective, name, description); + _material = material; + + setDisplayStartMessage(false); + setDisplayFinishMessage(false); + } + + public PurchaseGoal(Objective objective, Material material, String name, String description, + String helpText) + { + super(objective, name, description, helpText, null); + _material = material; + + setDisplayStartMessage(false); + setDisplayFinishMessage(false); + } + + @Override + protected void customStart(Player player) + { + + } + + @Override + protected void customFinish(Player player) + { + + } + + @EventHandler + public void button(ClansShopAddButtonEvent event) + { + if (contains(event.getPlayer()) && event.getMaterial() == _material) + { + event.setBuyPrice(0); + } + } + + @EventHandler (priority = EventPriority.HIGH) + public void buy(final ClansPlayerBuyItemEvent event) + { + if (contains(event.getPlayer()) && event.getItem().getType() == _material) + { + event.setCancelled(false); + finish(event.getPlayer()); + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/SellPotatoesGoal.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/SellPotatoesGoal.java new file mode 100644 index 000000000..abfca5e9f --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/objective/goals/shops/SellPotatoesGoal.java @@ -0,0 +1,59 @@ +package mineplex.game.clans.tutorial.tutorials.clans.objective.goals.shops; + +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilPlayer; +import mineplex.game.clans.clans.event.ClansPlayerSellItemEvent; +import mineplex.game.clans.tutorial.TutorialSession; +import mineplex.game.clans.tutorial.objective.ObjectiveGoal; +import mineplex.game.clans.tutorial.tutorials.clans.ClansMainTutorial; +import mineplex.game.clans.tutorial.tutorials.clans.objective.ShopsObjective; +import org.bukkit.event.EventPriority; + +public class SellPotatoesGoal extends ObjectiveGoal +{ + public SellPotatoesGoal(ShopsObjective objective) + { + super( + objective, + "Sell Potatoes", + "Sell your Potatoes to the " + F.elem("Organic Produce Shop"), + "Farming is a great way to make money in Clans. Build a farm in your land, " + + "harvest the crops, and sell it to the shops for profit!", + DyeColor.PINK + ); + } + + @Override + protected void customStart(Player player) + { + TutorialSession session = getObjective().getPlugin().getTutorialSession(player); + session.setMapTargetLocation(getObjective().getPlugin().getPoint(session.getRegion(), ClansMainTutorial.Point.FARMING_SHOP)); + } + + @Override + protected void customFinish(Player player) + { + // Shops Fences Closed + getObjective().getPlugin().spawnFences(getObjective().getPlugin().getRegion(player), DyeColor.BROWN); + + // Remove all potatoes from inventory + UtilInv.removeAll(player, Material.POTATO_ITEM, (byte) 0); + } + + @EventHandler (priority = EventPriority.HIGH) + public void onSell(ClansPlayerSellItemEvent event) + { + if (contains(event.getPlayer())) { + if (event.getItem().getType() == Material.POTATO_ITEM) { + event.setCancelled(false); + finish(event.getPlayer()); + } + } + } +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/repository/TutorialRepository.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/repository/TutorialRepository.java new file mode 100644 index 000000000..415f9ae6e --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/tutorials/clans/repository/TutorialRepository.java @@ -0,0 +1,68 @@ +package mineplex.game.clans.tutorial.tutorials.clans.repository; + +import java.util.UUID; + +import mineplex.core.account.CoreClientManager; +import mineplex.core.common.util.EnclosedObject; +import mineplex.core.common.util.UUIDFetcher; +import mineplex.core.database.MinecraftRepository; +import mineplex.serverdata.database.DBPool; +import mineplex.serverdata.database.column.ColumnInt; +import mineplex.serverdata.database.column.ColumnVarChar; + +public class TutorialRepository extends MinecraftRepository +{ + private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS clansTutorial (uuid VARCHAR(36), timesPlayed INT, PRIMARY KEY (uuid));"; + private static final String GET = "SELECT * FROM clansTutorial WHERE uuid = ?;"; + private static final String INSERT = "INSERT INTO clansTutorial (uuid, timesPlayed) VALUES (?, ?);"; + private static final String UPDATE = "UPDATE clansTutorial SET timesPlayed=? WHERE uuid=?;"; + + private CoreClientManager _clientManager; + + public TutorialRepository(CoreClientManager clientManager) + { + super(clientManager.getPlugin(), DBPool.getAccount()); + + _clientManager = clientManager; + } + + public void SetTimesPlayed(UUID uuid, int timesPlayed) + { + // Prevent duplicate entries for individuals + executeQuery(GET, result -> { + if (result.next()) + executeUpdate(UPDATE, new ColumnInt("timesPlayed", timesPlayed), new ColumnVarChar("uuid", 36, uuid.toString())); + else + executeUpdate(INSERT, new ColumnVarChar("uuid", 36, uuid.toString()), new ColumnInt("timesPlayed", timesPlayed)); + }, new ColumnVarChar("uuid", 36, uuid.toString())); + } + + public int GetTimesPlayed(UUID uuid) + { + EnclosedObject status = new EnclosedObject<>(); + + executeQuery(GET, result -> { + if (result.next()) + status.Set(Integer.valueOf(result.getInt("timesPlayed"))); + else + status.Set(Integer.valueOf(0)); + }, new ColumnVarChar("uuid", 36, uuid.toString())); + + return status.Get().intValue(); + } + + public int GetTimesPlayed(String name) + { + return GetTimesPlayed(UUIDFetcher.getUUIDOf(name)); + } + + protected void initialize() + { + executeUpdate(CREATE_TABLE); + } + + protected void update() + { + } + +} diff --git a/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/visual/VisualManager.java b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/visual/VisualManager.java new file mode 100644 index 000000000..9fd96caf5 --- /dev/null +++ b/Plugins/Mineplex.Game.Clans/src/mineplex/game/clans/tutorial/visual/VisualManager.java @@ -0,0 +1,35 @@ +package mineplex.game.clans.tutorial.visual; + +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.MiniPlugin; + +public class VisualManager extends MiniPlugin +{ + public VisualManager(JavaPlugin plugin) + { + super("Visual", plugin); + } + + public void setTitleMessage(Player player, String message, String desc, int timer, boolean displayNow) + { + + } + + public void displayTitleMessage(Player player, String message, String desc) + { + + } + + public void playFinish(Player player) + { + player.playSound(player.getLocation(), Sound.LEVEL_UP, 1f, 1f); + } + + public void clear(Player player) + { + + } +} diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/Hub.java b/Plugins/Mineplex.Hub/src/mineplex/hub/Hub.java index 15513f191..244d67d00 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/Hub.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/Hub.java @@ -25,6 +25,7 @@ import mineplex.core.give.Give; import mineplex.core.globalpacket.GlobalPacketManager; import mineplex.core.hologram.HologramManager; import mineplex.core.ignore.IgnoreManager; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.inventory.InventoryManager; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.memory.MemoryFix; @@ -50,11 +51,11 @@ import mineplex.core.status.ServerStatusManager; import mineplex.core.task.TaskManager; import mineplex.core.teleport.Teleport; import mineplex.core.titangiveaway.TitanGiveawayManager; +import mineplex.core.tournament.TournamentManager; import mineplex.core.updater.FileUpdater; import mineplex.core.updater.Updater; import mineplex.core.velocity.VelocityFix; import mineplex.core.visibility.VisibilityManager; -import mineplex.hub.modules.NewYearCountdown; import mineplex.hub.modules.StackerManager; import mineplex.hub.queue.QueueManager; import mineplex.hub.server.ServerManager; @@ -106,14 +107,19 @@ public class Hub extends JavaPlugin implements IRelation //Other Modules PacketHandler packetHandler = new PacketHandler(this); DisguiseManager disguiseManager = new DisguiseManager(this, packetHandler); - PreferencesManager preferenceManager = new PreferencesManager(this, clientManager, donationManager); + IncognitoManager incognito = new IncognitoManager(this, clientManager, packetHandler); + PreferencesManager preferenceManager = new PreferencesManager(this, incognito, clientManager, donationManager); + + incognito.setPreferencesManager(preferenceManager); + preferenceManager.GiveItem = true; Creature creature = new Creature(this); NpcManager npcManager = new NpcManager(this, creature); InventoryManager inventoryManager = new InventoryManager(this, clientManager); PetManager petManager = new PetManager(this, clientManager, donationManager, inventoryManager, disguiseManager, creature, blockRestore, webServerAddress); PollManager pollManager = new PollManager(this, clientManager, donationManager); - + //new TournamentManager(this, clientManager, donationManager); + //Main Modules ServerStatusManager serverStatusManager = new ServerStatusManager(this, clientManager, new LagMeter(this, clientManager)); new TitanGiveawayManager(this, clientManager, serverStatusManager); @@ -140,9 +146,10 @@ public class Hub extends JavaPlugin implements IRelation QueueManager queueManager = new QueueManager(this, clientManager, donationManager, new EloManager(this, clientManager), partyManager); + new ServerManager(this, clientManager, donationManager, portal, partyManager, serverStatusManager, hubManager, new StackerManager(hubManager), queueManager); - Chat chat = new Chat(this, clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); - new MessageManager(this, clientManager, preferenceManager, ignoreManager, punish, friendManager, chat); + Chat chat = new Chat(this, incognito, clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); + new MessageManager(this, incognito, clientManager, preferenceManager, ignoreManager, punish, friendManager, chat); new MemoryFix(this); new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion()); new CustomTagFix(this, packetHandler); diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java index a4cb31a3b..ca9703a81 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/HubManager.java @@ -6,10 +6,9 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.Random; -import mineplex.core.reward.RewardManager; -import mineplex.core.valentines.ValentinesGiftManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; @@ -73,8 +72,8 @@ import mineplex.core.gadget.GadgetManager; import mineplex.core.gadget.event.GadgetCollideEntityEvent; import mineplex.core.gadget.event.GadgetEnableEvent; import mineplex.core.gadget.types.GadgetType; -import mineplex.core.giveaway.GiveawayManager; import mineplex.core.hologram.HologramManager; +import mineplex.core.incognito.events.IncognitoHidePlayerEvent; import mineplex.core.inventory.InventoryManager; import mineplex.core.message.PrivateMessageEvent; import mineplex.core.mount.MountManager; @@ -96,12 +95,14 @@ import mineplex.core.portal.Portal; import mineplex.core.preferences.PreferencesManager; import mineplex.core.projectile.ProjectileManager; import mineplex.core.punish.Punish; +import mineplex.core.reward.RewardManager; import mineplex.core.stats.StatsManager; import mineplex.core.status.ServerStatusManager; import mineplex.core.task.TaskManager; import mineplex.core.treasure.TreasureManager; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; +import mineplex.core.valentines.ValentinesGiftManager; import mineplex.hub.commands.DisguiseCommand; import mineplex.hub.commands.ForcefieldRadius; import mineplex.hub.commands.GadgetToggle; @@ -573,6 +574,15 @@ public class HubManager extends MiniClientPlugin event.setCancelled(true); } } + + @EventHandler + public void Incog(IncognitoHidePlayerEvent event) + { + if (!_clientManager.hasRank(event.getPlayer(), Rank.ADMIN)) + { + event.setCancelled(true); + } + } @EventHandler public void PlayerChat(AsyncPlayerChatEvent event) @@ -1077,4 +1087,21 @@ public class HubManager extends MiniClientPlugin { playNextSong(); } + + @EventHandler + public void trackPortalDelayPlayers(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + for (Iterator playerNameIterator = _portalTime.keySet().iterator(); playerNameIterator.hasNext();) + { + String playerName = playerNameIterator.next(); + + if (UtilTime.elapsed(_portalTime.get(playerName), 5000)) + { + playerNameIterator.remove(); + } + } + } } diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/modules/StackerManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/modules/StackerManager.java index 9c52e18a3..532058fa2 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/modules/StackerManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/modules/StackerManager.java @@ -257,7 +257,12 @@ public class StackerManager extends MiniPlugin implements IThrown { public void run() { - fThrower.setPassenger(fThroweeStack); + if ((fThrower instanceof Player && !((Player)fThrower).isOnline()) + || (fThroweeStack instanceof Player && !((Player)fThroweeStack).isOnline())) + { + fThrower.setPassenger(fThroweeStack); + } + _tempStackShift.remove(fThroweeStack); } }, 2); @@ -272,8 +277,6 @@ public class StackerManager extends MiniPlugin implements IThrown UtilPlayer.message(thrower, F.main("Stacker", "You threw " + F.name(UtilEnt.getName(throwee)) + ".")); UtilPlayer.message(throwee, F.main("Stacker", "You were thrown by " + F.name(thrower.getName()) + ".")); - - System.out.println("Stacker throw."); UtilAction.velocity(throwee, thrower.getLocation().getDirection(), 1.8, false, 0, 0.3, 2, false); diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueManager.java index e1f06c6ef..19334819c 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueManager.java @@ -73,7 +73,7 @@ public class QueueManager extends MiniPlugin } } - public void queuePlayer(final String gameType, final Player...players) + public void queuePlayer(final int gameType, final Player...players) { StringBuilder stringBuilder = new StringBuilder(); @@ -103,7 +103,7 @@ public class QueueManager extends MiniPlugin for (Player player : players) { - eloCumulative = _eloManager.getElo(player.getUniqueId(), gameType); + eloCumulative = _eloManager.getElo(player, gameType); } final int elo = eloCumulative / players.length; @@ -116,7 +116,7 @@ public class QueueManager extends MiniPlugin synchronized (_queueLock) { - _queuedPlayerMatchList.put(players[0].getName(), matchStatus); + _queuedPlayerMatchList.put(players[0].getName(), matchStatus); } synchronized (_queuePlayerListLock) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueRepository.java b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueRepository.java index 217e4cd49..416f6d1ba 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueRepository.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/QueueRepository.java @@ -12,7 +12,7 @@ public class QueueRepository { private boolean _us = true; - private static String CREATE_ELO_QUEUE_TABLE = "CREATE TABLE IF NOT EXISTS playerQueue (id INT NOT NULL AUTO_INCREMENT, playerList VARCHAR(256), gameType VARCHAR(256), playerCount INT, elo INT, state VARCHAR(256), time LONG, assignedMatch INT, US BOOLEAN NOT NULL DEFAULT '1', PRIMARY KEY (id), UNIQUE INDEX name_gametype (playerList, gameType));"; + private static String CREATE_ELO_QUEUE_TABLE = "CREATE TABLE IF NOT EXISTS playerQueue (id INT NOT NULL AUTO_INCREMENT, playerList VARCHAR(256), gameType INT, playerCount INT, elo INT, state VARCHAR(256), time LONG, assignedMatch INT, US BOOLEAN NOT NULL DEFAULT '1', PRIMARY KEY (id), UNIQUE INDEX name_gametype (playerList, gameType));"; private static String SAVE_STATE_VALUE = "UPDATE playerQueue SET state = ? WHERE id = ?;"; private static String DELETE_QUEUE_RECORD = "DELETE FROM playerQueue WHERE id = ?;"; private static String INSERT_ACCOUNT = "INSERT INTO playerQueue (playerList, gameType, elo, state, time, playerCount, assignedMatch) VALUES (?, ?, ?, 'Awaiting Match', now(), ?, -1) ON DUPLICATE KEY UPDATE time=VALUES(time);"; @@ -100,7 +100,7 @@ public class QueueRepository } } - public PlayerMatchStatus addQueueRecord(String playerList, int playerCount, String gameType, int elo) + public PlayerMatchStatus addQueueRecord(String playerList, int playerCount, int gameType, int elo) { ResultSet resultSet = null; PreparedStatement preparedStatement = null; @@ -110,7 +110,7 @@ public class QueueRepository { preparedStatement = connection.prepareStatement(INSERT_ACCOUNT, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, playerList); - preparedStatement.setString(2, gameType); + preparedStatement.setInt(2, gameType); preparedStatement.setInt(3, elo); //preparedStatement.setBoolean(4, _us); preparedStatement.setInt(4, playerCount); diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/ui/QueuePage.java b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/ui/QueuePage.java index b8794d407..f0a5122cb 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/queue/ui/QueuePage.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/queue/ui/QueuePage.java @@ -105,7 +105,8 @@ public class QueuePage extends ShopPageBase @Override public void onClick(Player player, ClickType clickType) { - queuePlayer("Dominate", player); + // TODO GAMEID? + queuePlayer(1, player); } }; @@ -128,7 +129,7 @@ public class QueuePage extends ShopPageBase buildPage(); } - private void queuePlayer(String gameType, Player player) + private void queuePlayer(int gameType, Player player) { Party party = getPlugin().getPartyManager().GetParty(player); diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerManager.java index d6a21481f..66d8f06a4 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerManager.java @@ -1,5 +1,7 @@ package mineplex.hub.server; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -26,7 +28,7 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.Vector; -import mineplex.core.MiniPlugin; +import mineplex.core.MiniDbClientPlugin; import mineplex.core.account.CoreClientManager; import mineplex.core.common.Rank; import mineplex.core.common.util.C; @@ -48,10 +50,10 @@ import mineplex.core.shop.ShopBase; import mineplex.core.status.ServerStatusManager; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; +import mineplex.game.clans.core.repository.tokens.SimpleClanToken; import mineplex.hub.HubManager; import mineplex.hub.modules.StackerManager; import mineplex.hub.queue.QueueManager; -import mineplex.hub.queue.ui.QueueShop; import mineplex.hub.server.ui.LobbyShop; import mineplex.hub.server.ui.QuickShop; import mineplex.hub.server.ui.ServerCountSorter; @@ -61,7 +63,7 @@ import mineplex.serverdata.Region; import mineplex.serverdata.data.MinecraftServer; import mineplex.serverdata.data.ServerGroup; -public class ServerManager extends MiniPlugin +public class ServerManager extends MiniDbClientPlugin { private static final Long FREE_PORTAL_TIMER = 20000L; private static final Long BETA_PORTAL_TIMER = 120000L; @@ -77,8 +79,6 @@ public class ServerManager extends MiniPlugin private PartyManager _partyManager; private ServerStatusManager _statusManager; private HubManager _hubManager; - private StackerManager _stackerManager; - private QueueManager _queueManager; private NautHashMap _queueCooldowns = new NautHashMap(); private NautHashMap> _serverKeyInfoMap = new NautHashMap>(); @@ -93,7 +93,6 @@ public class ServerManager extends MiniPlugin // Join Time for Free Players Timer private NautHashMap _joinTime = new NautHashMap(); - private QueueShop _domShop; private QuickShop _quickShop; private LobbyShop _lobbyShop; @@ -103,7 +102,7 @@ public class ServerManager extends MiniPlugin public ServerManager(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager, Portal portal, PartyManager partyManager, ServerStatusManager statusManager, HubManager hubManager, StackerManager stackerManager, QueueManager queueManager) { - super("Server Manager", plugin); + super("Server Manager", plugin, clientManager); _clientManager = clientManager; _donationManager = donationManager; @@ -111,8 +110,6 @@ public class ServerManager extends MiniPlugin _partyManager = partyManager; _statusManager = statusManager; _hubManager = hubManager; - _stackerManager = stackerManager; - _queueManager = queueManager; plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); @@ -120,7 +117,6 @@ public class ServerManager extends MiniPlugin _quickShop = new QuickShop(this, clientManager, donationManager, "Quick Menu"); _lobbyShop = new LobbyShop(this, clientManager, donationManager, "Lobby Menu"); - //_domShop = new new QueueShop(_queueManager, clientManager, donationManager, "Dominate"); // TODO: Find more appropriate place to initialize Clans server shop? _clansShop = new ClansServerShop(this, _clientManager, _donationManager); @@ -918,4 +914,33 @@ public class ServerManager extends MiniPlugin { return _serverNpcShopMap.get("Valentines Vendetta"); } + + @Override + public String getQuery(int accountId, String uuid, String name) + { + return "SELECT clans.name, accountClan.clanRole, clanServer.serverName, clans.id FROM accountClan INNER JOIN clans ON clans.id = accountClan.clanId INNER JOIN clanServer ON clans.serverId = clanServer.id WHERE accountClan.accountId = " + accountId + ";"; + } + + @Override + public void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException + { + SimpleClanToken clanToken = new SimpleClanToken(); + + while (resultSet.next()) + { + String clanName = resultSet.getString(1); + String clanRole = resultSet.getString(2); + String homeServer = resultSet.getString(3); + int clanId = resultSet.getInt(4); + clanToken = new SimpleClanToken(clanName, clanRole, homeServer, clanId); + } + + Set(playerName, clanToken); + } + + @Override + protected SimpleClanToken AddPlayer(String player) + { + return new SimpleClanToken(); + } } diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerSorter.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerSorter.java index ac874017c..325ae80c6 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerSorter.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ServerSorter.java @@ -52,6 +52,14 @@ public class ServerSorter implements Comparator } } + if (a.Name.contains("Clans") && b.Name.contains("Clans")) + { + if (Integer.parseInt(a.Name.split("-")[1]) < Integer.parseInt(b.Name.split("-")[1])) + return -1; + else if (Integer.parseInt(a.Name.split("-")[1]) > Integer.parseInt(b.Name.split("-")[1])) + return 1; + } + if (a.MaxPlayers - a.CurrentPlayers < _requiredSlots && b.MaxPlayers - b.CurrentPlayers >= _requiredSlots) return -1; diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerGameMenu.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerGameMenu.java index 42f56f53e..20764ef6b 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerGameMenu.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/ServerGameMenu.java @@ -40,6 +40,7 @@ public class ServerGameMenu extends ShopPageBase @Override protected void buildPage() { + /* addButton(2, new ItemBuilder(Material.RED_ROSE).setTitle(C.cYellowB + "Valentines Vendetta " + C.cGray + "Save Valentines!").addLore(new String[] { (_extraValue ? C.cAquaB : C.cWhiteB) + "LIMITED TIME GAME", @@ -50,8 +51,9 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "", C.Reset + "Join " + ChatColor.GREEN + getPlugin().getGroupTagPlayerCount("VV") + C.Reset + " other players!", }).setHideInfo(true).build(), new SelectVVButton(this)); + */ - addButton(4, new ItemBuilder(Material.QUARTZ_BLOCK).setTitle(C.cYellowB + "Speed Builders " + C.cGray + "Competitive Building").addLore(new String[] + addButton(2, new ItemBuilder(Material.QUARTZ_BLOCK).setTitle(C.cYellowB + "Speed Builders " + C.cGray + "Competitive Building").addLore(new String[] { (_extraValue ? C.cAquaB : C.cWhiteB) + "NEW GAME", C.Reset + "", @@ -62,6 +64,28 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "Join " + ChatColor.GREEN + getPlugin().getGroupTagPlayerCount("SB") + C.Reset + " other players!", }).setHideInfo(true).build(), new SelectSBButton(this)); + addButton(4, new ItemBuilder(Material.BOOK_AND_QUILL).setTitle(C.cYellowB + "Draw My Thing " + C.cGray + "Pictionary").addLore(new String[] + { + (_extraValue ? C.cAquaB : C.cWhiteB) + "NEW UPDATE", + C.Reset + "", + C.Reset + "Players take turns at drawing a random", + C.Reset + "word. Whoever guesses it within the time", + C.Reset + "limit gets some points!", + C.Reset + "", + C.Reset + "Join " + ChatColor.GREEN + getPlugin().getGroupTagPlayerCount("DMT") + C.Reset + " other players!", + }).setHideInfo(true).build(), new SelectDMTButton(this)); + + addButton(6, new ItemBuilder(Material.TNT).setTitle(C.cYellowB + "Dragon Escape " + C.cGray + "Fast Paced Parkour").addLore(new String[] + { + (_extraValue ? C.cAquaB : C.cWhiteB) + "FEATURED ARCADE GAME", + C.Reset + "", + C.Reset + "Douglas the Dragon is angry", + C.Reset + "You better RUNNNNN!", + C.Reset + "Last player alive wins", + C.Reset + "", + C.Reset + "Join " + C.cGreen + getPlugin().getGroupTagPlayerCount("DE") + C.Reset + " other players!" + }).setHideInfo(true).build(), new SelectFEATButton(this, "Dragon Escape")); + /* addButton(6, new ItemBuilder(Material.IRON_SWORD).setTitle(C.cYellowB + "Gladiators" + C.cGray + " Bracketted Deathmatch").addLore(new String[] { @@ -88,6 +112,7 @@ public class ServerGameMenu extends ShopPageBase }).setHideInfo(true).build(), new SelectFEATButton(this, "Micro Battle")); */ + /* addButton(6, new ItemBuilder(Material.TNT).setTitle(C.cYellowB + "Bomb Lobbers " + C.cGray + "TNT Mayhem").addLore(new String[] { (_extraValue ? C.cAquaB : C.cWhiteB) + "FEATURED ARCADE GAME", @@ -97,6 +122,7 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "", C.Reset + "Join " + C.cGreen + getPlugin().getGroupTagPlayerCount("BL") + C.Reset + " other players!" }).setHideInfo(true).build(), new SelectFEATButton(this, "Bomb Lobbers")); + */ addButton(9, new ItemBuilder(Material.IRON_PICKAXE).setTitle(C.cYellowB + "The Bridges " + C.cGray + "4 Team Survival").addLore(new String[] { @@ -201,7 +227,7 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "Join " + C.cGreen + getPlugin().getGroupTagPlayerCount("BH") + C.Reset + " other players!", }).setHideInfo(true).build(), new SelectBHButton(this)); - addButton(27, new ItemBuilder(Material.TNT).setTitle(C.cYellowB + "MineStrike " + C.cGray + "Team Survival").addLore(new String[] + addButton(28, new ItemBuilder(Material.TNT).setTitle(C.cYellowB + "MineStrike " + C.cGray + "Team Survival").addLore(new String[] { C.Reset + "", C.Reset + "One team must defend two bomb sites from", @@ -211,21 +237,11 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "Join " + C.cGreen + getPlugin().getGroupTagPlayerCount("MS") + C.Reset + " other players!", }).setHideInfo(true).build(), new SelectMSButton(this)); - addButton(29, new ItemBuilder(Material.BOOK_AND_QUILL).setTitle(C.cYellowB + "Draw My Thing " + C.cGray + "Pictionary").addLore(new String[] - { - C.Reset + "", - C.Reset + "Players take turns at drawing a random", - C.Reset + "word. Whoever guesses it within the time", - C.Reset + "limit gets some points!", - C.Reset + "", - C.Reset + "Join " + ChatColor.GREEN + getPlugin().getGroupTagPlayerCount("DMT") + C.Reset + " other players!", - }).setHideInfo(true).build(), new SelectDMTButton(this)); + addButton(30, _superSmashCycle.get(_ssmIndex), new SelectSSMButton(this)); - addButton(31, _superSmashCycle.get(_ssmIndex), new SelectSSMButton(this)); + addButton(32, _minigameCycle.get(_minigameIndex), new SelectMINButton(this)); - addButton(33, _minigameCycle.get(_minigameIndex), new SelectMINButton(this)); - - addButton(35, new ItemBuilder(Material.WOOD).setTitle(C.cYellowB + "Master Builders " + C.cGray + "Creative Build").setLore(new String[] + addButton(34, new ItemBuilder(Material.WOOD).setTitle(C.cYellowB + "Master Builders " + C.cGray + "Creative Build").setLore(new String[] { C.Reset + "", C.Reset + "Players are given a Build Theme and ", @@ -256,9 +272,9 @@ public class ServerGameMenu extends ShopPageBase C.Reset + "the games you want, when you want.", }).setHideInfo(true).build(), new SelectPLAYERButton(this)); - addButton(40, new ItemBuilder(Material.IRON_DOOR).setTitle(C.cYellowB + "Mineplex Clans " + C.cGray + "Champions Teams").addLore(new String[] + addButton(40, new ItemBuilder(Material.IRON_DOOR).setTitle(C.cYellowB + "Mineplex Clans " + C.cGray + "Factions PvP").addLore(new String[] { - (_extraValue ? C.cAquaB : C.cWhiteB) + "ALPHA RELEASE", + (_extraValue ? C.cAquaB : C.cWhiteB) + "BETA RELEASE", C.Reset + "", C.Reset + "Equip custom skills and builds", C.Reset + "and join your clan to destroy", diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClanMoveServerShop.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClanMoveServerShop.java index d8fb30e91..e85528ee8 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClanMoveServerShop.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClanMoveServerShop.java @@ -4,7 +4,6 @@ import org.bukkit.Sound; import org.bukkit.entity.Player; import mineplex.core.account.CoreClientManager; -import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.donation.DonationManager; import mineplex.core.party.Party; diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerPage.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerPage.java index 137fa6322..fe5ceaeea 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerPage.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerPage.java @@ -1,6 +1,8 @@ package mineplex.hub.server.ui.clans; import java.util.Collection; +import java.util.Comparator; +import java.util.TreeSet; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -10,6 +12,7 @@ import org.bukkit.event.inventory.ClickType; import mineplex.core.account.CoreClientManager; import mineplex.core.common.util.C; import mineplex.core.common.util.Callback; +import mineplex.core.common.util.UtilAlg; import mineplex.core.donation.DonationManager; import mineplex.core.shop.item.DisplayButton; import mineplex.core.shop.item.IButton; @@ -24,18 +27,10 @@ import mineplex.serverdata.data.DataRepository; public class ClansServerPage extends ShopPageBase { - - //private DataRepository _repository; // Stores the name of the last Clans server a player was on - private ClanRepository _repository; - private int _accountId; - public ClansServerPage(ServerManager plugin, ClansServerShop shop, CoreClientManager clientManager, - DonationManager donationManager, Player player, ClanRepository repository) + DonationManager donationManager, Player player) { - super(plugin, shop, clientManager, donationManager, "Clans Alpha", player, 27); - - _repository = repository; - _accountId = clientManager.getAccountId(player); + super(plugin, shop, clientManager, donationManager, "Clans Beta", player, 54); buildPage(); } @@ -43,21 +38,14 @@ public class ClansServerPage extends ShopPageBase() - { - @Override - public void run(SimpleClanToken data) - { - if (data != null) - { - buildClanPage(data); - } - else - { - buildNoClanPage(); - } - } - }); + if (!getPlugin().Get(_player).getClanName().isEmpty()) + { + buildClanPage(getPlugin().Get(_player)); + } + else + { + buildNoClanPage(); + } } private void buildClanPage(SimpleClanToken clan) @@ -72,7 +60,14 @@ public class ClansServerPage extends ShopPageBase servers = getPlugin().getServerList("Clans"); + Collection servers = UtilAlg.sortSet(getPlugin().getServerList("Clans"), new Comparator() + { + @Override + public int compare(ServerInfo o1, ServerInfo o2) + { + return o1.Name.compareTo(o2.Name); + } + }); int currentSlot = 9; for (ServerInfo server : servers) diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerShop.java b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerShop.java index a3241e2cc..f5590b095 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerShop.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/server/ui/clans/ClansServerShop.java @@ -2,29 +2,23 @@ package mineplex.hub.server.ui.clans; import org.bukkit.Sound; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; import mineplex.core.account.CoreClientManager; -import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.donation.DonationManager; import mineplex.core.party.Party; import mineplex.core.shop.ShopBase; import mineplex.core.shop.page.ShopPageBase; import mineplex.game.clans.core.repository.ClanRepository; -import mineplex.game.clans.core.repository.tokens.SimpleClanToken; import mineplex.hub.server.ServerManager; public class ClansServerShop extends ShopBase { - private ClanRepository _repository; public ClansServerShop(ServerManager plugin, CoreClientManager clientManager, DonationManager donationManager) { - super(plugin, clientManager, donationManager, "Clans Alpha"); + super(plugin, clientManager, donationManager, "Clans Beta"); _repository = new ClanRepository(plugin.getPlugin(), plugin.getStatusManager().getCurrentServerName()); } @@ -32,7 +26,7 @@ public class ClansServerShop extends ShopBase @Override protected ShopPageBase> buildPagesFor(Player player) { - return new ClansServerPage(getPlugin(), this, getClientManager(), getDonationManager(), player, _repository); + return new ClansServerPage(getPlugin(), this, getClientManager(), getDonationManager(), player); } @Override diff --git a/Plugins/Mineplex.Hub/src/mineplex/hub/tutorial/TutorialManager.java b/Plugins/Mineplex.Hub/src/mineplex/hub/tutorial/TutorialManager.java index ff13349f0..58332d12c 100644 --- a/Plugins/Mineplex.Hub/src/mineplex/hub/tutorial/TutorialManager.java +++ b/Plugins/Mineplex.Hub/src/mineplex/hub/tutorial/TutorialManager.java @@ -87,7 +87,7 @@ public class TutorialManager extends MiniPlugin if (InTutorial(event.getPlayer())) event.setCancelled(true); } - + @EventHandler public void MoveCancel(PlayerMoveEvent event) { diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Flash.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Flash.java index 494900104..110b30524 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Flash.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Flash.java @@ -3,11 +3,9 @@ package mineplex.minecraft.game.classcombat.Skill.Assassin; import java.util.HashMap; import org.bukkit.Bukkit; -import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; -import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -15,16 +13,16 @@ import org.bukkit.event.block.Action; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; -import mineplex.core.common.util.UtilItem; -import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; import mineplex.core.common.util.F; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilItem; import mineplex.core.common.util.UtilParticle; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilParticle.ParticleType; import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; import mineplex.minecraft.game.classcombat.Skill.SkillActive; import mineplex.minecraft.game.classcombat.Skill.SkillFactory; import mineplex.minecraft.game.classcombat.Skill.event.SkillTeleportEvent; @@ -157,16 +155,19 @@ public class Flash extends SkillActive if(aboveTargetData <= 7) aboveTargetSlabIsBottom = true; } - - // Doors - if (UtilItem.is(newTarget.getBlock(), UtilItem.ItemCategory.DOOR)) + + if ((!newTargetSlabIsBottom && + !UtilItem.isBoundless(aboveTarget.getBlock().getType()) + || (!aboveTargetSlabIsBottom) + && !UtilItem.isBoundless(aboveTarget.getBlock().getType()))) break; - if ((!newTargetSlabIsBottom && UtilBlock.fullSolid(newTarget.getBlock())) || (!aboveTargetSlabIsBottom && UtilBlock.fullSolid(aboveTarget.getBlock()))) + if (!UtilItem.isBoundless(newTarget.getBlock().getType()) && UtilItem.isBoundless(aboveTarget.getBlock().getType()) + || !UtilItem.isBoundless(aboveTarget.getBlock().getType()) && !UtilItem.isBoundless(newTarget.getBlock().getType())) break; - + //Progress Forwards - curRange += 0.2; + curRange += 0.1; //Smoke Trail UtilParticle.PlayParticle(ParticleType.FIREWORKS_SPARK, newTarget.clone().add(0, 0.5, 0), 0, 0, 0, 0, 1, @@ -180,7 +181,12 @@ public class Flash extends SkillActive //Destination Location loc = getDestination(player, curRange); - + + if (UtilItem.isBoundless(UtilAlg.moveForward(loc, 0.15d, player.getLocation().getYaw(), false).getBlock().getType())) + { + loc = UtilAlg.moveForward(loc, 0.25d, player.getLocation().getYaw(), true); + } + if (curRange > 0) player.teleport(loc); diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Leap.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Leap.java index 37dc508e6..06bdda17a 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Leap.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Leap.java @@ -13,6 +13,7 @@ import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilTime; import mineplex.minecraft.game.classcombat.Skill.SkillActive; diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Recall.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Recall.java index cd7af9243..b675e3a58 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Recall.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/Recall.java @@ -6,6 +6,7 @@ import java.util.LinkedList; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventoryCrafting; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryCloseEvent; @@ -27,6 +28,7 @@ import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; import mineplex.minecraft.game.classcombat.Skill.Skill; import mineplex.minecraft.game.classcombat.Skill.SkillFactory; import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; +import net.minecraft.server.v1_8_R3.Material; public class Recall extends Skill { @@ -57,9 +59,14 @@ public class Recall extends Skill public void use(PlayerDropItemEvent event) { Player player = event.getPlayer(); - + + if (!(player.getOpenInventory().getTopInventory() instanceof CraftInventoryCrafting)) + { + return; + } + int level = getLevel(player); - if (level == 0) + if (level == 0) return; if (!UtilGear.isWeapon(event.getItemDrop().getItemStack())) @@ -153,7 +160,7 @@ public class Recall extends Skill _healthMap.get(cur).removeLast(); } } - + @Override public void Reset(Player player) { diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/SmokeBomb.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/SmokeBomb.java index 41f70572b..3552c2856 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/SmokeBomb.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Assassin/SmokeBomb.java @@ -2,6 +2,7 @@ package mineplex.minecraft.game.classcombat.Skill.Assassin; import mineplex.minecraft.game.classcombat.Class.IPvpClass.ClassType; import mineplex.minecraft.game.core.damage.CustomDamageEvent; +import net.minecraft.server.v1_8_R3.Material; import mineplex.core.common.util.F; import mineplex.core.recharge.Recharge; import mineplex.core.updater.event.UpdateEvent; @@ -21,9 +22,11 @@ import mineplex.minecraft.game.classcombat.Skill.event.SkillTriggerEvent; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Sound; +import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventoryCrafting; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; @@ -55,7 +58,12 @@ public class SmokeBomb extends Skill public void Use(PlayerDropItemEvent event) { Player player = event.getPlayer(); - + + if (!(player.getOpenInventory().getTopInventory() instanceof CraftInventoryCrafting)) + { + return; + } + int level = getLevel(player); if (level == 0) return; @@ -140,7 +148,19 @@ public class SmokeBomb extends Skill Factory.Condition().EndCondition(event.getPlayer(), null, GetName()); } - + + @EventHandler + public void closeInv(InventoryCloseEvent event) + { + if (getLevel(event.getPlayer()) == 0) + { + return; + } + + event.getPlayer().getInventory().addItem(event.getPlayer().getItemOnCursor()); + event.getPlayer().setItemOnCursor(null); + } + @EventHandler public void Smoke(UpdateEvent event) { diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Brute/BlockToss.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Brute/BlockToss.java index cde190a34..c25d056b8 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Brute/BlockToss.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Brute/BlockToss.java @@ -70,6 +70,7 @@ public class BlockToss extends SkillCharge implements IThrown Material.STONE_BUTTON, Material.WOOD_BUTTON, Material.LEVER, + Material.BARRIER, }; public BlockToss(SkillFactory skills, String name, ClassType classType, SkillType skillType, int cost, int levels) diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Knight/HoldPosition.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Knight/HoldPosition.java index c60df3d8f..4aea8ddfd 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Knight/HoldPosition.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/Skill/Knight/HoldPosition.java @@ -126,6 +126,6 @@ public class HoldPosition extends SkillActive @Override public void Reset(Player player) { - + player.setFoodLevel(20); } } diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/ClassCombatShop.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/ClassCombatShop.java index 503a22f10..6ba4e02fb 100644 --- a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/ClassCombatShop.java +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/ClassCombatShop.java @@ -1,5 +1,6 @@ package mineplex.minecraft.game.classcombat.shop; +import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; @@ -19,6 +20,7 @@ import mineplex.core.common.util.UtilPlayer; import mineplex.minecraft.game.classcombat.Class.ClientClass; import mineplex.minecraft.game.classcombat.Class.IPvpClass; import mineplex.minecraft.game.classcombat.Class.repository.token.CustomBuildToken; +import mineplex.minecraft.game.classcombat.shop.event.OpenClassShopEvent; import mineplex.minecraft.game.classcombat.shop.page.CustomBuildPage; public class ClassCombatShop extends ShopBase @@ -50,7 +52,10 @@ public class ClassCombatShop extends ShopBase } protected void openShopForPlayer(Player player) - { + { + OpenClassShopEvent event = new OpenClassShopEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (_gameClass != null) getPlugin().GetClassManager().Get(player).SetGameClass(_gameClass); diff --git a/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/event/OpenClassShopEvent.java b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/event/OpenClassShopEvent.java new file mode 100644 index 000000000..cd52d54e1 --- /dev/null +++ b/Plugins/Mineplex.Minecraft.Game.ClassCombat/src/mineplex/minecraft/game/classcombat/shop/event/OpenClassShopEvent.java @@ -0,0 +1,18 @@ +package mineplex.minecraft.game.classcombat.shop.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class OpenClassShopEvent extends PlayerEvent +{ + private static final HandlerList handlers = new HandlerList(); + public static HandlerList getHandlerList() { return handlers; } + public HandlerList getHandlers() { return handlers; } + + public OpenClassShopEvent(Player who) + { + super(who); + } + +} diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/WorldEvent.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/WorldEvent.java index 3781f2a5b..6f10d660c 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/WorldEvent.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/WorldEvent.java @@ -5,8 +5,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; +import java.util.Set; -import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -15,6 +15,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.Vector; import mineplex.core.blockrestore.BlockRestore; import mineplex.core.blockrestore.BlockRestoreMap; @@ -25,7 +26,7 @@ import mineplex.core.common.block.schematic.UtilSchematic; import mineplex.core.common.util.C; import mineplex.core.common.util.Callback; import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTextMiddle; @@ -65,6 +66,14 @@ public abstract class WorldEvent implements Listener, ScoreboardElement private boolean _isArcade; private double _difficulty = 1; + private double _minX; + private double _minY; + private double _minZ; + + private double _maxX; + private double _maxY; + private double _maxZ; + public WorldEvent(DisguiseManager disguiseManager, ProjectileManager projectileManager, DamageManager damageManager, BlockRestore blockRestore, ConditionManager conditionManager, String name, Location cornerLocation) { this(disguiseManager, projectileManager, damageManager, blockRestore, conditionManager, name, cornerLocation, null); @@ -263,12 +272,12 @@ public abstract class WorldEvent implements Listener, ScoreboardElement HandlerList.unregisterAll(creature); _creatures.remove(creature); } - + public void announceStart() { UtilTextMiddle.display(C.cGreen + getName(), UtilWorld.locToStrClean(getCenterLocation()), 10, 100, 40); - - Bukkit.broadcastMessage(F.main("Event", F.elem(getName()) + " has started at coordinates " + F.elem(UtilWorld.locToStrClean(getCenterLocation())))); + + UtilServer.broadcast(F.main("Event", F.elem(getName()) + " has started at coordinates " + F.elem(UtilWorld.locToStrClean(getCenterLocation())))); } public void clearCreatures() @@ -328,7 +337,6 @@ public abstract class WorldEvent implements Listener, ScoreboardElement { onComplete.run(); } - } }); @@ -407,4 +415,50 @@ public abstract class WorldEvent implements Listener, ScoreboardElement } } + public boolean isInBounds(Location location) + { + if (_minX == 0) + { + // Calculate bounds + Set blocks = _blocks.getChangedBlocks(); + + for (Block block : blocks) + { + if (_minX > block.getX()) + { + _minX = block.getX(); + } + + if (_minY > block.getY()) + { + _minY = block.getY(); + } + + if (_minZ > block.getZ()) + { + _minZ = block.getZ(); + } + + if (_maxX < block.getX()) + { + _maxX = block.getX(); + } + + if (_maxY < block.getY()) + { + _maxY = block.getY(); + } + + if (_maxZ < block.getZ()) + { + _maxZ = block.getZ(); + } + } + + _maxY++; + } + + return UtilAlg.inBoundingBox(location, new Vector(_minX, _minY, _minZ), new Vector(_maxX, _maxY, _maxZ)); + } + } diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/BlockHailBlock.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/BlockHailBlock.java index 07e23702c..d4455f406 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/BlockHailBlock.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/BlockHailBlock.java @@ -2,6 +2,7 @@ package mineplex.minecraft.game.core.boss.ironwizard.abilities; import mineplex.core.common.util.UtilEnt; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.Entity; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; @@ -52,8 +53,8 @@ public class BlockHailBlock PacketPlayOutSpawnEntityLiving packet1 = new PacketPlayOutSpawnEntityLiving(); DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); + watcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 0); + watcher.a(1, 0, Entity.META_AIR, 0); packet1.a = _silverfish; packet1.b = EntityType.SILVERFISH.getTypeId(); diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplodingAura.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplodingAura.java index 8ac030a5e..516e501f7 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplodingAura.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplodingAura.java @@ -172,8 +172,8 @@ public class GolemExplodingAura extends BossAbility PacketPlayOutSpawnEntityLiving packet1 = new PacketPlayOutSpawnEntityLiving(); DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); + watcher.a(0, (byte) 32, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 0); + watcher.a(1, 0, net.minecraft.server.v1_8_R3.Entity.META_AIR, 0); packet1.a = key; packet1.b = EntityType.SILVERFISH.getTypeId(); diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplosiveBlock.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplosiveBlock.java index de9121c43..720bd2e1d 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplosiveBlock.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/ironwizard/abilities/GolemExplosiveBlock.java @@ -395,8 +395,8 @@ public class GolemExplosiveBlock extends BossAbility PacketPlayOutSpawnEntityLiving packet1 = new PacketPlayOutSpawnEntityLiving(); DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); + watcher.a(0, (byte) 32, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 0); + watcher.a(1, 0, net.minecraft.server.v1_8_R3.Entity.META_AIR, 0); packet1.a = id; packet1.b = EntityType.SILVERFISH.getTypeId(); diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/snake/SnakeSegment.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/snake/SnakeSegment.java index 2ce42ca68..3f58ac483 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/snake/SnakeSegment.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/boss/snake/SnakeSegment.java @@ -1,5 +1,7 @@ package mineplex.minecraft.game.core.boss.snake; +import java.util.UUID; + import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; @@ -8,12 +10,14 @@ import org.bukkit.util.Vector; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilEnt; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityEquipment; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityTeleport; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; +import net.minecraft.server.v1_8_R3.Vector3f; public class SnakeSegment { @@ -92,16 +96,16 @@ public class SnakeSegment _prevDir = vec; DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); - watcher.a(10, (byte) 0); - - watcher.a(11, vec); - - for (int i = 12; i < 17; i++) - { - watcher.a(i, new Vector(0, 0, 0)); - } + watcher.a(0, (byte) 32, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 0); + watcher.a(1, 0, net.minecraft.server.v1_8_R3.Entity.META_AIR, 0); + watcher.a(10, (byte) 0, EntityArmorStand.META_ARMOR_OPTION, (byte) 0); + watcher.a(11, new Vector3f(0, 0, 0), EntityArmorStand.META_HEAD_POSE, + new Vector3f((float) vec.getX(), (float) vec.getY(), (float) vec.getZ())); + watcher.a(12, new Vector3f(0, 0, 0), EntityArmorStand.META_BODY_POSE, new Vector3f(0, 0, 0)); + watcher.a(13, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_ARM_POSE, new Vector3f(0, 0, 0)); + watcher.a(14, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_ARM_POSE, new Vector3f(0, 0, 0)); + watcher.a(15, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_LEG_POSE, new Vector3f(0, 0, 0)); + watcher.a(16, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_LEG_POSE, new Vector3f(0, 0, 0)); PacketPlayOutEntityMetadata meta = new PacketPlayOutEntityMetadata(); @@ -129,23 +133,25 @@ public class SnakeSegment PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(); DataWatcher watcher = new DataWatcher(null); - watcher.a(1, 0); + watcher.a(1, 0, net.minecraft.server.v1_8_R3.Entity.META_AIR, 0); packet.a = getId(); packet.c = (int) Math.floor(_entityLocation.getX() * 32); packet.d = (int) Math.floor(_entityLocation.getY() * 32); packet.e = (int) Math.floor(_entityLocation.getZ() * 32); packet.l = watcher; + packet.uuid = UUID.randomUUID(); if (_item != null) { - watcher.a(0, (byte) 32); - watcher.a(10, (byte) 0); - - for (int i = 11; i < 17; i++) - { - watcher.a(i, new Vector(0, 0, 0)); - } + watcher.a(0, (byte) 32, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 32); + watcher.a(10, (byte) 0, EntityArmorStand.META_ARMOR_OPTION, (byte) 0); + watcher.a(11, new Vector3f(0, 0, 0), EntityArmorStand.META_HEAD_POSE, new Vector3f(0, 0, 0)); + watcher.a(12, new Vector3f(0, 0, 0), EntityArmorStand.META_BODY_POSE, new Vector3f(0, 0, 0)); + watcher.a(13, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_ARM_POSE, new Vector3f(0, 0, 0)); + watcher.a(14, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_ARM_POSE, new Vector3f(0, 0, 0)); + watcher.a(15, new Vector3f(0, 0, 0), EntityArmorStand.META_LEFT_LEG_POSE, new Vector3f(0, 0, 0)); + watcher.a(16, new Vector3f(0, 0, 0), EntityArmorStand.META_RIGHT_LEG_POSE, new Vector3f(0, 0, 0)); packet.b = 30; @@ -162,7 +168,7 @@ public class SnakeSegment } else { - watcher.a(0, (byte) 0); + watcher.a(0, (byte) 0, net.minecraft.server.v1_8_R3.Entity.META_ENTITYDATA, (byte) 0); packet.b = EntityType.MAGMA_CUBE.getTypeId(); return new Packet[] diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/combat/CombatManager.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/combat/CombatManager.java index b42ae087d..e8cd54e15 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/combat/CombatManager.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/combat/CombatManager.java @@ -3,6 +3,7 @@ package mineplex.minecraft.game.core.combat; import java.util.HashSet; import java.util.Iterator; +import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.entity.Arrow; import org.bukkit.entity.Fireball; @@ -89,11 +90,53 @@ public class CombatManager extends MiniPlugin { if (damagerEnt instanceof Player) Get((Player)damagerEnt).SetLastCombat(System.currentTimeMillis()); + + String cause = ""; + switch(event.getCause()) + { + case ENTITY_ATTACK: + cause = "Attack"; + break; + case ENTITY_EXPLOSION: + cause = "Explosion"; + break; + case MAGIC: + cause = "Thrown Potion"; + break; + case PROJECTILE: + cause = "Ranged Weapon"; + break; + case THORNS: + cause = "Thorns Enchantment"; + break; + default: + cause = event.getCause() + ""; + break; + } + + if (UtilEvent.isBowDamage(event)) + { + cause = "Bow"; + } + + if (damagerEnt instanceof Player) + { + if (event.getCause() == DamageCause.ENTITY_ATTACK) + { + Player player = (Player) damagerEnt; + if (player.getItemInHand() == null) + cause = "Fists"; + else if (player.getItemInHand().getType() == Material.AIR) + cause = "Fists"; + else + cause = ItemStackFactory.Instance.GetName(player.getItemInHand(), false); + } + } Get(damagee).Attacked( UtilEnt.getName(damagerEnt), event.getDamage(), damagerEnt, - event.getCause() + "", null); + cause, null); } // Damager is WORLD else diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/condition/ConditionEffect.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/condition/ConditionEffect.java index 74e3f7473..c976c0a54 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/condition/ConditionEffect.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/condition/ConditionEffect.java @@ -377,9 +377,22 @@ public class ConditionEffect implements Listener if (condition == null || condition.GetSource() == null) continue; - Manager.getDamagerManager().NewDamageEvent(ent, condition.GetSource(), null, - DamageCause.CUSTOM, 0.1, false, true, false, - condition.GetSource().getName(), "Poison"); + try + { + Manager.getDamagerManager().NewDamageEvent(ent, condition.GetSource(), null, + DamageCause.CUSTOM, 0.1, false, true, false, + condition.GetSource() != null ? condition.GetSource().getName() : "The Mighty Defek7", "Poison"); + } + catch (Exception exception) + { + System.out.println("__+Poison error+__"); + System.out.println("Manager null? : " + Manager == null); + System.out.println("Manager.getDamagerManager null? : " + Manager.getDamagerManager() == null); + System.out.println("condition.GetSource() null? : " + condition.GetSource() == null); + System.out.println("condition.GetSource().getName() null? : " + condition.GetSource().getName() == null); + + throw exception; + } } } diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/damage/DamageManager.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/damage/DamageManager.java index 67b2ba1f3..de559f25b 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/damage/DamageManager.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/damage/DamageManager.java @@ -692,6 +692,11 @@ public class DamageManager extends MiniPlugin return null; } + + public boolean IsEnabled() + { + return _enabled; + } public void SetEnabled(boolean var) { diff --git a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/explosion/CustomExplosion.java b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/explosion/CustomExplosion.java index fed9d16ff..3a844f097 100644 --- a/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/explosion/CustomExplosion.java +++ b/Plugins/Mineplex.Minecraft.Game.Core/src/mineplex/minecraft/game/core/explosion/CustomExplosion.java @@ -53,7 +53,7 @@ public class CustomExplosion extends Explosion private mineplex.core.explosion.Explosion _explosion; private float _damage; private boolean _useCustomDamage; - private int _maxFallingBlocks = -1; + private int _maxFallingBlocks = 0; private float _maxDamage = 1000; private float _size; private boolean _damageBlocks = true; diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java index f80fe0b7c..8d8f2daf3 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/Utility.java @@ -163,25 +163,11 @@ public class Utility { long currentTime = 0; JedisPool pool = getPool(false); - Jedis jedis = pool.getResource(); - try + try(Jedis jedis = pool.getResource()) { currentTime = Long.parseLong(jedis.time().get(0)); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - pool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (pool != null) - { - pool.returnResource(jedis); - } - } _millisTimeDifference = (currentTime * 1000) - System.currentTimeMillis(); } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/commands/ServerCommandManager.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/commands/ServerCommandManager.java index 29abc70ce..0b0779035 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/commands/ServerCommandManager.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/commands/ServerCommandManager.java @@ -45,29 +45,15 @@ public class ServerCommandManager */ private void initialize() { - final Jedis jedis = _readPool.getResource(); - // Spin up a new thread and subscribe to the Redis pubsub network Thread thread = new Thread("Redis Manager") { public void run() { - try + try (Jedis jedis = _readPool.getResource()) { jedis.psubscribe(new ServerCommandListener(), SERVER_COMMANDS_CHANNEL + ":*"); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - } - finally - { - if (_readPool != null) - { - _readPool.returnResource(jedis); - } - } } }; @@ -86,25 +72,11 @@ public class ServerCommandManager { String commandType = serverCommand.getClass().getSimpleName(); String serializedCommand = Utility.serialize(serverCommand); - Jedis jedis = _writePool.getResource(); - try + try(Jedis jedis = _writePool.getResource()) { jedis.publish(SERVER_COMMANDS_CHANNEL + ":" + commandType, serializedCommand); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (_writePool != null) - { - _writePool.returnResource(jedis); - } - } } }).start(); } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/DBPool.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/DBPool.java index f69fabe62..acc786379 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/DBPool.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/DBPool.java @@ -24,13 +24,14 @@ public final class DBPool BasicDataSource source = new BasicDataSource(); source.addConnectionProperty("autoReconnect", "true"); source.addConnectionProperty("allowMultiQueries", "true"); + source.addConnectionProperty("zeroDateTimeBehavior", "convertToNull"); source.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); source.setDriverClassName("com.mysql.jdbc.Driver"); source.setUrl(url); source.setUsername(username); source.setPassword(password); - source.setMaxTotal(3); - source.setMaxIdle(3); + source.setMaxTotal(4); + source.setMaxIdle(4); source.setTimeBetweenEvictionRunsMillis(180 * 1000); source.setSoftMinEvictableIdleTimeMillis(180 * 1000); diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/RepositoryBase.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/RepositoryBase.java index 668985c77..28650bc01 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/RepositoryBase.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/database/RepositoryBase.java @@ -126,7 +126,10 @@ public abstract class RepositoryBase try (ResultSet resultSet = statement.executeQuery()) { - callable.processResultSet(resultSet); + if (callable != null) + { + callable.processResultSet(resultSet); + } } } catch (SQLException exception) @@ -140,7 +143,7 @@ public abstract class RepositoryBase } protected void executeQuery(String query, ResultSetCallable callable, Column...columns) - { + { // Automatic resource management for handling/closing objects. try ( Connection connection = getConnection(); diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisDataRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisDataRepository.java index caea6188b..5ccfd291a 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisDataRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisDataRepository.java @@ -13,29 +13,14 @@ import mineplex.serverdata.data.DataRepository; import mineplex.serverdata.servers.ConnectionData; import mineplex.serverdata.servers.ServerManager; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; -import redis.clients.jedis.exceptions.JedisConnectionException; -public class RedisDataRepository implements DataRepository +public class RedisDataRepository extends RedisRepository implements DataRepository { - - // The delimiter character used for redis key paths - public final char KEY_DELIMITER = '.'; - - // The pools used to retrieve jedis instances. - private JedisPool _writePool; - private JedisPool _readPool; - - // The geographical region of the servers stored by this ServerRepository - private Region _region; - // The class type of the elements stored in this repository private Class _elementType; - // A unique label designating the elements and this repository. private String _elementLabel; @@ -43,19 +28,14 @@ public class RedisDataRepository implements DataRepository * Class constructor * @param writeConn * @param readConn - * @param host - * @param port * @param region */ public RedisDataRepository(ConnectionData writeConn, ConnectionData readConn, Region region, Class elementType, String elementLabel) { - _writePool = Utility.generatePool(writeConn); - _readPool = (writeConn == readConn) ? _writePool : Utility.generatePool(readConn); - _region = region; + super(writeConn, readConn, region); _elementType = elementType; _elementLabel = elementLabel; - } public RedisDataRepository(ConnectionData conn, Region region, Class elementType, String elementLabel) @@ -71,7 +51,7 @@ public class RedisDataRepository implements DataRepository public String getElementSetKey() { - return concatenate("data", _elementLabel, _region.toString()); + return concatenate("data", _elementLabel, getRegion().toString()); } public String generateKey(T element) @@ -94,9 +74,8 @@ public class RedisDataRepository implements DataRepository public Collection getElements(Collection dataIds) { Collection elements = new HashSet(); - Jedis jedis = _readPool.getResource(); - try + try(Jedis jedis = getResource(false)) { Pipeline pipeline = jedis.pipelined(); @@ -120,20 +99,7 @@ public class RedisDataRepository implements DataRepository } } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return elements; } @@ -141,37 +107,21 @@ public class RedisDataRepository implements DataRepository public T getElement(String dataId) { T element = null; - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String key = generateKey(dataId); String serializedData = jedis.get(key); element = deserialize(serializedData); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return element; } @Override public void addElement(T element, int timeout) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { String serializedData = serialize(element); String dataId = element.getDataId(); @@ -184,19 +134,6 @@ public class RedisDataRepository implements DataRepository transaction.zadd(setKey, expiry, dataId.toString()); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override @@ -214,9 +151,7 @@ public class RedisDataRepository implements DataRepository @Override public void removeElement(String dataId) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { String setKey = getElementSetKey(); String dataKey = generateKey(dataId); @@ -226,19 +161,6 @@ public class RedisDataRepository implements DataRepository transaction.zrem(setKey, dataId); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override @@ -250,9 +172,7 @@ public class RedisDataRepository implements DataRepository @Override public int clean() { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { for (String dataId : getDeadElements()) { @@ -264,76 +184,35 @@ public class RedisDataRepository implements DataRepository transaction.exec(); } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } - + return 0; } protected Set getActiveElements() { Set dataIds = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String min = "(" + currentTime(); String max = "+inf"; dataIds = jedis.zrangeByScore(getElementSetKey(), min, max); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return dataIds; } protected Set getDeadElements() { Set dataIds = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String min = "-inf"; String max = currentTime() + ""; dataIds = jedis.zrangeByScore(getElementSetKey(), min, max); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return dataIds; } @@ -351,16 +230,4 @@ public class RedisDataRepository implements DataRepository { return Utility.currentTimeSeconds(); } - - /** - * @param elements - the elements to concatenate together - * @return the concatenated form of all {@code elements} - * separated by the delimiter {@value KEY_DELIMITER}. - */ - protected String concatenate(String... elements) - { - return Utility.concatenate(KEY_DELIMITER, elements); - } - - } diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisRepository.java new file mode 100644 index 000000000..dd43e1fb0 --- /dev/null +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisRepository.java @@ -0,0 +1,70 @@ +package mineplex.serverdata.redis; + +import mineplex.serverdata.Region; +import mineplex.serverdata.Utility; +import mineplex.serverdata.servers.ConnectionData; +import mineplex.serverdata.servers.ServerManager; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +/** + * Repository for managing Redis Connections + * @author Shaun Bennett + */ +public class RedisRepository +{ + protected static final char KEY_DELIMITER = '.'; + + private JedisPool _writePool; + private JedisPool _readPool; + private Region _region; + + public RedisRepository(ConnectionData writeConn, ConnectionData readConn, Region region) + { + _writePool = Utility.generatePool(writeConn); + _readPool = (writeConn == readConn) ? _writePool : Utility.generatePool(readConn); + _region = region; + } + + public RedisRepository(Region region) + { + this(ServerManager.getMasterConnection(), ServerManager.getSlaveConnection(), region); + } + + /** + * Get a Jedis Resource from the pool. This Jedis instance needs to be closed when you are done with using it. + * Call jedis.close() or use try with resources when using getResource() + * + * @param writeable If we need to be able to write to redis. Trying to write to a non writeable jedis instance will + * throw an error. + * @return {@link Jedis} instance from pool + */ + protected Jedis getResource(boolean writeable) + { + return (writeable ? _writePool : _readPool).getResource(); + } + + /** + * Get the server region that this redis repository is for. The region will affect the keys for redis + * @return server region + */ + public Region getRegion() + { + return _region; + } + + protected String getKey(String dataKey) + { + return concatenate("minecraft", "data", _region.name(), dataKey); + } + + /** + * @param elements - the elements to concatenate together + * @return the concatenated form of all {@code elements} + * separated by the delimiter {@value KEY_DELIMITER}. + */ + protected String concatenate(String... elements) + { + return Utility.concatenate(KEY_DELIMITER, elements); + } +} diff --git a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisServerRepository.java b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisServerRepository.java index 50b3bee6a..15120076e 100644 --- a/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisServerRepository.java +++ b/Plugins/Mineplex.ServerData/src/mineplex/serverdata/redis/RedisServerRepository.java @@ -30,29 +30,11 @@ import redis.clients.jedis.exceptions.JedisConnectionException; * @author Ty * */ -public class RedisServerRepository implements ServerRepository +public class RedisServerRepository extends RedisRepository implements ServerRepository { - - // The delimiter character used for redis key paths - public final char KEY_DELIMITER = '.'; - - // The pool used to retrieve jedis instances. - private JedisPool _writePool; - private JedisPool _readPool; - - // The geographical region of the servers stored by this ServerRepository - private Region _region; - - /** - * Class constructor - * @param host - * @param port - */ public RedisServerRepository(ConnectionData writeConn, ConnectionData readConn, Region region) { - _writePool = Utility.generatePool(writeConn); - _readPool = (writeConn == readConn) ? _writePool : Utility.generatePool(readConn); - _region = region; + super(writeConn, readConn, region); } @Override @@ -65,11 +47,10 @@ public class RedisServerRepository implements ServerRepository public Collection getServerStatusesByPrefix(String prefix) { Collection servers = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { - String setKey = concatenate("serverstatus", "minecraft", _region.toString()); + String setKey = concatenate("serverstatus", "minecraft", getRegion().toString()); Pipeline pipeline = jedis.pipelined(); List> responses = new ArrayList>(); @@ -95,20 +76,7 @@ public class RedisServerRepository implements ServerRepository } } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return servers; } @@ -132,42 +100,26 @@ public class RedisServerRepository implements ServerRepository public MinecraftServer getServerStatus(String serverName) { MinecraftServer server = null; - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { - String setKey = concatenate("serverstatus", "minecraft", _region.toString()); + String setKey = concatenate("serverstatus", "minecraft", getRegion().toString()); String dataKey = concatenate(setKey, serverName); String serializedData = jedis.get(dataKey); server = Utility.deserialize(serializedData, MinecraftServer.class); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return server; } @Override public void updataServerStatus(MinecraftServer serverData, int timeout) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { String serializedData = Utility.serialize(serverData); String serverName = serverData.getName(); - String setKey = concatenate("serverstatus", "minecraft", _region.toString()); + String setKey = concatenate("serverstatus", "minecraft", getRegion().toString()); String dataKey = concatenate(setKey, serverName); long expiry = Utility.currentTimeSeconds() + timeout; @@ -176,30 +128,15 @@ public class RedisServerRepository implements ServerRepository transaction.zadd(setKey, expiry, serverName); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override public void removeServerStatus(MinecraftServer serverData) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { String serverName = serverData.getName(); - String setKey = concatenate("serverstatus", "minecraft", _region.toString()); + String setKey = concatenate("serverstatus", "minecraft", getRegion().toString()); String dataKey = concatenate(setKey, serverName); Transaction transaction = jedis.multi(); @@ -207,19 +144,6 @@ public class RedisServerRepository implements ServerRepository transaction.zrem(setKey, serverName); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override @@ -232,9 +156,8 @@ public class RedisServerRepository implements ServerRepository public Collection getDedicatedServers() { Collection servers = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String key = concatenate("serverstatus", "dedicated"); Set serverNames = jedis.smembers(key); @@ -258,7 +181,7 @@ public class RedisServerRepository implements ServerRepository { DedicatedServer server = new DedicatedServer(data); - if (server.getRegion() == _region) + if (server.getRegion() == getRegion()) servers.add(server); } catch (Exception ex) @@ -268,20 +191,7 @@ public class RedisServerRepository implements ServerRepository } } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return servers; } @@ -289,10 +199,9 @@ public class RedisServerRepository implements ServerRepository public Collection getServerGroups(Collection serverStatuses) { Collection servers = new HashSet(); - Jedis jedis = _readPool.getResource(); - try + + try(Jedis jedis = getResource(false)) { - String key = "servergroups"; Set names = jedis.smembers(key); Set>> serverDatas = new HashSet>>(); @@ -321,7 +230,7 @@ public class RedisServerRepository implements ServerRepository { ServerGroup serverGroup = new ServerGroup(data, serverStatuses); - if (serverGroup.getRegion() == Region.ALL || serverGroup.getRegion() == _region) + if (serverGroup.getRegion() == Region.ALL || serverGroup.getRegion() == getRegion()) servers.add(serverGroup); } catch (Exception exception) @@ -331,20 +240,7 @@ public class RedisServerRepository implements ServerRepository } } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return servers; } @@ -356,28 +252,14 @@ public class RedisServerRepository implements ServerRepository protected Set getActiveNames(String key) { Set names = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String min = "(" + Utility.currentTimeSeconds(); String max = "+inf"; names = jedis.zrangeByScore(key, min, max); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return names; } @@ -388,51 +270,26 @@ public class RedisServerRepository implements ServerRepository protected Set getDeadNames(String key) { Set names = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { String min = "-inf"; String max = Utility.currentTimeSeconds() + ""; names = jedis.zrangeByScore(key, min, max); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return names; } - /** - * @param elements - the elements to concatenate together - * @return the concatenated form of all {@code elements} - * separated by the delimiter {@value KEY_DELIMITER}. - */ - protected String concatenate(String... elements) - { - return Utility.concatenate(KEY_DELIMITER, elements); - } - @Override public Collection getDeadServers() { Set servers = new HashSet(); - Jedis jedis = _readPool.getResource(); - - try + + try(Jedis jedis = getResource(false)) { Pipeline pipeline = jedis.pipelined(); - String setKey = concatenate("serverstatus", "minecraft", _region.toString()); + String setKey = concatenate("serverstatus", "minecraft", getRegion().toString()); String min = "-inf"; String max = Utility.currentTimeSeconds() + ""; @@ -454,29 +311,14 @@ public class RedisServerRepository implements ServerRepository servers.add(server); } } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return servers; } @Override public void updateServerGroup(ServerGroup serverGroup) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { HashMap serializedData = serverGroup.getDataMap(); System.out.println(serializedData); @@ -489,27 +331,12 @@ public class RedisServerRepository implements ServerRepository transaction.sadd(key, serverGroupName); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override public void removeServerGroup(ServerGroup serverGroup) { - Jedis jedis = _writePool.getResource(); - - try + try(Jedis jedis = getResource(true)) { String serverName = serverGroup.getName(); String setKey = "servergroups"; @@ -520,47 +347,20 @@ public class RedisServerRepository implements ServerRepository transaction.srem(setKey, serverName); transaction.exec(); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _writePool.returnResource(jedis); - } - } } @Override public ServerGroup getServerGroup(String serverGroup) { ServerGroup server = null; - Jedis jedis = _readPool.getResource(); - try + try(Jedis jedis = getResource(false)) { String key = concatenate("servergroups", serverGroup); Map data = jedis.hgetAll(key); server = new ServerGroup(data, null); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - _readPool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (jedis != null) - { - _readPool.returnResource(jedis); - } - } - + return server; } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java index cdb02169a..14d2f9958 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/StaffServer.java @@ -2,6 +2,12 @@ package mineplex.staffServer; import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_8_R3.CraftServer; +import org.bukkit.plugin.java.JavaPlugin; + +import com.mojang.authlib.GameProfile; + import mineplex.core.account.CoreClientManager; import mineplex.core.achievement.AchievementManager; import mineplex.core.antihack.AntiHack; @@ -9,6 +15,7 @@ import mineplex.core.chat.Chat; import mineplex.core.command.CommandCenter; import mineplex.core.creature.Creature; import mineplex.core.donation.DonationManager; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.inventory.InventoryManager; import mineplex.core.memory.MemoryFix; import mineplex.core.monitor.LagMeter; @@ -26,12 +33,6 @@ import mineplex.staffServer.customerSupport.CustomerSupport; import mineplex.staffServer.salespackage.SalesPackageManager; import net.minecraft.server.v1_8_R3.MinecraftServer; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.v1_8_R3.CraftServer; -import org.bukkit.plugin.java.JavaPlugin; - -import com.mojang.authlib.GameProfile; - public class StaffServer extends JavaPlugin { private String WEB_CONFIG = "webServer"; @@ -56,11 +57,11 @@ public class StaffServer extends JavaPlugin Punish punish = new Punish(this, webServerAddress, clientManager); new NpcManager(this, new Creature(this)); ServerStatusManager serverStatusManager = new ServerStatusManager(this, clientManager, new LagMeter(this, clientManager)); - PreferencesManager preferenceManager = new PreferencesManager(this, clientManager, donationManager); + PreferencesManager preferenceManager = new PreferencesManager(this, null, clientManager, donationManager); preferenceManager.GiveItem = false; Portal portal = new Portal(this, clientManager, serverStatusManager.getCurrentServerName()); - new Chat(this, clientManager, preferenceManager, new AchievementManager(new StatsManager(this, clientManager), clientManager, donationManager), serverStatusManager.getCurrentServerName()); + new Chat(this, null, clientManager, preferenceManager, new AchievementManager(new StatsManager(this, clientManager), clientManager, donationManager), serverStatusManager.getCurrentServerName()); new MemoryFix(this); new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion()); AntiHack.Initialize(this, punish, portal, preferenceManager, clientManager); diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java index 58e91b517..85502fd37 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupport.java @@ -1,6 +1,10 @@ package mineplex.staffServer.customerSupport; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import mineplex.core.MiniPlugin; import mineplex.core.account.CoreClient; @@ -13,6 +17,7 @@ import mineplex.core.donation.DonationManager; import mineplex.core.donation.Donor; import mineplex.core.donation.repository.token.CoinTransactionToken; import mineplex.core.donation.repository.token.TransactionToken; +import mineplex.serverdata.database.ResultSetCallable; import mineplex.staffServer.salespackage.SalesPackageManager; import org.bukkit.GameMode; @@ -27,13 +32,15 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; -public class CustomerSupport extends MiniPlugin +public class CustomerSupport extends MiniPlugin implements ResultSetCallable { private CoreClientManager _clientManager; private DonationManager _donationManager; private SalesPackageManager _salesPackageManager; + private CustomerSupportRepository _repository; private NautHashMap> _agentCacheMap = new NautHashMap>(); + private NautHashMap> _accountBonusLog = new NautHashMap<>(); public CustomerSupport(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager, SalesPackageManager salesPackageManager) { @@ -42,6 +49,7 @@ public class CustomerSupport extends MiniPlugin _clientManager = clientManager; _donationManager = donationManager; _salesPackageManager = salesPackageManager; + _repository = new CustomerSupportRepository(getPlugin()); } @EventHandler @@ -94,98 +102,124 @@ public class CustomerSupport extends MiniPlugin { CoreClient client = _clientManager.Get(playerName); Donor donor = _donationManager.Get(playerName); + CustomerSupport instance = this; - caller.sendMessage(C.cDGreen + C.Strike + "============================================="); - caller.sendMessage(C.cBlue + "Name : " + C.cYellow + playerName); - caller.sendMessage(C.cBlue + "Rank : " + C.cYellow + (client.GetRank() == null ? C.cRed + "Error rank null!" : (client.GetRank().Name.isEmpty() ? "Regular" : client.GetRank().Name))); - caller.sendMessage(C.cBlue + "Coins : " + C.cYellow + donor.getCoins()); - caller.sendMessage(C.cBlue + "Gems : " + C.cYellow + donor.GetGems()); - - int enjinCoinsReceived = 0; - int oldChestsReceived = 0; - int ancientChestsReceived = 0; - int mythicalChestsReceived = 0; - int winterChestsReceived = 0; - int valentinesGiftsReceived = 0; - - for (CoinTransactionToken transaction : donor.getCoinTransactions()) + runAsync(new Runnable() { - if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Halloween Pumpkin") || transaction.Source.equalsIgnoreCase("Treasure Chest") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase")) + public void run() { - if (transaction.Source.contains("purchase")) - enjinCoinsReceived += transaction.Amount; - } - } + _repository.loadBonusLogForAccountId(client.getAccountId(), instance); + + runSync(new Runnable() + { + public void run() + { + caller.sendMessage(C.cDGreen + C.Strike + "============================================="); + caller.sendMessage(C.cBlue + "Name : " + C.cYellow + playerName); + caller.sendMessage(C.cBlue + "Rank : " + C.cYellow + (client.GetRank() == null ? C.cRed + "Error rank null!" : (client.GetRank().Name.isEmpty() ? "Regular" : client.GetRank().Name))); + caller.sendMessage(C.cBlue + "Coins : " + C.cYellow + donor.getCoins()); + caller.sendMessage(C.cBlue + "Gems : " + C.cYellow + donor.GetGems()); - for (TransactionToken transaction : donor.getTransactions()) - { - if (transaction.SalesPackageName.startsWith("Old Chest")) - { - if (transaction.Coins == 0 && transaction.Gems == 0) - { - if (transaction.SalesPackageName.split(" ").length == 3) - oldChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); - else if (transaction.SalesPackageName.split(" ").length == 2) - oldChestsReceived += 1; - } - - } - if (transaction.SalesPackageName.startsWith("Ancient Chest")) - { - if (transaction.Coins == 0 && transaction.Gems == 0) - { - if (transaction.SalesPackageName.split(" ").length == 3) - ancientChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); - else if (transaction.SalesPackageName.split(" ").length == 2) - ancientChestsReceived += 1; - } - - } - if (transaction.SalesPackageName.startsWith("Mythical Chest")) - { - if (transaction.Coins == 0 && transaction.Gems == 0) - { - if (transaction.SalesPackageName.split(" ").length == 3) - mythicalChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); - else if (transaction.SalesPackageName.split(" ").length == 2) - mythicalChestsReceived += 1; - } - - } - if (transaction.SalesPackageName.startsWith("Winter Chest")) - { - if (transaction.Coins == 0 && transaction.Gems == 0) - { - if (transaction.SalesPackageName.split(" ").length == 3) - winterChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); - else if (transaction.SalesPackageName.split(" ").length == 2) - winterChestsReceived += 1; - } + int enjinCoinsReceived = 0; + int oldChestsReceived = 0; + int ancientChestsReceived = 0; + int mythicalChestsReceived = 0; + int winterChestsReceived = 0; + int valentinesGiftsReceived = 0; + + for (CoinTransactionToken transaction : donor.getCoinTransactions()) + { + if (transaction.Source.equalsIgnoreCase("Poll") || transaction.Source.equalsIgnoreCase("Halloween Pumpkin") || transaction.Source.equalsIgnoreCase("Treasure Chest") || transaction.Source.equalsIgnoreCase("Coin Party Bomb Pickup") || transaction.Source.contains("Reward") || transaction.Source.contains("purchase")) + { + if (transaction.Source.contains("purchase")) + enjinCoinsReceived += transaction.Amount; + } + } - } - if (transaction.SalesPackageName.startsWith("Valentines Gift")) - { - if (transaction.Coins == 0 && transaction.Gems == 0) - { - if (transaction.SalesPackageName.split(" ").length == 3) - valentinesGiftsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); - else if (transaction.SalesPackageName.split(" ").length == 2) - valentinesGiftsReceived += 1; - } + for (TransactionToken transaction : donor.getTransactions()) + { + if (transaction.SalesPackageName.startsWith("Old Chest")) + { + if (transaction.Coins == 0 && transaction.Gems == 0) + { + if (transaction.SalesPackageName.split(" ").length == 3) + oldChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + else if (transaction.SalesPackageName.split(" ").length == 2) + oldChestsReceived += 1; + } + + } + if (transaction.SalesPackageName.startsWith("Ancient Chest")) + { + if (transaction.Coins == 0 && transaction.Gems == 0) + { + if (transaction.SalesPackageName.split(" ").length == 3) + ancientChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + else if (transaction.SalesPackageName.split(" ").length == 2) + ancientChestsReceived += 1; + } + + } + if (transaction.SalesPackageName.startsWith("Mythical Chest")) + { + if (transaction.Coins == 0 && transaction.Gems == 0) + { + if (transaction.SalesPackageName.split(" ").length == 3) + mythicalChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + else if (transaction.SalesPackageName.split(" ").length == 2) + mythicalChestsReceived += 1; + } + + } + if (transaction.SalesPackageName.startsWith("Winter Chest")) + { + if (transaction.Coins == 0 && transaction.Gems == 0) + { + if (transaction.SalesPackageName.split(" ").length == 3) + winterChestsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + else if (transaction.SalesPackageName.split(" ").length == 2) + winterChestsReceived += 1; + } + } + if (transaction.SalesPackageName.startsWith("Valentines Gift")) + { + if (transaction.Coins == 0 && transaction.Gems == 0) + { + if (transaction.SalesPackageName.split(" ").length == 3) + valentinesGiftsReceived += Integer.parseInt(transaction.SalesPackageName.split(" ")[2]); + else if (transaction.SalesPackageName.split(" ").length == 2) + valentinesGiftsReceived += 1; + } + + } + } + + caller.sendMessage(C.cBlue + "Enjin Coin Total Received : " + C.cYellow + enjinCoinsReceived); + caller.sendMessage(C.cBlue + "Old Chests Received : " + C.cYellow + oldChestsReceived); + caller.sendMessage(C.cBlue + "Ancient Chests Received : " + C.cYellow + ancientChestsReceived); + caller.sendMessage(C.cBlue + "Mythical Chests Received : " + C.cYellow + mythicalChestsReceived); + caller.sendMessage(C.cBlue + "Winter Chests Received : " + C.cYellow + winterChestsReceived); + caller.sendMessage(C.cBlue + "Valentines Gifts Received : " + C.cYellow + valentinesGiftsReceived); + caller.sendMessage(C.cBlue + "Monthly Bonus Log (Last 6 entries):"); + + if (_accountBonusLog.containsKey(client.getAccountId())) + { + for (String logEntry : _accountBonusLog.get(client.getAccountId())) + { + caller.sendMessage(C.cYellow + logEntry); + } + } + + caller.sendMessage(C.cDGreen + C.Strike + "============================================="); + _salesPackageManager.displaySalesPackages(caller, playerName); + caller.sendMessage(C.cDGreen + C.Strike + "============================================="); + + _accountBonusLog.remove(client.getAccountId()); + } + }); } - } - - caller.sendMessage(C.cBlue + "Enjin Coin Total Received : " + C.cYellow + enjinCoinsReceived); - caller.sendMessage(C.cBlue + "Old Chests Received : " + C.cYellow + oldChestsReceived); - caller.sendMessage(C.cBlue + "Ancient Chests Received : " + C.cYellow + ancientChestsReceived); - caller.sendMessage(C.cBlue + "Mythical Chests Received : " + C.cYellow + mythicalChestsReceived); - caller.sendMessage(C.cBlue + "Winter Chests Received : " + C.cYellow + winterChestsReceived); - caller.sendMessage(C.cBlue + "Valentines Gifts Received : " + C.cYellow + valentinesGiftsReceived); - - caller.sendMessage(C.cDGreen + C.Strike + "============================================="); - _salesPackageManager.displaySalesPackages(caller, playerName); - caller.sendMessage(C.cDGreen + C.Strike + "============================================="); + }); } @EventHandler @@ -215,4 +249,20 @@ public class CustomerSupport extends MiniPlugin event.setCancelled(true); } + + @Override + public void processResultSet(ResultSet resultSet) throws SQLException + { + List log = new ArrayList(); + int accountId = 0; + + while (resultSet.next() && log.size() < 6) + { + accountId = resultSet.getInt(1); + log.add("Received " + resultSet.getInt(3) + " " + resultSet.getString(2) + " on " + resultSet.getDate(4)); + } + + if (accountId != 0) + _accountBonusLog.put(accountId, log); + } } diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupportRepository.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupportRepository.java new file mode 100644 index 000000000..877a4c71d --- /dev/null +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/CustomerSupportRepository.java @@ -0,0 +1,25 @@ +package mineplex.staffServer.customerSupport; + +import org.bukkit.plugin.java.JavaPlugin; + +import mineplex.core.database.MinecraftRepository; +import mineplex.serverdata.database.DBPool; + +public class CustomerSupportRepository extends MinecraftRepository +{ + public CustomerSupportRepository(JavaPlugin plugin) + { + super(plugin, DBPool.getAccount()); + } + + @Override + protected void initialize() { } + + @Override + protected void update() { } + + public void loadBonusLogForAccountId(int accountId, CustomerSupport customerSupport) + { + executeQuery("SELECT accountId, items.name, itemChange, time FROM bonusLog INNER JOIN items ON itemId = items.id WHERE accountId = " + accountId + " ORDER BY bonusLog.id DESC;", customerSupport); + } +} diff --git a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/checkCommand.java b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/checkCommand.java index c548351ca..b6303f8b3 100644 --- a/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/checkCommand.java +++ b/Plugins/Mineplex.StaffServer/src/mineplex/staffServer/customerSupport/checkCommand.java @@ -34,8 +34,8 @@ public class checkCommand extends CommandBase { public void run() { - Plugin.addAgentMapping(caller, name); Plugin.showPlayerInfo(caller, name); + Plugin.addAgentMapping(caller, name); } }); } diff --git a/Plugins/Mineplex.Votifier/src/mineplex/votifier/VotifierManager.java b/Plugins/Mineplex.Votifier/src/mineplex/votifier/VotifierManager.java index 23801e02d..de1e9e7c7 100644 --- a/Plugins/Mineplex.Votifier/src/mineplex/votifier/VotifierManager.java +++ b/Plugins/Mineplex.Votifier/src/mineplex/votifier/VotifierManager.java @@ -255,27 +255,12 @@ public class VotifierManager extends MiniPlugin { public void run() { - Jedis jedis = writePool.getResource(); - - try + try (Jedis jedis = writePool.getResource()) { String commandType = serverCommand.getClass().getSimpleName(); String serializedCommand = Utility.serialize(serverCommand); jedis.publish("commands.server" + ":" + commandType, serializedCommand); } - catch (JedisConnectionException exception) - { - exception.printStackTrace(); - writePool.returnBrokenResource(jedis); - jedis = null; - } - finally - { - if (writePool != null) - { - writePool.returnResource(jedis); - } - } } }).start(); } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/Arcade.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/Arcade.java index 9bec8fee2..f2c27d4b8 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/Arcade.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/Arcade.java @@ -30,6 +30,7 @@ import mineplex.core.give.Give; import mineplex.core.globalpacket.GlobalPacketManager; import mineplex.core.hologram.HologramManager; import mineplex.core.ignore.IgnoreManager; +import mineplex.core.incognito.IncognitoManager; import mineplex.core.inventory.InventoryManager; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.leaderboard.LeaderboardManager; @@ -57,6 +58,7 @@ import mineplex.core.velocity.VelocityFix; import mineplex.core.visibility.VisibilityManager; import mineplex.minecraft.game.core.combat.CombatManager; import mineplex.minecraft.game.core.damage.DamageManager; +import nautilus.game.arcade.broadcast.BroadcastManager; import nautilus.game.arcade.game.GameServerConfig; import net.minecraft.server.v1_8_R3.BiomeBase; import net.minecraft.server.v1_8_R3.MinecraftServer; @@ -108,15 +110,19 @@ public class Arcade extends JavaPlugin _serverConfiguration = new ServerConfiguration(this, _clientManager); - PreferencesManager preferenceManager = new PreferencesManager(this, _clientManager, _donationManager); + PacketHandler packetHandler = new PacketHandler(this); + + IncognitoManager incognito = new IncognitoManager(this, _clientManager, packetHandler); + PreferencesManager preferenceManager = new PreferencesManager(this, incognito, _clientManager, _donationManager); + incognito.setPreferencesManager(preferenceManager); + Creature creature = new Creature(this); ServerStatusManager serverStatusManager = new ServerStatusManager(this, _clientManager, new LagMeter(this, _clientManager)); LeaderboardManager leaderboardManager = new LeaderboardManager(this, _clientManager); Teleport teleport = new Teleport(this, _clientManager); Portal portal = new Portal(this, _clientManager, serverStatusManager.getCurrentServerName()); new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion()); - PacketHandler packetHandler = new PacketHandler(this); DisguiseManager disguiseManager = new DisguiseManager(this, packetHandler); @@ -131,8 +137,8 @@ public class Arcade extends JavaPlugin StatsManager statsManager = new StatsManager(this, _clientManager); AchievementManager achievementManager = new AchievementManager(statsManager, _clientManager, _donationManager); FriendManager friendManager = new FriendManager(this, _clientManager, preferenceManager, portal); - Chat chat = new Chat(this, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); - new MessageManager(this, _clientManager, preferenceManager, ignoreManager, punish, friendManager, chat); + Chat chat = new Chat(this, incognito, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName()); + new MessageManager(this, incognito, _clientManager, preferenceManager, ignoreManager, punish, friendManager, chat); BlockRestore blockRestore = new BlockRestore(this); @@ -154,7 +160,9 @@ public class Arcade extends JavaPlugin //Arcade Manager PollManager pollManager = new PollManager(this, _clientManager, _donationManager); - _gameManager = new ArcadeManager(this, serverStatusManager, ReadServerConfig(), _clientManager, _donationManager, _damageManager, statsManager, achievementManager, disguiseManager, creature, teleport, new Blood(this), chat, portal, preferenceManager, inventoryManager, packetHandler, cosmeticManager, projectileManager, petManager, hologramManager, webServerAddress, pollManager, npcmanager, customDataManager, punish); + _gameManager = new ArcadeManager(this, serverStatusManager, ReadServerConfig(), _clientManager, _donationManager, _damageManager, statsManager, incognito, achievementManager, disguiseManager, creature, teleport, new Blood(this), chat, portal, preferenceManager, inventoryManager, packetHandler, cosmeticManager, projectileManager, petManager, hologramManager, webServerAddress, pollManager, npcmanager, customDataManager, punish); + + //new BroadcastManager(this, _gameManager); new MemoryFix(this); new CustomTagFix(this, packetHandler); @@ -216,7 +224,7 @@ public class Arcade extends JavaPlugin for (String gameName : _serverConfiguration.getServerGroup().getGames().split(",")) { try - { + {System.out.println(gameName); GameType type = GameType.valueOf(gameName); config.GameList.add(type); } @@ -248,6 +256,11 @@ public class Arcade extends JavaPlugin return config; } + + public ArcadeManager getArcadeManager() + { + return _gameManager; + } private void DeleteFolders() { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java index eadeb8bd7..c642dee43 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/ArcadeManager.java @@ -34,6 +34,8 @@ import mineplex.core.facebook.FacebookManager; import mineplex.core.gadget.types.Gadget; import mineplex.core.gadget.types.GadgetType; import mineplex.core.hologram.HologramManager; +import mineplex.core.incognito.IncognitoManager; +import mineplex.core.incognito.events.IncognitoStatusChangeEvent; import mineplex.core.inventory.InventoryManager; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.movement.Movement; @@ -86,7 +88,6 @@ import nautilus.game.arcade.game.GameTeam; import nautilus.game.arcade.game.games.event.EventModule; import nautilus.game.arcade.game.games.uhc.UHC; import nautilus.game.arcade.managers.GameAchievementManager; -import nautilus.game.arcade.managers.chat.GameChatManager; import nautilus.game.arcade.managers.GameCreationManager; import nautilus.game.arcade.managers.GameFlagManager; import nautilus.game.arcade.managers.GameGemManager; @@ -100,11 +101,12 @@ import nautilus.game.arcade.managers.GameStatManager; import nautilus.game.arcade.managers.GameTestingManager; import nautilus.game.arcade.managers.GameTournamentManager; import nautilus.game.arcade.managers.GameWorldManager; -import nautilus.game.arcade.managers.HolidayManager; import nautilus.game.arcade.managers.IdleManager; import nautilus.game.arcade.managers.MiscManager; +import nautilus.game.arcade.managers.chat.GameChatManager; import nautilus.game.arcade.player.ArcadePlayer; import nautilus.game.arcade.shop.ArcadeShop; +import net.minecraft.server.v1_8_R3.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -133,7 +135,8 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.util.Vector; - +import net.minecraft.server.v1_8_R3.EntityLiving; + public class ArcadeManager extends MiniPlugin implements IRelation { // Modules @@ -188,12 +191,15 @@ public class ArcadeManager extends MiniPlugin implements IRelation private ResourcePackManager _resourcePackManager; private CustomDataManager _customDataManager; private Punish _punishmentManager; + + private IncognitoManager _incognitoManager; private TaskManager _taskManager; private PacketHandler _packetHandler; // Observers private HashSet _specList = new HashSet(); + private HashSet _fakeObserve = new HashSet(); // Server Games private GameServerConfig _serverConfig; @@ -209,7 +215,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation public ArcadeManager(Arcade plugin, ServerStatusManager serverStatusManager, GameServerConfig serverConfig, CoreClientManager clientManager, DonationManager donationManager, DamageManager damageManager, - StatsManager statsManager, AchievementManager achievementManager, DisguiseManager disguiseManager, Creature creature, Teleport teleport, Blood blood, Chat chat, + StatsManager statsManager, IncognitoManager incognitoManager, AchievementManager achievementManager, DisguiseManager disguiseManager, Creature creature, Teleport teleport, Blood blood, Chat chat, Portal portal, PreferencesManager preferences, InventoryManager inventoryManager, PacketHandler packetHandler, CosmeticManager cosmeticManager, ProjectileManager projectileManager, PetManager petManager, HologramManager hologramManager, String webAddress, PollManager pollManager, NpcManager npcManager, CustomDataManager customDataManager, Punish punish) @@ -221,6 +227,8 @@ public class ArcadeManager extends MiniPlugin implements IRelation // Modules _blockRestore = new BlockRestore(plugin); + _incognitoManager = incognitoManager; + _blood = blood; _preferencesManager = preferences; @@ -608,6 +616,41 @@ public class ArcadeManager extends MiniPlugin implements IRelation return true; } + @EventHandler + public void StaffIncognito(IncognitoStatusChangeEvent event) + { + if (event.getNewState() && _game != null && _game.IsPlaying(event.getPlayer()) && _game.IsLive()) + { + addSpectator(event.getPlayer(), true); + event.setCancelled(true); + return; + } + + if (event.getNewState()) + { + UtilServer.broadcast(F.sys("Quit", event.getPlayer().getName())); + + if (_game == null || _game.GetState() != GameState.Live) + { + _specList.add(event.getPlayer()); + } + } + else + { + UtilServer.broadcast(F.sys("Join", event.getPlayer().getName())); + + if (_game != null && isSpectator(event.getPlayer())) + { + if (_game.GetState() != GameState.Live) + { + _specList.remove(event.getPlayer()); + } + + event.show(false); + } + } + } + @EventHandler public void MessageMOTD(ServerListPingEvent event) { @@ -672,6 +715,15 @@ public class ArcadeManager extends MiniPlugin implements IRelation { String name = event.getPlayer().getName(); + if (_incognitoManager.Get(event.getPlayer()).Status) + { + event.setJoinMessage(null); + return; + } + + if (event.getJoinMessage() == null) + return; + if (_game != null && _game.AnnounceJoinQuit) event.setJoinMessage(F.sys("Join", GetColor(event.getPlayer()) + name)); @@ -682,8 +734,17 @@ public class ArcadeManager extends MiniPlugin implements IRelation @EventHandler public void MessageQuit(PlayerQuitEvent event) { + if (_incognitoManager.Get(event.getPlayer()).Status) + { + event.setQuitMessage(null); + return; + } + String name = event.getPlayer().getName(); + if (event.getQuitMessage() == null) + return; + if (_game == null || _game.AnnounceJoinQuit) event.setQuitMessage(F.sys("Quit", GetColor(event.getPlayer()) + name)); else @@ -870,7 +931,12 @@ public class ArcadeManager extends MiniPlugin implements IRelation UtilInv.Clear(player); - ((CraftEntity) player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0)); + UtilPlayer.setAutoDeploy(player, false); + UtilPlayer.setGlidableWithoutWings(player, false); + UtilPlayer.setGliding(player, false); + UtilPlayer.setAutoDeployDistance(player, 1.15F); + + ((CraftEntity) player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0), EntityLiving.META_ENTITYDATA, (byte) 0); player.setCustomName(""); player.setCustomNameVisible(false); @@ -1074,9 +1140,22 @@ public class ArcadeManager extends MiniPlugin implements IRelation { _specList.remove(event.getPlayer()); } + + public void toggleFakeObserver(Player player) + { + if (!_fakeObserve.remove(player)) + _fakeObserve.add(player); + } public boolean IsObserver(Player player) { + if (_fakeObserve.contains(player)) + return true; + + if (_incognitoManager.Get(player).Status) + { + _specList.add(player); + } return _specList.contains(player); } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/GameType.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/GameType.java index 54d042920..eed2cfd33 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/GameType.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/GameType.java @@ -1,7 +1,10 @@ package nautilus.game.arcade; -import org.bukkit.Material; +import java.util.AbstractMap; +import java.util.Map.Entry; +import mineplex.core.common.MinecraftVersion; +import mineplex.core.common.Pair; import mineplex.core.game.GameCategory; import mineplex.core.game.GameDisplay; import nautilus.game.arcade.game.Game; @@ -35,6 +38,7 @@ import nautilus.game.arcade.game.games.horsecharge.Horse; import nautilus.game.arcade.game.games.lobbers.BombLobbers; import nautilus.game.arcade.game.games.micro.Micro; import nautilus.game.arcade.game.games.milkcow.MilkCow; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; import nautilus.game.arcade.game.games.minestrike.MineStrike; import nautilus.game.arcade.game.games.mineware.BawkBawkBattles; import nautilus.game.arcade.game.games.monsterleague.MonsterLeague; @@ -43,6 +47,7 @@ import nautilus.game.arcade.game.games.oldmineware.OldMineWare; import nautilus.game.arcade.game.games.paintball.Paintball; import nautilus.game.arcade.game.games.quiver.Quiver; import nautilus.game.arcade.game.games.quiver.QuiverTeams; +import nautilus.game.arcade.game.games.rings.ElytraRings; import nautilus.game.arcade.game.games.runner.Runner; import nautilus.game.arcade.game.games.searchanddestroy.SearchAndDestroy; import nautilus.game.arcade.game.games.sheep.SheepGame; @@ -81,25 +86,40 @@ public enum GameType ChampionsCTF(ChampionsCTF.class, GameDisplay.ChampionsCTF), ChampionsDominate(ChampionsDominate.class, GameDisplay.ChampionsDominate), ChampionsTDM(ChampionsTDM.class, GameDisplay.ChampionsTDM), - Christmas(Christmas.class, GameDisplay.Christmas, "http://file.mineplex.com/ResChristmas.zip", true), + Christmas(Christmas.class, GameDisplay.Christmas, new Pair[] + { + Pair.create(MinecraftVersion.ALL, "http://file.mineplex.com/ResChristmas.zip") + }, true), DeathTag(DeathTag.class, GameDisplay.DeathTag), DragonEscape(DragonEscape.class, GameDisplay.DragonEscape), DragonEscapeTeams(DragonEscapeTeams.class, GameDisplay.DragonEscapeTeams), DragonRiders(DragonRiders.class, GameDisplay.DragonRiders), Dragons(Dragons.class, GameDisplay.Dragons), DragonsTeams(DragonsTeams.class, GameDisplay.DragonsTeams), - Draw(Draw.class, GameDisplay.Draw, "http://chivebox.com/mineplex/ResDrawMyThing.zip", true), + Draw(Draw.class, GameDisplay.Draw, new Pair[] + { + Pair.create(MinecraftVersion.ALL, "http://chivebox.com/mineplex/ResDrawMyThing.zip") + }, true), + ElytraRings(ElytraRings.class, GameDisplay.ElytraRings), Evolution(Evolution.class, GameDisplay.Evolution), Gravity(Gravity.class, GameDisplay.Gravity), - Halloween(Halloween.class, GameDisplay.Halloween, "http://file.mineplex.com/ResHalloween.zip", true), + Halloween(Halloween.class, GameDisplay.Halloween, new Pair[] + { + Pair.create(MinecraftVersion.ALL, "http://file.mineplex.com/ResHalloween.zip") + }, true), HideSeek(HideSeek.class, GameDisplay.HideSeek), HoleInTheWall(HoleInTheWall.class, GameDisplay.HoleInTheWall), Horse(Horse.class, GameDisplay.Horse), Lobbers(BombLobbers.class, GameDisplay.Lobbers), Micro(Micro.class, GameDisplay.Micro), MilkCow(MilkCow.class, GameDisplay.MilkCow), - MineStrike(MineStrike.class, GameDisplay.MineStrike, "http://chivebox.com/mineplex/ResMinestrike.zip", true), + MineStrike(MineStrike.class, GameDisplay.MineStrike, new Pair[] + { + Pair.create(MinecraftVersion.Version1_8, "http://chivebox.com/mineplex/ResMinestrike.zip"), + Pair.create(MinecraftVersion.Version1_9, "http://chivebox.com/mineplex/ResMinestrike19.zip") + }, true), BawkBawkBattles(BawkBawkBattles.class, GameDisplay.BawkBawkBattles), + MinecraftLeague(MinecraftLeague.class, GameDisplay.Minecraft_League), OldMineWare(OldMineWare.class, GameDisplay.OldMineWare), Paintball(Paintball.class, GameDisplay.Paintball), Quiver(Quiver.class, GameDisplay.Quiver), @@ -126,7 +146,10 @@ public enum GameType TurfWars(TurfForts.class, GameDisplay.TurfWars), UHC(UHC.class, GameDisplay.UHC), WitherAssault(WitherGame.class, GameDisplay.WitherAssault), - Wizards(Wizards.class, GameDisplay.Wizards, "http://file.mineplex.com/ResWizards.zip", true), + Wizards(Wizards.class, GameDisplay.Wizards, new Pair[] + { + Pair.create(MinecraftVersion.ALL, "http://file.mineplex.com/ResWizards.zip") + }, true), ZombieSurvival(ZombieSurvival.class, GameDisplay.ZombieSurvival), Build(Build.class, GameDisplay.Build), Cards(Cards.class, GameDisplay.Cards), @@ -156,7 +179,7 @@ public enum GameType boolean _enforceResourcePack; GameType[] _mapSource; boolean _ownMaps; - String _resourcePack; + Pair[] _resourcePacks; Class _gameClass; private int _gameId; // Unique identifying id for this gamemode (used for statistics) @@ -167,7 +190,7 @@ public enum GameType this(gameClass, display, null, false, null, true); } - GameType(Class gameClass, GameDisplay display, String resourcePackUrl, boolean enforceResourcePack) + GameType(Class gameClass, GameDisplay display, Pair[] resourcePackUrl, boolean enforceResourcePack) { this(gameClass, display, resourcePackUrl, enforceResourcePack, null, true); } @@ -177,11 +200,12 @@ public enum GameType this(gameClass, display, null, false, mapSource, ownMap); } - GameType(Class gameClass, GameDisplay display, String resourcePackUrl, boolean enforceResourcePack, GameType[] mapSource, boolean ownMaps) + GameType(Class gameClass, GameDisplay display, Pair[] resourcePackUrls, boolean enforceResourcePack, GameType[] mapSource, boolean ownMaps) { _display = display; + _gameId = display.getGameId(); _gameClass = gameClass; - _resourcePack = resourcePackUrl; + _resourcePacks = resourcePackUrls; _enforceResourcePack = enforceResourcePack; _mapSource = mapSource; _ownMaps = ownMaps; @@ -197,11 +221,11 @@ public enum GameType return _enforceResourcePack; } - public String getResourcePackUrl() + public Pair[] getResourcePackUrls() { - return _resourcePack; + return _resourcePacks; } - + public GameType[] getMapSource() { return _mapSource; @@ -241,5 +265,4 @@ public enum GameType { return _display.getKitGameName(); } - } \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastData.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastData.java new file mode 100644 index 000000000..fe4b389da --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastData.java @@ -0,0 +1,97 @@ +package nautilus.game.arcade.broadcast; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import mineplex.core.recharge.Recharge; +import net.minecraft.server.v1_8_R3.PacketPlayOutCamera; + +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class BroadcastData +{ + private Player _player; + private BroadcastManager _plugin; + + private boolean _rotate; + + private List _gamePlayers; + private List _recentlyViewed; + private Player _currentlyViewing; + + public BroadcastData(Player player, BroadcastManager plugin) + { + _player = player; + _plugin = plugin; + + _recentlyViewed = new ArrayList(); + + setRotating(false); + } + + private void setRotating(boolean rotate) + { + _rotate = rotate; + UtilPlayer.message(_player, F.main(_plugin.getName(), "Player Rotation: " + rotate)); + } + + public boolean isRotating() + { + return _rotate; + } + + public Player currentView() + { + return _currentlyViewing; + } + + public Player nextPlayer() + { + if (_gamePlayers.size() == _recentlyViewed.size()) + _recentlyViewed.clear(); + + for (Player player : _gamePlayers) + { + if (!player.isOnline() || !player.isValid() || player.isDead()) + continue; + + if (!_recentlyViewed.contains(player)) + return player; + } + + return null; + } + + public void toggleRotating(List gamePlayers) + { + if (!isRotating()) + { + if (gamePlayers == null) + return; + + if (gamePlayers.size() == 0) + return; + + _gamePlayers = gamePlayers; + } + if (isRotating()) + { + PacketPlayOutCamera restore = new PacketPlayOutCamera((net.minecraft.server.v1_8_R3.Entity)_player); + ((CraftPlayer)_player).getHandle().playerConnection.sendPacket(restore); + } + setRotating(!isRotating()); + } + + public void goToNext(Player player) + { + Recharge.Instance.useForce(_player, "Broadcaster Rotation", UtilTime.convert(10, TimeUnit.SECONDS, TimeUnit.MILLISECONDS), false); + _currentlyViewing = player; + PacketPlayOutCamera view = new PacketPlayOutCamera((net.minecraft.server.v1_8_R3.Entity)player); + ((CraftPlayer)_player).getHandle().playerConnection.sendPacket(view); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastManager.java new file mode 100644 index 000000000..d3693e598 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/BroadcastManager.java @@ -0,0 +1,120 @@ +package nautilus.game.arcade.broadcast; + +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.MiniPlugin; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.game.Game; +import nautilus.game.arcade.game.Game.GameState; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +public class BroadcastManager extends MiniPlugin +{ + ArcadeManager ArcadeManager; + private ConcurrentHashMap _broadcasters; + + public BroadcastManager(JavaPlugin plugin, ArcadeManager manager) + { + super("Broadcasting Manager", plugin); + ArcadeManager = manager; + _broadcasters = new ConcurrentHashMap(); + } + + public boolean isBroadcaster(Player player) + { + return _broadcasters.containsKey(player); + } + + public void addBroadcaster(Player player) + { + _broadcasters.put(player, new BroadcastData(player, this)); + if (ArcadeManager.GetGame() != null) + { + ArcadeManager.GetGame().RemoveTeamPreference(player); + ArcadeManager.GetGame().GetPlayerKits().remove(player); + ArcadeManager.GetGame().GetPlayerGems().remove(player); + try + { + ArcadeManager.GetGame().GetTeam(player).RemovePlayer(player); + } + catch (Exception e) {} + ArcadeManager.Clear(player); + ArcadeManager.toggleFakeObserver(player); + } + player.getInventory().clear(); + player.setGameMode(GameMode.SPECTATOR); + } + + public void removeBroadcaster(Player player) + { + _broadcasters.remove(player); + ArcadeManager.toggleFakeObserver(player); + if (ArcadeManager.GetGame().InProgress()) + ArcadeManager.addSpectator(player, true); + player.setGameMode(GameMode.SURVIVAL); + } + + @EventHandler + public void handleBroadcasting(GameStateChangeEvent event) + { + if (event.GetState() == GameState.Dead) + { + for (BroadcastData data : _broadcasters.values()) + { + if (data.isRotating()) + data.toggleRotating(null); + } + _broadcasters.clear(); + } + } + + @EventHandler + public void handleRotation(UpdateEvent event) + { + if (event.getType() == UpdateType.FASTEST) + { + Game game = ArcadeManager.GetGame(); + if (game == null) + return; + if (!game.InProgress()) + return; + + for (Player player : _broadcasters.keySet()) + { + if (!Recharge.Instance.usable(player, "Broadcaster Rotation", false)) + continue; + } + } + } + + @EventHandler + public void handleRotation(PlayerQuitEvent event) + { + Game game = ArcadeManager.GetGame(); + if (game == null) + return; + if (!game.InProgress()) + return; + + if (_broadcasters.containsKey(event.getPlayer())) + _broadcasters.remove(event.getPlayer()); + + for (BroadcastData data : _broadcasters.values()) + { + if (data.currentView() == null) + continue; + + if (data.currentView() == event.getPlayer()); + data.goToNext(data.nextPlayer()); + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/BroadcastCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/BroadcastCommand.java new file mode 100644 index 000000000..49d4858d2 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/BroadcastCommand.java @@ -0,0 +1,33 @@ +package nautilus.game.arcade.broadcast.command; + +import mineplex.core.command.MultiCommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import nautilus.game.arcade.broadcast.BroadcastManager; +import nautilus.game.arcade.broadcast.command.manage.AddCommand; +import nautilus.game.arcade.broadcast.command.manage.RemoveCommand; + +import org.bukkit.entity.Player; + +public class BroadcastCommand extends MultiCommandBase +{ + public BroadcastCommand(BroadcastManager plugin) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.TWITCH, Rank.YOUTUBE, Rank.YOUTUBE_SMALL, Rank.JNR_DEV}, "broadcaster"); + AddCommand(new AddCommand(plugin)); + AddCommand(new RemoveCommand(plugin)); + AddCommand(new RotateCommand(plugin)); + } + + @Override + protected void Help(Player caller, String[] args) + { + UtilPlayer.message(caller, F.main(Plugin.getName(), "Commands List:")); + UtilPlayer.message(caller, F.help("/broadcaster add ", "Puts a player in Broadcast mode for this game", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/broadcaster remove ", "Takes a player out of Broadcast mode", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/broadcaster rotate", "Toggles rotating view between game players", Rank.TWITCH)); + UtilPlayer.message(caller, F.main("Tip", "Rotation is great for a background to commentary!")); + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/RotateCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/RotateCommand.java new file mode 100644 index 000000000..b455ce4af --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/RotateCommand.java @@ -0,0 +1,21 @@ +package nautilus.game.arcade.broadcast.command; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.broadcast.BroadcastManager; + +public class RotateCommand extends CommandBase +{ + public RotateCommand(BroadcastManager plugin) { + super(plugin, Rank.TWITCH, "rotate"); + } + + @Override + public void Execute(Player caller, String[] args) + { + + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/AddCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/AddCommand.java new file mode 100644 index 000000000..ee67c8609 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/AddCommand.java @@ -0,0 +1,22 @@ +package nautilus.game.arcade.broadcast.command.manage; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.broadcast.BroadcastManager; + +public class AddCommand extends CommandBase +{ + public AddCommand(BroadcastManager plugin) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.JNR_DEV}, "add"); + } + + @Override + public void Execute(Player caller, String[] args) + { + + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/RemoveCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/RemoveCommand.java new file mode 100644 index 000000000..021202498 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/broadcast/command/manage/RemoveCommand.java @@ -0,0 +1,22 @@ +package nautilus.game.arcade.broadcast.command.manage; + +import org.bukkit.entity.Player; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.broadcast.BroadcastManager; + +public class RemoveCommand extends CommandBase +{ + public RemoveCommand(BroadcastManager plugin) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.JNR_DEV}, "remove"); + } + + @Override + public void Execute(Player caller, String[] args) + { + + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java index 79e46c510..30f0bd51f 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/Game.java @@ -1,5 +1,6 @@ package nautilus.game.arcade.game; +import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -55,6 +56,9 @@ import mineplex.core.common.util.UtilTabTitle; import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.common.util.UtilTime; import mineplex.core.disguise.disguises.DisguisePlayer; +import mineplex.core.elo.EloPlayer; +import mineplex.core.elo.EloTeam; +import mineplex.core.elo.GameResult; import mineplex.core.itemstack.ItemBuilder; import mineplex.core.packethandler.IPacketHandler; import mineplex.core.packethandler.PacketInfo; @@ -309,10 +313,11 @@ public abstract class Game implements Listener public String Winner = "Nobody"; public GameTeam WinnerTeam = null; - + + //ELO public boolean EloRanking = false; public int EloStart = 1000; - + public boolean CanAddStats = true; public boolean CanGiveLoot = true; @@ -401,7 +406,7 @@ public abstract class Game implements Listener new ExperienceStatTracker(this), new WinStatTracker(this), new LoseStatTracker(this), new DamageDealtStatTracker( this), new DamageTakenStatTracker(this), new GamesPlayedStatTracker(this)); - Manager.getResourcePackManager().setResourcePack(gameType.getResourcePackUrl(), gameType.isEnforceResourcePack()); + Manager.getResourcePackManager().setResourcePack(gameType.getResourcePackUrls(), gameType.isEnforceResourcePack()); _useEntityPacketHandler = new IPacketHandler() { @@ -438,7 +443,7 @@ public abstract class Game implements Listener { return _gameType.GetName(); } - + public GameType[] GetWorldHostNames() { GameType[] mapSource = new GameType[] @@ -595,7 +600,7 @@ public abstract class Game implements Listener // Event GameStateChangeEvent stateEvent = new GameStateChangeEvent(this, state); UtilServer.getServer().getPluginManager().callEvent(stateEvent); - + System.out.println(GetName() + " state set to " + state.toString()); } @@ -888,7 +893,7 @@ public abstract class Game implements Listener public void RespawnPlayer(final Player player) { player.eject(); - player.teleport(GetTeam(player).GetSpawn()); + RespawnPlayerTeleport(player); Manager.Clear(player); @@ -905,6 +910,11 @@ public abstract class Game implements Listener } }, 0); } + + public void RespawnPlayerTeleport(Player player) + { + player.teleport(GetTeam(player).GetSpawn()); + } public boolean IsPlaying(Player player) { @@ -1032,18 +1042,6 @@ public abstract class Game implements Listener return SpectatorSpawn; } - @EventHandler - public void eloStart(PlayerLoginEvent event) - { - if (EloRanking) - { - if (Manager.getEloManager().getElo(event.getPlayer().getUniqueId(), GetName()) == -1) - { - Manager.getEloManager().saveElo(event.getPlayer().getUniqueId(), GetName(), EloStart); - } - } - } - @EventHandler public abstract void ScoreboardUpdate(UpdateEvent event); @@ -1206,9 +1204,11 @@ public abstract class Game implements Listener } UtilTextMiddle.display(winnerText, subColor + "won the game", 20, 120, 20); - + if (AnnounceSilence) Manager.GetChat().Silence(5000, false); + + endElo(); } public void AnnounceEnd(List places) @@ -1263,9 +1263,11 @@ public abstract class Game implements Listener } UtilTextMiddle.display(winnerText, subColor + "won the game", 20, 120, 20); - + if (AnnounceSilence) Manager.GetChat().Silence(5000, false); + + endElo(); } public void Announce(String message) @@ -1288,7 +1290,7 @@ public abstract class Game implements Listener System.out.println("[Announcement] " + message); } - + public boolean AdvertiseText(GameLobbyManager gameLobbyManager, int _advertiseStage) { return false; @@ -1564,11 +1566,49 @@ public abstract class Game implements Listener if (player.isOnline()) AddGems(player, 10, "Participation", false, false); } - + + endElo(); + // End SetState(GameState.End); } + @EventHandler + public void onGameStart(GameStateChangeEvent event) + { + if (event.GetState() == GameState.Live) + { + if (EloRanking) + { + // Populate teams + for (GameTeam team : GetTeamList()) + { + EloTeam eloTeam = new EloTeam(); + + for (Player player : team.GetPlayers(false)) + { + eloTeam.addPlayer(new EloPlayer(player, Manager.GetClients().getAccountId(player), Manager.getEloManager().getElo(player, GetType().getGameId()))); + } + + Manager.getEloManager().addTeam(team.getDisplayName(), eloTeam); + } + } + } + } + + // Handle Elo at end of game -- method can be overridden in different game modes to meet their individual needs + protected void endElo() + { + if (EloRanking) + { + if (WinnerTeam != null) + Manager.getEloManager().setWinningTeam(WinnerTeam.getDisplayName()); + + Manager.getEloManager().endMatch(GetType().getGameId()); + } + } + + @EventHandler public void handleInteractEntityPacket(GameStateChangeEvent event) { @@ -1776,4 +1816,5 @@ public abstract class Game implements Listener public void addTutorials(){} public void disable(){} + } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/GameOption.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/GameOption.java new file mode 100644 index 000000000..38f67d7fd --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/GameOption.java @@ -0,0 +1,51 @@ +/*Every GameOption will have SetOption and GetOption methods + * However, since each GameOption class will have a different return type + * and take different parameters, there isn't much need to create any here at this time +*/ + +package nautilus.game.arcade.game; + +import org.bukkit.material.MaterialData; + +public class GameOption +{ + //Store the name and Description of each option - Literally every GameOption should have these + private String _optionName; + private String _optionDescription; + private MaterialData _optionMaterialData; + + public GameOption(String optName, String optDesc) + { + _optionName = optName; + _optionDescription = optDesc; + } + + public GameOption(MaterialData _optMat, String optName, String optDesc) + { + _optionName = optName; + _optionDescription = optDesc; + _optionMaterialData = _optMat; + } + + //Get methods for name of option and description + public String GetOptionName() + { + return _optionName; + } + + public String GetOptionDescription() + { + return _optionDescription; + } + + public MaterialData GetOptionMaterialData() + { + if(_optionMaterialData != null) + { + return _optionMaterialData; + } + + return null; + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/bridge/Bridge.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/bridge/Bridge.java index d19dc43e7..810812772 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/bridge/Bridge.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/bridge/Bridge.java @@ -1118,11 +1118,17 @@ public class Bridge extends TeamGame implements OreObsfucation while (!UtilBlock.airFoliage(block)) { block = block.getRelative(BlockFace.UP); + + if (block.getY() >= 256) + break; } while (UtilBlock.airFoliage(block)) { block = block.getRelative(BlockFace.DOWN); + + if (block.getY() <= 0) + break; } block = block.getRelative(BlockFace.UP); @@ -1943,4 +1949,10 @@ public class Bridge extends TeamGame implements OreObsfucation { event.setCancelled(true); } + + public void setBridgeTime(int time) + { + _bridgeTime = time; + } + } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsCTF.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsCTF.java index c2633e3b4..fbe9a5428 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsCTF.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsCTF.java @@ -71,7 +71,6 @@ public class ChampionsCTF extends CaptureTheFlag InventoryOpenChest = true; - EloRanking = false; EloStart = 1000; this.DontAllowOverfill = true; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java index 83b44d9de..f8583deec 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsDominate.java @@ -66,7 +66,6 @@ public class ChampionsDominate extends Domination InventoryOpenChest = true; - EloRanking = false; EloStart = 1000; this.DontAllowOverfill = true; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java index 73bbb3812..3f6441659 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/champions/ChampionsTDM.java @@ -66,7 +66,6 @@ public class ChampionsTDM extends TeamDeathmatch this.StrictAntiHack = true; InventoryOpenChest = true; - this.DisableKillCommand = false; this.DontAllowOverfill = true; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/christmas/SleighHorse.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/christmas/SleighHorse.java index 0f0e5ed2f..8bbe45336 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/christmas/SleighHorse.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/christmas/SleighHorse.java @@ -1,6 +1,7 @@ package nautilus.game.arcade.game.games.christmas; import java.util.HashSet; +import java.util.UUID; import org.bukkit.Location; import org.bukkit.Material; @@ -18,6 +19,8 @@ import mineplex.core.common.util.C; import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilPlayer; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.Entity; +import net.minecraft.server.v1_8_R3.EntityArmorStand; import net.minecraft.server.v1_8_R3.EntityPlayer; import net.minecraft.server.v1_8_R3.EntityTrackerEntry; import net.minecraft.server.v1_8_R3.Packet; @@ -162,11 +165,13 @@ public class SleighHorse packet.d = (int) (loc.getY() * 32); packet.e = (int) (loc.getZ() * 32) + this._previousDir[(i * 2) + 1]; packet.f = ((byte) (int) (loc.getYaw() * 256.0F / 360.0F)); + packet.uuid = UUID.randomUUID(); + // Setup datawatcher for armor stand DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(10, (byte) 4); - watcher.a(11, new Vector3f(0, i * 180, (i == 0 ? -1 : 1) * 60f)); + watcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 32); + watcher.a(10, (byte) 4, EntityArmorStand.META_ARMOR_OPTION, (byte) 4); + watcher.a(11, new Vector3f(0, i * 180, (i == 0 ? -1 : 1) * 60f), EntityArmorStand.META_HEAD_POSE, new Vector3f(0, i * 180, (i == 0 ? -1 : 1) * 60f)); packet.l = watcher; PacketPlayOutEntityEquipment enquipPacket = new PacketPlayOutEntityEquipment(); enquipPacket.a = id; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/CaptureTheFlag.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/CaptureTheFlag.java index d2d8dd2e8..6ecb96ed2 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/CaptureTheFlag.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/CaptureTheFlag.java @@ -551,51 +551,10 @@ public class CaptureTheFlag extends TeamGame if (player.isOnline()) AddGems(player, 10, "Participation", false, false); } - - if (EloRanking) - { - EloTeam teamWinner = new EloTeam(); - EloTeam teamLoser = new EloTeam(); - - for (GameTeam team : GetTeamList()) - { - if (WinnerTeam != null && team.equals(WinnerTeam)) - { - for (Player player : WinnerTeam.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamWinner.addPlayer(eloPlayer); - } - } - else - { - for (Player player : team.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamLoser.addPlayer(eloPlayer); - } - } - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamWinner, teamLoser, GameResult.Win).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamLoser, teamWinner, GameResult.Loss).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - } + endElo(); //End - SetState(GameState.End); + SetState(GameState.End); } @Override diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/Domination.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/Domination.java index c92af3e1f..55a56367f 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/Domination.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/Domination.java @@ -315,47 +315,7 @@ public class Domination extends TeamGame AddGems(player, 10, "Participation", false, false); } - if (EloRanking) - { - EloTeam teamWinner = new EloTeam(); - EloTeam teamLoser = new EloTeam(); - - for (GameTeam team : GetTeamList()) - { - if (WinnerTeam != null && team.equals(WinnerTeam)) - { - for (Player player : WinnerTeam.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamWinner.addPlayer(eloPlayer); - } - } - else - { - for (Player player : team.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamLoser.addPlayer(eloPlayer); - } - } - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamWinner, teamLoser, GameResult.Win).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamLoser, teamWinner, GameResult.Loss).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - } + endElo(); //End SetState(GameState.End); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java index 1e26628f7..5b016f0a3 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/common/TeamDeathmatch.java @@ -3,11 +3,30 @@ package nautilus.game.arcade.game.games.common; import java.util.ArrayList; import java.util.HashMap; -import org.bukkit.ChatColor; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.minecraft.game.core.combat.DeathMessageType; +import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.GameType; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.GameTeam.PlayerState; +import nautilus.game.arcade.game.TeamGame; +import nautilus.game.arcade.game.games.common.dominate_data.CapturePointTDM; +import nautilus.game.arcade.game.games.common.dominate_data.Resupply; +import nautilus.game.arcade.kit.Kit; + import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; -import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -18,38 +37,6 @@ import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.scoreboard.Objective; -import mineplex.core.common.util.C; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilTime; -import mineplex.core.elo.EloPlayer; -import mineplex.core.elo.EloTeam; -import mineplex.core.elo.GameResult; -import mineplex.core.updater.UpdateType; -import mineplex.core.updater.event.UpdateEvent; -import mineplex.minecraft.game.core.combat.DeathMessageType; -import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; -import nautilus.game.arcade.ArcadeManager; -import nautilus.game.arcade.GameType; -import nautilus.game.arcade.events.GameStateChangeEvent; -import nautilus.game.arcade.game.GameTeam; -import nautilus.game.arcade.game.TeamGame; -import nautilus.game.arcade.game.Game.GameState; -import nautilus.game.arcade.game.GameTeam.PlayerState; -import nautilus.game.arcade.game.games.champions.kits.KitAssassin; -import nautilus.game.arcade.game.games.champions.kits.KitBrute; -import nautilus.game.arcade.game.games.champions.kits.KitKnight; -import nautilus.game.arcade.game.games.champions.kits.KitMage; -import nautilus.game.arcade.game.games.champions.kits.KitRanger; -import nautilus.game.arcade.game.games.common.dominate_data.CapturePoint; -import nautilus.game.arcade.game.games.common.dominate_data.CapturePointTDM; -import nautilus.game.arcade.game.games.common.dominate_data.Emerald; -import nautilus.game.arcade.game.games.common.dominate_data.Resupply; -import nautilus.game.arcade.kit.Kit; - public class TeamDeathmatch extends TeamGame { private ArrayList _points = new ArrayList(); @@ -78,7 +65,22 @@ public class TeamDeathmatch extends TeamGame this.HungerSet = 20; this.WorldTimeSet = 2000; this.CompassEnabled = true; - + + //this.EloRanking = true; + //this.EloSetting.setEloSetting(2); + + //this.addEloColumn(); + + /* + try + { + this.Manager.getEloManager().addGameToDatabase("ALTER TABLE Accounts.eloRatingTest ADD [Champions TDM Team Deathmatch] INT;"); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + */ + this.Manager.GetDamage().UseSimpleWeaponDamage = false; //_healthObj = GetScoreboard().registerNewObjective("HP", "dummy"); @@ -127,7 +129,7 @@ public class TeamDeathmatch extends TeamGame { if (!(event.GetEvent().getEntity() instanceof Player)) return; - + Player killed = (Player)event.GetEvent().getEntity(); SetPlayerState(killed, PlayerState.OUT); @@ -158,7 +160,7 @@ public class TeamDeathmatch extends TeamGame } } } - + @EventHandler public void Health(GameStateChangeEvent event) { @@ -334,9 +336,6 @@ public class TeamDeathmatch extends TeamGame ScoreboardWrite(); - //Announce - AnnounceEnd(winner); - for (GameTeam team : GetTeamList()) { if (WinnerTeam != null && team.equals(WinnerTeam)) @@ -349,53 +348,28 @@ public class TeamDeathmatch extends TeamGame if (player.isOnline()) AddGems(player, 10, "Participation", false, false); } - - if (EloRanking) - { - EloTeam teamWinner = new EloTeam(); - EloTeam teamLoser = new EloTeam(); - - for (GameTeam team : GetTeamList()) - { - if (WinnerTeam != null && team.equals(WinnerTeam)) - { - for (Player player : WinnerTeam.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamWinner.addPlayer(eloPlayer); - } - } - else - { - for (Player player : team.GetPlayers(false)) - { - EloPlayer eloPlayer = new EloPlayer(); - eloPlayer.UniqueId = player.getUniqueId().toString(); - eloPlayer.Rating = Manager.getEloManager().getElo(player.getUniqueId(), GetName()); - - teamLoser.addPlayer(eloPlayer); - } - } - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamWinner, teamLoser, GameResult.Win).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - - for (EloPlayer eloPlayer : Manager.getEloManager().getNewRatings(teamLoser, teamWinner, GameResult.Loss).getPlayers()) - { - Manager.getEloManager().saveElo(eloPlayer.UniqueId, GetName(), eloPlayer.Rating); - } - } - + + //Announce End + AnnounceEnd(winner); + //End SetState(GameState.End); } + /*//call endElo (Game.Java) if the game ends + @EventHandler + public void EloCalc(GameStateChangeEvent event) + { + //relevant if we decide to move this to Game.java + if(EloRanking) + { + if (event.GetState() == GameState.End) + { + endElo(); + } + } + }*/ + @EventHandler(priority = EventPriority.HIGHEST) public void UsableInteract(PlayerInteractEvent event) { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/draw/tools/Tool.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/draw/tools/Tool.java index 11893a40e..4470fb7e6 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/draw/tools/Tool.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/draw/tools/Tool.java @@ -40,6 +40,9 @@ public abstract class Tool public void start(PlayerInteractEvent event) { + if (_start != null) + return; + if (!UtilEvent.isAction(event, ActionType.R)) return; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventModule.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventModule.java index 31508193d..379833f82 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventModule.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/event/EventModule.java @@ -17,7 +17,9 @@ import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilSystem; import mineplex.core.common.util.UtilText; +import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.common.util.UtilEvent.ActionType; +import mineplex.core.common.util.UtilInv; import mineplex.core.creature.event.CreatureKillEntitiesEvent; import mineplex.core.event.StackerEvent; import mineplex.core.gadget.gadgets.morph.MorphBlock; @@ -30,6 +32,7 @@ import mineplex.core.updater.event.UpdateEvent; import mineplex.minecraft.game.core.damage.CustomDamageEvent; import nautilus.game.arcade.ArcadeManager; import nautilus.game.arcade.events.PlayerDeathOutEvent; +import nautilus.game.arcade.game.games.bridge.Bridge; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -452,6 +455,84 @@ public class EventModule extends MiniPlugin } UtilPlayer.message(event.getPlayer(), F.main("Event", "You gave the gadget " + F.item(gadget) + " to all Players!")); } + else if (args[0].equalsIgnoreCase("announce")) + { + String text = args[1]; + + for (int i = 2; i < args.length; i++) + { + text += " " + args[i]; + } + + UtilTextMiddle.display(C.cDGreenB + "Announcement", text); + UtilServer.broadcast(F.main("Event Announcement", text)); + } + else if (args[0].equalsIgnoreCase("clear")) + { + String playerName = args[1]; + + if (playerName.equalsIgnoreCase("@a")) + { + for (Player player : UtilServer.getPlayers()) + { + UtilInv.Clear(player); + } + + UtilPlayer.message(event.getPlayer(), F.main("Event", "Cleared everyone's inventory!")); + } + else + { + Player player = Bukkit.getPlayer(args[1]); + + if (player == null) + { + UtilPlayer.message(event.getPlayer(), "No matches for: " + F.elem(args[1])); + } + else + { + UtilInv.Clear(player); + UtilPlayer.message(event.getPlayer(), F.main("Event", "Cleared " + F.elem(player.getName() + "'s") + " inventory!")); + } + } + } + else if (args[0].equalsIgnoreCase("bridge")) + { + if (!(Manager.GetGame() instanceof Bridge)) + { + UtilPlayer.message(event.getPlayer(), F.main("Event", "You can only drop the bridges in Bridges!")); + return; + } + + if (((Bridge) Manager.GetGame()).isBridgesDown()) + { + UtilPlayer.message(event.getPlayer(), F.main("Event", "The bridges have already dropped!")); + return; + } + + int seconds = 10; + + if (args.length > 1) + { + try + { + seconds = Integer.parseInt(args[1]); + } + catch (NumberFormatException e) + { + UtilPlayer.message(event.getPlayer(), F.main("Event", "Invalid integer for seconds!")); + return; + } + } + + if (seconds < 0) + { + UtilPlayer.message(event.getPlayer(), F.main("Event", "Seconds must be greater than 0!")); + return; + } + + ((Bridge) Manager.GetGame()).setBridgeTime((int) ((System.currentTimeMillis() - Manager.GetGame().GetStateTime()) + seconds * 1000)); + UtilPlayer.message(event.getPlayer(), F.main("Event", "Bridges will drop in " + F.elem(seconds + " Seconds") + "!")); + } } public void listSettings(Player player) diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/HideSeek.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/HideSeek.java index f360e190a..5488f3d77 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/HideSeek.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/HideSeek.java @@ -240,54 +240,45 @@ public class HideSeek extends TeamGame for (Entry entry : _forms.entrySet()) { - if (entry.getValue() instanceof BlockForm) + if (!(entry.getValue() instanceof BlockForm)) + continue; + + final BlockForm blockForm = (BlockForm) entry.getValue(); + + if (blockForm.Player.getEntityId() != id || blockForm.Player == packetInfo.getPlayer()) + continue; + + final Player player = packetInfo.getPlayer(); + + Bukkit.getScheduler().scheduleSyncDelayedTask(Manager.getPlugin(), new Runnable() { - final BlockForm blockForm = (BlockForm) entry - .getValue(); - - if (blockForm.Player.getEntityId() == id - && blockForm.Player != packetInfo.getPlayer()) + public void run() { - final Player player = packetInfo.getPlayer(); - - Bukkit.getScheduler().scheduleSyncDelayedTask( - Manager.getPlugin(), new Runnable() - { - public void run() - { - UtilPlayer - .sendPacket( - player, - blockForm - .getBlockPackets()); - } - }); - break; + UtilPlayer.sendPacket(player, blockForm.getBlockPackets(UtilPlayer.is1_9(player))); } - } + }); + + break; } } else if (packetInfo.getPacket() instanceof PacketPlayOutEntityDestroy) { - for (int i : ((PacketPlayOutEntityDestroy) packetInfo - .getPacket()).a) + for (int i : ((PacketPlayOutEntityDestroy) packetInfo.getPacket()).a) { for (Entry entry : _forms.entrySet()) { - if (entry.getValue() instanceof BlockForm) - { - BlockForm blockForm = (BlockForm) entry.getValue(); + if (!(entry.getValue() instanceof BlockForm)) + continue; - if (blockForm.Player.getEntityId() == i) + BlockForm blockForm = (BlockForm) entry.getValue(); + + if (blockForm.Player.getEntityId() != i) + continue; + + UtilPlayer.sendPacket(packetInfo.getPlayer(), new PacketPlayOutEntityDestroy(new int[] { - UtilPlayer.sendPacket(packetInfo.getPlayer(), - new PacketPlayOutEntityDestroy( - new int[] - { - blockForm.getBlockId() - })); - } - } + blockForm.getBlockId() + })); } } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/BlockForm.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/BlockForm.java index 0ebd75ca8..f0a2973f4 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/BlockForm.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/BlockForm.java @@ -1,5 +1,7 @@ package nautilus.game.arcade.game.games.hideseek.forms; +import java.util.UUID; + import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.MapUtil; @@ -15,10 +17,12 @@ import mineplex.core.recharge.Recharge; import nautilus.game.arcade.game.games.hideseek.HideSeek; import nautilus.game.arcade.game.games.hideseek.kits.KitHiderQuick; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.Entity; import net.minecraft.server.v1_8_R3.EntityPlayer; import net.minecraft.server.v1_8_R3.EntityTrackerEntry; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity; +import net.minecraft.server.v1_8_R3.PacketPlayOutNewAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntity.PacketPlayOutRelEntityMove; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityTeleport; @@ -50,8 +54,8 @@ public class BlockForm extends Form private int _entityId; private Location _loc; - private int _selfEntityId1; - private int _selfEntityId2; + private int _fakeSilverfishId; + private int _fakeBlockId; private Vector _lastSaw; private Vector _sawDiff = new Vector(); private int _blockId = UtilEnt.getNewEntityId(); @@ -62,29 +66,29 @@ public class BlockForm extends Form _mat = mat; _loc = player.getLocation(); - _selfEntityId1 = UtilEnt.getNewEntityId(); - _selfEntityId2 = UtilEnt.getNewEntityId(); + _fakeSilverfishId = UtilEnt.getNewEntityId(); + _fakeBlockId = UtilEnt.getNewEntityId(); System.out.println("Block Form: " + _mat + " " + _mat.getId()); } @Override - public void Apply() - { - // Remove Old - if (Player.getPassenger() != null) - { - Player.getPassenger().remove(); - Player.eject(); - } + public void Apply() + { + // Remove Old + if (Player.getPassenger() != null) + { + Player.getPassenger().remove(); + Player.eject(); + } - EntityPlayer player = ((CraftPlayer) Player).getHandle(); - player.getDataWatcher().watch(0, Byte.valueOf((byte) 32)); + EntityPlayer player = ((CraftPlayer) Player).getHandle(); + player.getDataWatcher().watch(0, Byte.valueOf((byte) 32), Entity.META_ENTITYDATA, (byte) 32); - // Player > Chicken - DisguiseChicken disguise = new DisguiseChicken(Player); - disguise.setBaby(); - - disguise.setInvisible(true); + // Player > Chicken + DisguiseChicken disguise = new DisguiseChicken(Player); + disguise.setBaby(); + + disguise.setInvisible(true); disguise.setSoundDisguise(new DisguiseCat(Player)); Host.Manager.GetDisguise().disguise(disguise); @@ -96,71 +100,95 @@ public class BlockForm extends Form Packet[] packets = new Packet[3]; PacketPlayOutSpawnEntityLiving packet1 = new PacketPlayOutSpawnEntityLiving(); - packet1.a = _selfEntityId1; + packet1.a = _fakeSilverfishId; packet1.b = EntityType.SILVERFISH.getTypeId(); packet1.c = (int) Math.floor(_lastSaw.getX() * 32); packet1.d = (int) Math.floor(_lastSaw.getY() * 32); packet1.e = (int) Math.floor(_lastSaw.getZ() * 32); DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); + watcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 32); + watcher.a(1, 0, Entity.META_AIR, 0); packet1.l = watcher; + packet1.uuid = UUID.randomUUID(); packets[0] = packet1; - PacketPlayOutAttachEntity packet3 = new PacketPlayOutAttachEntity(); + if (UtilPlayer.is1_9(Player)) + { + packets[2] = new PacketPlayOutNewAttachEntity(_fakeSilverfishId, new int[] + { + _fakeBlockId + }); - packet3.b = _selfEntityId2; - packet3.c = _selfEntityId1; - packets[2] = packet3; + } + else + { + PacketPlayOutAttachEntity packet3 = new PacketPlayOutAttachEntity(); - PacketPlayOutSpawnEntity packet2 = new PacketPlayOutSpawnEntity(player, - 70, _mat.getId()); - packet2.a = _selfEntityId2; + packet3.b = _fakeBlockId; + packet3.c = _fakeSilverfishId; + + packets[2] = packet3; + } + + PacketPlayOutSpawnEntity packet2 = new PacketPlayOutSpawnEntity(player, 70, _mat.getId()); + packet2.a = _fakeBlockId; + packet2.uuid = UUID.randomUUID(); packets[1] = packet2; UtilPlayer.sendPacket(Player, packets); // Inform String blockName = F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false)); - if (!blockName.contains("Block")) - UtilPlayer.message( - Player, - F.main("Game", - C.cWhite + "You are now a " - + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false) + " Block") + "!")); - else - UtilPlayer.message( - Player, - F.main("Game", C.cWhite + "You are now a " + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false)) - + "!")); + if (!blockName.contains("Block")) + UtilPlayer.message(Player, F.main("Game", C.cWhite + "You are now a " + + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false) + " Block") + "!")); + else + UtilPlayer.message(Player, F.main("Game", + C.cWhite + "You are now a " + F.elem(ItemStackFactory.Instance.GetName(_mat, (byte) 0, false)) + "!")); - // Give Item - Player.getInventory().setItem(8, new ItemStack(Host.GetItemEquivilent(_mat))); - UtilInv.Update(Player); + // Give Item + Player.getInventory().setItem(8, new ItemStack(Host.GetItemEquivilent(_mat))); + UtilInv.Update(Player); - // Sound - Player.playSound(Player.getLocation(), Sound.ZOMBIE_UNFECT, 2f, 2f); - } - - public Packet[] getBlockPackets() - { - PacketPlayOutSpawnEntity packet2 = new PacketPlayOutSpawnEntity(((CraftPlayer) Player).getHandle(), - 70, _mat.getId()); - packet2.a = _blockId; - - PacketPlayOutAttachEntity packet3 = new PacketPlayOutAttachEntity(); - - packet3.b = _blockId; - packet3.c = Player.getEntityId(); - - return new Packet[] {packet2, packet3}; + // Sound + Player.playSound(Player.getLocation(), Sound.ZOMBIE_UNFECT, 2f, 2f); } - + + public Packet[] getBlockPackets(boolean is19) + { + Packet[] packets = new Packet[2]; + + PacketPlayOutSpawnEntity packet2 = new PacketPlayOutSpawnEntity(((CraftPlayer) Player).getHandle(), 70, _mat.getId()); + packet2.a = _blockId; + packet2.uuid = UUID.randomUUID(); + + packets[0] = packet2; + + if (is19) + { + packets[1] = new PacketPlayOutNewAttachEntity(Player.getEntityId(), new int[] + { + _blockId + + }); + } + else + { + PacketPlayOutAttachEntity packet3 = new PacketPlayOutAttachEntity(); + + packet3.b = _blockId; + packet3.c = Player.getEntityId(); + packets[1] = packet3; + } + + return packets; + } + public int getBlockId() { return _blockId; } - + @Override public void Remove() { @@ -169,19 +197,20 @@ public class BlockForm extends Form Host.Manager.GetDisguise().undisguise(Player); UtilPlayer.sendPacket(Player, new PacketPlayOutEntityDestroy(new int[] - { - _selfEntityId1, _selfEntityId2, _blockId - })); + { + _fakeSilverfishId, + _fakeBlockId, + _blockId + })); - ((CraftEntity) Player).getHandle().getDataWatcher() - .watch(0, Byte.valueOf((byte) 0)); + ((CraftEntity) Player).getHandle().getDataWatcher().watch(0, (byte) 0, Entity.META_ENTITYDATA, (byte) 0); } public void SolidifyUpdate() { if (!Player.isSprinting()) - ((CraftEntity) Player).getHandle().getDataWatcher() - .watch(0, Byte.valueOf((byte) 32)); + ((CraftEntity) Player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 32), Entity.META_ENTITYDATA, + (byte) 32); // Not a Block if (_block == null) @@ -199,8 +228,7 @@ public class BlockForm extends Form if (Host.GetKit(Player) instanceof KitHiderQuick) hideBoost = 0.1; - Player.setExp((float) Math.min(0.999f, Player.getExp() - + hideBoost)); + Player.setExp((float) Math.min(0.999f, Player.getExp() + hideBoost)); // Set Block if (Player.getExp() >= 0.999f) @@ -208,25 +236,20 @@ public class BlockForm extends Form Block block = Player.getLocation().getBlock(); // Not Able - if (block.getType() != Material.AIR - || !UtilBlock.solid(block - .getRelative(BlockFace.DOWN))) + if (block.getType() != Material.AIR || !UtilBlock.solid(block.getRelative(BlockFace.DOWN))) { - UtilPlayer.message(Player, F.main("Game", - "You cannot become a Solid Block here.")); + UtilPlayer.message(Player, F.main("Game", "You cannot become a Solid Block here.")); Player.setExp(0f); return; } - Bukkit.getPluginManager().callEvent( - new HideSeek.PlayerSolidifyEvent(Player)); + Bukkit.getPluginManager().callEvent(new HideSeek.PlayerSolidifyEvent(Player)); // Set Block _block = block; // Effect - Player.playEffect(Player.getLocation(), Effect.STEP_SOUND, - _mat); + Player.playEffect(Player.getLocation(), Effect.STEP_SOUND, _mat); // block.getWorld().playEffect(block.getLocation(), // Effect.STEP_SOUND, _mat); @@ -238,39 +261,34 @@ public class BlockForm extends Form // Player, Player, 60000, false, false); // Sound - Player.playSound(Player.getLocation(), Sound.NOTE_PLING, - 1f, 2f); + Player.playSound(Player.getLocation(), Sound.NOTE_PLING, 1f, 2f); // Teleport falling block to the position. - Vector blockLoc = _block.getLocation() - .add(0.5, -.21875, 0.5).toVector(); + Vector blockLoc = _block.getLocation().add(0.5, -.21875, 0.5).toVector(); _sawDiff.add(blockLoc.clone().subtract(_lastSaw)); - Packet packet = this.getPacket(_sawDiff, blockLoc); + Packet[] packet = this.getPacket(_sawDiff, blockLoc); - _lastSaw = Player.getLocation().toVector() - .subtract(new Vector(0, 0.15625, 0)); + _lastSaw = Player.getLocation().toVector().subtract(new Vector(0, 0.15625, 0)); _sawDiff = _lastSaw.clone().subtract(blockLoc); if (packet != null) { - if (packet instanceof PacketPlayOutEntityTeleport) + if (packet[0] instanceof PacketPlayOutEntityTeleport) { _sawDiff = new Vector(); } - ((CraftPlayer) Player).getHandle().playerConnection - .sendPacket(packet); + UtilPlayer.sendPacket(Player, packet[UtilPlayer.is1_9(Player) ? 1 : 0]); } for (Player player : UtilServer.getPlayers()) { - UtilPlayer.sendPacket(player, - new PacketPlayOutEntityDestroy(new int[] - { + UtilPlayer.sendPacket(player, new PacketPlayOutEntityDestroy(new int[] + { getBlockId() - })); + })); } } } @@ -299,15 +317,13 @@ public class BlockForm extends Form _block = null; EntityTrackerEntry tracker = (EntityTrackerEntry) ((WorldServer) ((CraftEntity) Player) - .getHandle().world).tracker.trackedEntities.get(Player - .getEntityId()); + .getHandle().world).tracker.trackedEntities.get(Player.getEntityId()); if (tracker != null) { for (EntityPlayer entity : tracker.trackedPlayers) { - UtilPlayer.sendPacket(entity.getBukkitEntity(), - getBlockPackets()); + UtilPlayer.sendPacket(entity.getBukkitEntity(), getBlockPackets(UtilPlayer.is1_9(entity.getBukkitEntity()))); } } } @@ -348,35 +364,31 @@ public class BlockForm extends Form if (_lastSaw != null) { - this._sawDiff.add(Player.getLocation() - .subtract(0, 0.15625, 0).toVector() - .subtract(_lastSaw)); + this._sawDiff.add(Player.getLocation().subtract(0, 0.15625, 0).toVector().subtract(_lastSaw)); } - _lastSaw = Player.getLocation().subtract(0, 0.15625, 0) - .toVector(); + _lastSaw = Player.getLocation().subtract(0, 0.15625, 0).toVector(); - Packet packet = this.getPacket(_sawDiff, _lastSaw); + Packet[] packet = this.getPacket(_sawDiff, _lastSaw); if (packet != null) { - if (packet instanceof PacketPlayOutRelEntityMove) + if (!UtilPlayer.is1_9(Player) && packet[0] instanceof PacketPlayOutRelEntityMove) { - PacketPlayOutRelEntityMove relPacket = (PacketPlayOutRelEntityMove) packet; - _sawDiff.subtract(new Vector(relPacket.b / 32D, - relPacket.c / 32D, relPacket.d / 32D)); + PacketPlayOutRelEntityMove relPacket = (PacketPlayOutRelEntityMove) packet[0]; + _sawDiff.subtract(new Vector(relPacket.b / 32D, relPacket.c / 32D, relPacket.d / 32D)); } else { _sawDiff = new Vector(); } - UtilPlayer.sendPacket(Player, packet); + UtilPlayer.sendPacket(Player, packet[UtilPlayer.is1_9(Player) ? 1 : 0]); } } } - private Packet getPacket(Vector blocksFromNewPosition, Vector newPosition) + private Packet[] getPacket(Vector blocksFromNewPosition, Vector newPosition) { int x = (int) Math.floor(blocksFromNewPosition.getX() * 32); int y = (int) Math.floor(blocksFromNewPosition.getY() * 32); @@ -384,27 +396,33 @@ public class BlockForm extends Form if (x != 0 || y != 0 || z != 0) { - if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 - && z <= 127) + Packet[] packets = new Packet[2]; + + if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) { PacketPlayOutRelEntityMove relMove = new PacketPlayOutRelEntityMove(); - relMove.a = this._selfEntityId1; + relMove.a = this._fakeSilverfishId; relMove.b = (byte) x; relMove.c = (byte) y; relMove.d = (byte) z; - return relMove; + packets[0] = relMove; } - else + { PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport(); - teleportPacket.a = _selfEntityId1; + teleportPacket.a = _fakeSilverfishId; teleportPacket.b = (int) Math.floor(32 * newPosition.getX()); teleportPacket.c = (int) Math.floor(32 * newPosition.getY()); teleportPacket.d = (int) Math.floor(32 * newPosition.getZ()); - return teleportPacket; + if (packets[0] == null) + packets[0] = teleportPacket; + + packets[1] = teleportPacket; } + + return packets; } return null; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/CreatureForm.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/CreatureForm.java index 3577f78c9..22db07638 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/CreatureForm.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/hideseek/forms/CreatureForm.java @@ -7,6 +7,7 @@ import mineplex.core.common.util.UtilInv; import mineplex.core.common.util.UtilPlayer; import mineplex.core.disguise.disguises.*; import nautilus.game.arcade.game.games.hideseek.HideSeek; +import net.minecraft.server.v1_8_R3.Entity; import org.bukkit.Material; import org.bukkit.Sound; @@ -43,7 +44,7 @@ public class CreatureForm extends Form _disguise.setSoundDisguise(new DisguiseCat(Player)); Host.Manager.GetDisguise().disguise(_disguise); - ((CraftEntity)Player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0)); + ((CraftEntity)Player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0), Entity.META_ENTITYDATA, (byte) 0); //Inform UtilPlayer.message(Player, F.main("Game", C.cWhite + "You are now a " + F.elem(UtilEnt.getName(_type)) + "!")); @@ -61,6 +62,6 @@ public class CreatureForm extends Form { Host.Manager.GetDisguise().undisguise(Player); - ((CraftEntity)Player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0)); + ((CraftEntity)Player).getHandle().getDataWatcher().watch(0, Byte.valueOf((byte) 0), Entity.META_ENTITYDATA, (byte) 0); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/holeinwall/Wall.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/holeinwall/Wall.java index 2c0184e88..6b03c9e3e 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/holeinwall/Wall.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/holeinwall/Wall.java @@ -11,11 +11,13 @@ import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import net.minecraft.server.v1_8_R3.DataWatcher; +import net.minecraft.server.v1_8_R3.Entity; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutEntity.PacketPlayOutRelEntityMove; import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy; +import net.minecraft.server.v1_8_R3.PacketPlayOutNewAttachEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntity; import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving; @@ -210,9 +212,10 @@ public class Wall packet1.d = (int) Math.floor((entry.getKey().getY() - 0.15625) * 32); packet1.e = (int) Math.floor(entry.getKey().getZ() * 32); DataWatcher watcher = new DataWatcher(null); - watcher.a(0, (byte) 32); - watcher.a(1, 0); + watcher.a(0, (byte) 32, Entity.META_ENTITYDATA, (byte) 32); + watcher.a(1, 0, Entity.META_AIR, 0); packet1.l = watcher; + packet1.uuid = UUID.randomUUID(); PacketPlayOutSpawnEntity packet2 = new PacketPlayOutSpawnEntity(((CraftPlayer) player).getHandle(), 70, Material.STAINED_GLASS.getId() | ids.data << 16); @@ -220,11 +223,26 @@ public class Wall packet2.b = (int) Math.floor(entry.getKey().getX() * 32); packet2.c = (int) Math.floor(entry.getKey().getY() * 32); packet2.d = (int) Math.floor(entry.getKey().getZ() * 32); + packet2.uuid = UUID.randomUUID(); - PacketPlayOutAttachEntity packet3 = new PacketPlayOutAttachEntity(); + Packet packet3; - packet3.b = ids.block; - packet3.c = ids.chicken; + if (UtilPlayer.is1_9(player)) + { + packet3 = new PacketPlayOutNewAttachEntity( ids.chicken, new int[] + { + ids.block + }); + } + else + { + PacketPlayOutAttachEntity packet = new PacketPlayOutAttachEntity(); + + packet.b = ids.block; + packet.c = ids.chicken; + + packet3 = packet; + } packets[i++] = packet1; packets[i++] = packet2; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/DataLoc.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/DataLoc.java new file mode 100644 index 000000000..8ca22140e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/DataLoc.java @@ -0,0 +1,42 @@ +package nautilus.game.arcade.game.games.minecraftleague; + +public enum DataLoc +{ + //Base + RED_CRYSTAL(" RED CRYSTAL"), + RED_TOWER(" RED TOWER"), + BLUE_CRYSTAL(" BLUE CRYSTAL"), + BLUE_TOWER(" BLUE TOWER"), + VARIANT_BASE("GAMEMODE "), + //RED_BEACON("PINK"), + /*BLUE_*/BEACON("CYAN"), + SKELETON_SPAWNER("BROWN"), + //MAP_DIAMOND("LIGHT_BLUE"), + //MAP_IRON("SILVER"), + RED_ORE("15"), + BLUE_ORE("14"), + DIAMOND_ORE("56"), + COAL_ORE("16"), + MOSH_IRON("129"), + GRIND_AREA(" GRIND"), + + //Wither + WITHER_WAYPOINT("PURPLE"), + TOWER_WAYPOINT(" $team$ WITHER $number$"), + WITHER_SKELETON("BLACK"), + BLUE_ALTAR("LIME"), + RED_ALTAR("YELLOW") + ; + + private String _key; + + private DataLoc(String key) + { + _key = key; + } + + public String getKey() + { + return _key; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/MinecraftLeague.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/MinecraftLeague.java new file mode 100644 index 000000000..9c2f29fd0 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/MinecraftLeague.java @@ -0,0 +1,1984 @@ +package nautilus.game.arcade.game.games.minecraftleague; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.Rank; +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.message.PrivateMessageEvent; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import mineplex.minecraft.game.core.combat.DeathMessageType; +import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.GameType; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.events.PlayerDeathOutEvent; +import nautilus.game.arcade.events.PlayerGameRespawnEvent; +import nautilus.game.arcade.events.PlayerPrepareTeleportEvent; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.TeamGame; +import nautilus.game.arcade.game.games.minecraftleague.commands.MinecraftLeagueCommand; +import nautilus.game.arcade.game.games.minecraftleague.commands.freeze.FreezeManager; +import nautilus.game.arcade.game.games.minecraftleague.data.BlockProtection; +import nautilus.game.arcade.game.games.minecraftleague.data.MapZone; +import nautilus.game.arcade.game.games.minecraftleague.data.Spawner; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamBeacon; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamCrystal; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamTowerBase; +import nautilus.game.arcade.game.games.minecraftleague.data.TowerAlert; +import nautilus.game.arcade.game.games.minecraftleague.data.TowerManager; +import nautilus.game.arcade.game.games.minecraftleague.data.map.ItemMapManager; +import nautilus.game.arcade.game.games.minecraftleague.kit.KitPlayer; +import nautilus.game.arcade.game.games.minecraftleague.tracker.AltarBuilderTracker; +import nautilus.game.arcade.game.games.minecraftleague.tracker.FirstStrikeTracker; +import nautilus.game.arcade.game.games.minecraftleague.tracker.HeadHunterTracker; +import nautilus.game.arcade.game.games.minecraftleague.tracker.SavingUpTracker; +import nautilus.game.arcade.game.games.minecraftleague.tracker.TowerDefenderTracker; +import nautilus.game.arcade.game.games.minecraftleague.variation.ExtraScoreboardData; +import nautilus.game.arcade.game.games.minecraftleague.variation.GameVariation; +import nautilus.game.arcade.game.games.minecraftleague.variation.VariationManager; +import nautilus.game.arcade.kit.Kit; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Furnace; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Enderman; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceSmeltEvent; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.inventory.PrepareItemCraftEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.material.Dispenser; +import org.bukkit.material.MaterialData; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import com.google.common.base.Objects; + +public class MinecraftLeague extends TeamGame +{ + //private ConcurrentHashMap _customRespawns = new ConcurrentHashMap(); + //private ConcurrentHashMap _maps = new ConcurrentHashMap(); + private ConcurrentHashMap> _gear = new ConcurrentHashMap>(); + public ConcurrentHashMap Beacons = new ConcurrentHashMap(); + //public ConcurrentHashMap TeamPoison = new ConcurrentHashMap(); + private ConcurrentHashMap _blockLock = new ConcurrentHashMap(); + //private ConcurrentHashMap _spawnAllow = new ConcurrentHashMap(); + private List _spawners = new ArrayList(); + private List _noFall = new ArrayList(); + + private static final String[] PERM_OP = new String[] {"SamitoD", "Relyh", "AlexTheCoder"}; + + public ConcurrentHashMap ExtraSb = new ConcurrentHashMap(); + + private long _liveTime = 0; + private MinecraftLeagueCommand _cmd; + private long _lastIncrease; + private long _lastOreReset; + private long _lastGrindReset; + private boolean _yellow = false; + + public List MapZones = new ArrayList(); + public ItemMapManager MapManager; + public boolean OverTime = false; + + private VariationManager _vman; + //public ObjectiveManager Objective; + private FreezeManager _freeze; + private TowerManager _tower; + public TowerAlert Alert; + public boolean ScoreboardAutoWrite = true; + + //private final EntityType[] _passive = new EntityType[] {EntityType.CHICKEN, EntityType.COW, EntityType.PIG, EntityType.RABBIT, EntityType.SHEEP}; + + public MinecraftLeague(ArcadeManager manager) + { + super(manager, GameType.MinecraftLeague, + + new Kit[] + { + new KitPlayer(manager) + }, + + new String[] + { + C.cWhite + "Gather resources for battle.", + C.cWhite + "Destroy all of the enemy's Towers to", + C.cWhite + "Defeat them and win the game!", + " ", + C.cWhite + "Last team with Towers alive wins", + }); + + this.EloRanking = true; + this.DeathOut = true; + this.DamageSelf = false; + this.DeathSpectateSecs = 10; + this.WorldBoundaryKill = true; + this.DeathDropItems = true; + this.CreatureAllow = false; + this.HungerSet = 20; + + this.BlockBreak = true; + this.BlockPlace = true; + this.ItemPickup = true; + this.ItemDrop = true; + + this.InventoryClick = true; + this.InventoryOpenBlock = true; + this.InventoryOpenChest = true; + + this.WorldWeatherEnabled = true; + this.WorldBlockBurn = true; + this.WorldBlockGrow = true; + this.WorldBoneMeal = true; + this.WorldFireSpread = true; + this.WorldLeavesDecay = true; + this.WorldSoilTrample = true; + + this.StrictAntiHack = true; + this.AllowParticles = false; + this.SoupEnabled = false; + this.GameTimeout = -1; + + _help = new String[] + { + "Towers have 150 health per person in-game!", + "The better the sword you have, the more damage you deal to Towers!", + //"Right-click a bed in order to change your personal spawn location!", + "Your map will display the locations of your enemies in OverTime!" + }; + + + registerStatTrackers( + new AltarBuilderTracker(this), + new FirstStrikeTracker(this), + new HeadHunterTracker(this), + new TowerDefenderTracker(this, 2, 8000, "TowerDefender"), + new SavingUpTracker(this) + ); + + _vman = new VariationManager(this); + //Objective = new ObjectiveManager(this); + _freeze = new FreezeManager(); + _tower = new TowerManager(this); + Alert = new TowerAlert(); + Bukkit.getPluginManager().registerEvents(_freeze, manager.getPlugin()); + } + + private enum DamageAmount + { + NONE(1), + WOOD(4), + STONE(5), + GOLD(4), + IRON(6), + DIAMOND(7); + + private double _amount; + + private DamageAmount(int amount) + { + _amount = amount; + } + + public double getDamage(int sharpnessLevel, DamageType type) + { + if (type.getDamageReduction() == null) + return 1; + + return _amount + (sharpnessLevel / 2) - type.getDamageReduction(); + } + + public static DamageAmount getDamageAmount(Material material) + { + for (DamageAmount da : DamageAmount.values()) + { + if (da == DamageAmount.NONE) + continue; + + if (material.toString().contains(da.toString() + "_")) + return da; + } + + return DamageAmount.NONE; + } + } + + private enum DamageType + { + NONE(null), + PICKAXE(2), + AXE(1), + SWORD(0), + SPADE(3); + + private Integer _reduction; + + private DamageType(Integer reduction) + { + _reduction = reduction; + } + + public Integer getDamageReduction() + { + return _reduction; + } + + public static DamageType getDamageType(Material material) + { + for (DamageType dt : DamageType.values()) + { + if (dt == DamageType.NONE) + continue; + + if (material.toString().contains("_" + dt.toString())) + return dt; + } + + return DamageType.NONE; + } + } + + private ItemStack getNewItemStack(ItemStack item) + { + ItemStack ret = item.clone(); + /*String type = ret.getType().toString(); + boolean damage = false; + boolean itemD = false; + if (type.contains("HELMET") || type.contains("CHESTPLATE") || type.contains("LEGGINGS") || type.contains("BOOTS")) + damage = true; + if (DamageType.getDamageType(ret.getType()) != DamageType.NONE) + itemD = true; + + if (damage) + { + ret.setDurability((short) (ret.getDurability() + (ret.getDurability() * .25))); + } + if (itemD) + { + ret.setDurability((short) (ret.getDurability() + 25)); + } + + if (ret.getDurability() > ret.getType().getMaxDurability()) + ret = new ItemStack(Material.AIR);*/ + + if (ret.getType() == Material.MAP) + ret = new ItemStack(Material.AIR); + if (UtilItem.isTool(ret)) + ret = new ItemStack(ret.getType()); + + return ret; + } + + private int getSwordLevel(ItemStack sword) + { + if (UtilItem.isSword(sword)) + { + //if (UtilItem.isDiamondProduct(sword)) + //return 5; + if (UtilItem.isIronProduct(sword)) + return 4; + if (UtilItem.isGoldProduct(sword)) + return 3; + if (UtilItem.isStoneProduct(sword)) + return 2; + if (UtilItem.isWoodProduct(sword)) + return 1; + } + + return 0; + } + + private int getPickLevel(ItemStack sword) + { + if (UtilItem.isPickaxe(sword)) + { + //if (UtilItem.isDiamondProduct(sword)) + //return 5; + if (UtilItem.isIronProduct(sword)) + return 4; + if (UtilItem.isGoldProduct(sword)) + return 3; + if (UtilItem.isStoneProduct(sword)) + return 2; + if (UtilItem.isWoodProduct(sword)) + return 1; + } + + return 0; + } + + private ItemStack getBestSword(Player player) + { + ItemStack ret = new ItemStack(Material.AIR); + int level = 0; + + for (ItemStack item : UtilInv.getItems(player, false, true, false)) + { + if (UtilItem.isSword(item)) + { + if (getSwordLevel(item) > level) + { + ret = item; + level = getSwordLevel(item); + } + } + } + + return ret; + } + + private ItemStack getBestPick(Player player) + { + ItemStack ret = new ItemStack(Material.AIR); + int level = 0; + + for (ItemStack item : UtilInv.getItems(player, false, true, false)) + { + if (UtilItem.isPickaxe(item)) + { + if (getPickLevel(item) > level) + { + ret = item; + level = getPickLevel(item); + } + } + } + + return ret; + } + + public List getMapVariantIDS() + { + List ids = new ArrayList(); + for (String s : WorldData.GetAllCustomLocs().keySet()) + { + if (s.contains(DataLoc.VARIANT_BASE.getKey())) + ids.add(s); + } + return ids; + } + + public TeamTowerBase getActiveTower(GameTeam team) + { + return _tower.getVulnerable(team); + } + + public TowerManager getTowerManager() + { + return _tower; + } + + public FreezeManager getFreezeManager() + { + return _freeze; + } + + /*public TeamMap getMap(GameTeam team) + { + return _maps.get(team); + }*/ + + @Override + public void ParseData() + { + _tower.parseTowers(WorldData); + + //_beacons.put(GetTeam(ChatColor.RED), new TeamBeacon(GetTeam(ChatColor.RED), WorldData.GetDataLocs(DataLoc.RED_BEACON.getKey()).get(0).getBlock(), redLoc)); + //_beacons.put(GetTeam(ChatColor.AQUA), new TeamBeacon(GetTeam(ChatColor.AQUA), WorldData.GetDataLocs(DataLoc.BLUE_BEACON.getKey()).get(0).getBlock(), blueLoc)); + + for (Location loc : WorldData.GetDataLocs(DataLoc.SKELETON_SPAWNER.getKey())) + { + _spawners.add(new Spawner(this, loc, EntityType.SKELETON)); + } + + /*for (Location loc : WorldData.GetDataLocs(DataLoc.MAP_DIAMOND.getKey())) + { + Ore.add(new OreDeposit(loc, Material.DIAMOND_ORE, new int[] {0, 255, 255})); + } + for (Location loc : WorldData.GetDataLocs(DataLoc.MAP_IRON.getKey())) + { + Ore.add(new OreDeposit(loc, Material.IRON_ORE, new int[] {190, 190, 190})); + }*/ + + for (Location diamond : WorldData.GetCustomLocs(DataLoc.DIAMOND_ORE.getKey())) + { + diamond.getBlock().setType(Material.DIAMOND_ORE); + } + for (Location coal : WorldData.GetCustomLocs(DataLoc.COAL_ORE.getKey())) + { + coal.getBlock().setType(Material.COAL_ORE); + } + + MapManager = new ItemMapManager(this, WorldData.World, WorldData.MinX, WorldData.MinZ, WorldData.MaxX, WorldData.MaxZ); + + _vman.selectVariation(); + } + + @Override + @EventHandler + public void ScoreboardUpdate(UpdateEvent event) + { + if (!ScoreboardAutoWrite) + return; + + if (event.getType() == UpdateType.FAST || event.getType() == UpdateType.SEC) + scoreboardWrite(event.getType() == UpdateType.SEC); + } + + public void writeEndSb(String winner) + { + Scoreboard.Reset(); + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cDRedB + GetName()); + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cGoldB + "Winner:"); + Scoreboard.Write(winner); + + Scoreboard.Draw(); + } + + private void scoreboardWrite(boolean sec) + { + if (!InProgress()) + return; + + if (!IsLive()) + { + if (!sec) + return; + Scoreboard.Reset(); + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cDRedB + GetName()); + Scoreboard.WriteBlank(); + + if (_yellow) + { + Scoreboard.Write(C.cYellow + "Loading..."); + _yellow = false; + } + else + { + Scoreboard.Write("Loading..."); + _yellow = true; + } + + Scoreboard.Draw(); + return; + } + + if (sec) + return; + + GameTeam red = GetTeam(ChatColor.RED); + GameTeam blue = GetTeam(ChatColor.AQUA); + String reds = ""; + String blues = ""; + for (TeamTowerBase tb : _tower.getTeamTowers(red)) + { + if (!reds.equalsIgnoreCase("")) + reds = reds + " "; + + String symbol = "♛"; + if (tb instanceof TeamCrystal) + symbol = "♚"; + + reds = reds + tb.getHealthColor() + symbol; + } + for (TeamTowerBase tb : _tower.getTeamTowers(blue)) + { + if (!blues.equalsIgnoreCase("")) + blues = blues + " "; + + String symbol = "♛"; + if (tb instanceof TeamCrystal) + symbol = "♚"; + + blues = blues + tb.getHealthColor() + symbol; + } + + _liveTime = Math.max(System.currentTimeMillis() - GetStateTime(), 0); + + Scoreboard.Reset(); + + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cRedB + "Red Team"); + Scoreboard.Write("Towers: " + reds); + for (String s : _vman.getSelected().getTeamScoreboardAdditions(red)) + { + Scoreboard.Write(s); + } + + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cAquaB + "Blue Team"); + Scoreboard.Write("Towers: " + blues); + for (String s : _vman.getSelected().getTeamScoreboardAdditions(blue)) + { + Scoreboard.Write(s); + } + + int i = 1; + for (ExtraScoreboardData sbD : ExtraSb.keySet()) + { + Scoreboard.WriteBlank(); + sbD.write(); + if (i < ExtraSb.size()) + Scoreboard.WriteBlank(); + i++; + } + + Scoreboard.WriteBlank(); + Scoreboard.Write(C.cYellowB + "Time Elapsed"); + Scoreboard.Write(UtilTime.MakeStr(_liveTime)); + if (OverTime) + Scoreboard.Write(C.cDRedB + "Overtime"); + + Scoreboard.Draw(); + } + + /*@Override + public void RespawnPlayerTeleport(Player player) + { + if (_customRespawns.containsKey(player)) + { + PlayerRespawnPoint point = _customRespawns.get(player); + if (point.respawnPlayer()) + return; + + _customRespawns.remove(player); + } + + player.teleport(GetTeam(player).GetSpawn()); + }*/ + + public boolean handleCommand(Player caller) + { + for (GameTeam team : GetTeamList()) + { + TeamTowerBase tower = _tower.getTeamTowers(team).getLast(); + UtilPlayer.message(caller, team.GetColor() + team.GetName()); + UtilPlayer.message(caller, C.cGray + "Health: " + tower.getHealth()); + UtilPlayer.message(caller, C.cGray + "Alive: " + tower.Alive); + } + + return true; + } + + public void restoreGear(Player player) + { + if (!_gear.containsKey(player)) + return; + List items = _gear.get(player); + for (int i = 0; i < 4; i++) + { + ItemStack item; + if (items.get(i) != null) + item = items.get(i); + else + item = new ItemStack(Material.AIR); + + switch(i + 1) + { + case 1: + player.getInventory().setHelmet(getNewItemStack(item)); + break; + case 2: + player.getInventory().setChestplate(getNewItemStack(item)); + break; + case 3: + player.getInventory().setLeggings(getNewItemStack(item)); + break; + case 4: + player.getInventory().setBoots(getNewItemStack(item)); + break; + } + } + for (int i = 4; i < items.size(); i++) + { + if (items.get(i) == null) + UtilInv.insert(player, new ItemStack(Material.AIR)); + else + UtilInv.insert(player, getNewItemStack(items.get(i))); + } + _gear.remove(player); + } + + @EventHandler + public void onEditSettings(GameStateChangeEvent event) + { + if (event.GetGame() != this) + return; + + if (event.GetState() == GameState.Live) + { + _lastIncrease = System.currentTimeMillis(); + _lastOreReset = System.currentTimeMillis(); + _lastGrindReset = System.currentTimeMillis() - UtilTime.convert(30, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); + Manager.GetExplosion().setEnabled(false); + Manager.GetExplosion().SetTemporaryDebris(false); + Manager.GetExplosion().SetDebris(true); + Manager.GetDamage().SetEnabled(false); + Manager.GetCreature().SetForce(false); + Manager.GetCreature().SetDisableCustomDrops(true); + _cmd = new MinecraftLeagueCommand(Manager, this); + Manager.addCommand(_cmd); + Manager.getGameChatManager().TeamSpy = false; + //Objective.setMainObjective(new GearObjective()); + } + + if (event.GetState() == GameState.End) + { + Manager.GetExplosion().setEnabled(true); + Manager.GetExplosion().SetDebris(false); + Manager.GetExplosion().SetTemporaryDebris(true); + Manager.GetDamage().SetEnabled(true); + Manager.GetCreature().SetForce(false); + Manager.GetCreature().SetDisableCustomDrops(false); + Manager.removeCommand(_cmd); + Manager.getGameChatManager().TeamSpy = true; + HandlerList.unregisterAll(MapManager); + HandlerList.unregisterAll(_freeze); + } + } + + @EventHandler + public void onUpdate(UpdateEvent event) + { + if (!IsLive()) + return; + + if (event.getType() == UpdateType.SEC) + { + /*for (MapZone od : Ore) + { + od.update(); + }*/ + + for (Player player : GetTeam(ChatColor.RED).GetPlayers(true)) + { + for (ItemStack armor : player.getInventory().getArmorContents()) + { + if (UtilItem.isLeatherProduct(armor)) + { + LeatherArmorMeta im = (LeatherArmorMeta)armor.getItemMeta(); + im.setColor(Color.RED); + armor.setItemMeta(im); + } + } + } + for (Player player : GetTeam(ChatColor.AQUA).GetPlayers(true)) + { + for (ItemStack armor : player.getInventory().getArmorContents()) + { + if (UtilItem.isLeatherProduct(armor)) + { + LeatherArmorMeta im = (LeatherArmorMeta)armor.getItemMeta(); + im.setColor(Color.BLUE); + armor.setItemMeta(im); + } + } + } + } + + /*if (event.getType() == UpdateType.FASTER) + { + for (GameTeam team : _teamList) + { + for (Location loc : team.GetSpawns()) + { + for (LivingEntity near : UtilEnt.getInRadius(loc, 2).keySet()) + { + if (!(near instanceof Player)) + continue; + Player player = (Player)near; + if (team.HasPlayer(player)) + { + if (_spawnAllow.containsKey(player)) + continue; + } + if (UtilPlayer.isSpectator(player)) + continue; + + Vector vec = UtilAlg.getTrajectory(loc, player.getLocation()); + + Location tpLoc = loc.add(vec.clone().multiply(8)); + tpLoc.setDirection(player.getLocation().getDirection()); + + //First tp out this combats hacked clients with anti-KB + player.teleport(tpLoc); + + //Then apply velocity as normal + UtilAction.velocity(player, vec, 1.8, false, 0, 0.4, vec.length(), false); + + player.playSound(player.getEyeLocation(), Sound.NOTE_PLING, 10F, 0.5F); + } + } + } + }*/ + + if (event.getType() == UpdateType.FASTEST) + { + _tower.update(); + + /*for (TeamMap map : _maps.values()) + { + map.update(null); + }*/ + + for (Spawner spawner : _spawners) + { + spawner.update(); + } + + for (TeamBeacon beacon : Beacons.values()) + { + beacon.update(); + } + + //Alert.update(); + + /*for (GameTeam dmg : TeamPoison.keySet()) + { + if (UtilTime.elapsed(TeamPoison.get(dmg), UtilTime.convert(1, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + TeamPoison.put(dmg, System.currentTimeMillis()); + for (Player player : dmg.GetPlayers(true)) + { + this.storeGear(player); + player.damage(1); + } + } + }*/ + + if (UtilTime.elapsed(_lastOreReset, UtilTime.convert(5, TimeUnit.MINUTES, TimeUnit.MILLISECONDS))) + { + _lastOreReset = System.currentTimeMillis(); + for (Location loc : WorldData.GetCustomLocs(DataLoc.COAL_ORE.getKey())) + { + loc.getBlock().setType(Material.COAL_ORE); + } + } + + if (!OverTime) + { + if (UtilTime.elapsed(GetStateTime(), UtilTime.convert(15, TimeUnit.MINUTES, TimeUnit.MILLISECONDS))) + { + OverTime = true; + UtilTextMiddle.display(C.cGold + "Overtime", C.cGold + "Dying will now cause your crystal to lose 50 health!"); + } + } + + if (UtilTime.elapsed(_lastIncrease, UtilTime.convert(5, TimeUnit.MINUTES, TimeUnit.MILLISECONDS))) + { + _lastIncrease = System.currentTimeMillis(); + this.DeathSpectateSecs = Math.min(20, this.DeathSpectateSecs + 2.5); + } + + if (UtilTime.elapsed(_lastGrindReset, UtilTime.convert(30, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _lastGrindReset = System.currentTimeMillis(); + for (Location grind : WorldData.GetCustomLocs(DataLoc.GRIND_AREA.getKey())) + { + int spider = 0; + int chicken = 0; + for (LivingEntity le : UtilEnt.getInRadius(grind, 15).keySet()) + { + if (le.getType() == EntityType.SPIDER) + spider++; + if (le.getType() == EntityType.CHICKEN) + chicken++; + } + while (spider < 5) + { + spider = 5; + CreatureAllowOverride = true; + Manager.GetCreature().SpawnEntity(grind, EntityType.SPIDER); + CreatureAllowOverride = false; + } + while (chicken < 10) + { + chicken = 10; + CreatureAllowOverride = true; + Manager.GetCreature().SpawnEntity(grind, EntityType.CHICKEN); + CreatureAllowOverride = false; + } + } + } + + /*for (Player player : _spawnAllow.keySet()) + { + if (UtilTime.elapsed(_spawnAllow.get(player), UtilTime.convert(30, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _spawnAllow.remove(player); + } + }*/ + + for (Player player : _blockLock.keySet()) + { + if (!player.isOnline()) + _blockLock.remove(player); + } + + for (Player player : Bukkit.getOnlinePlayers()) + { + if (UtilPlayer.isSpectator(player)) + { + player.setFireTicks(-1); + player.setFoodLevel(20); + } + if (UtilInv.contains(player, Material.LAVA_BUCKET, (byte) 0, 1)) + { + UtilInv.insert(player, new ItemStack(Material.BUCKET, UtilInv.removeAll(player, Material.LAVA_BUCKET, (byte) 0))); + } + if (player.getOpenInventory().getType() == InventoryType.BEACON) + player.closeInventory(); + if (player.getFireTicks() > 20 * 4) + player.setFireTicks(20 * 4); + } + } + } + + @EventHandler + public void towerDmg(EntityDamageEvent event) + { + if (!InProgress()) + return; + + if (event.getEntity().getType() != EntityType.ENDER_CRYSTAL) + return; + + for (GameTeam team : GetTeamList()) + for (TeamTowerBase tower : _tower.getTeamTowers(team)) + { + if (tower.isEntity(event.getEntity())) + event.setCancelled(true); + } + } + + @EventHandler + public void towerDmg(EntityDamageByEntityEvent event) + { + if (!IsLive()) + return; + + if (event.getEntity().getType() != EntityType.ENDER_CRYSTAL) + return; + + TeamTowerBase tower = null; + for (GameTeam team : GetTeamList()) + for (TeamTowerBase tow : _tower.getTeamTowers(team)) + { + if (tow == null) + continue; + if (tow.isEntity(event.getEntity())) + tower = tow; + } + + if (tower == null) + return; + + event.setCancelled(true); + + Player player; + + if (event.getDamager() instanceof Projectile) + { + if (((Projectile)event.getDamager()).getShooter() instanceof Player) + { + if (event.getDamager() instanceof Arrow) + { + player = (Player) ((Projectile)event.getDamager()).getShooter(); + + if (!tower.canDamage(player)) + return; + + if (!tower.Vulnerable) + { + UtilPlayer.message(player, F.main("Game", "That Tower is protected by the power of another!")); + return; + } + + if (!tower.damage(event.getDamage() / 2, player)) + { + player.playSound(tower.getLocation(), Sound.ORB_PICKUP, 100, 0); + Alert.alert(tower.getTeam(), tower); + } + } + } + } + + if (event.getDamager() instanceof Player) + { + player = (Player)event.getDamager(); + if (!tower.canDamage(player)) + return; + + if (!tower.Vulnerable) + { + UtilPlayer.message(player, F.main("Game", "That Tower is protected by the power of another!")); + return; + } + + if (player.getItemInHand() == null || player.getItemInHand().getType() == Material.AIR) + { + if (!tower.damage(1, player)) + { + player.getWorld().playSound(tower.getLocation(), Sound.ZOMBIE_METAL, 1, 1.5f); + Alert.alert(tower.getTeam(), tower); + } + return; + } + + Material type = player.getItemInHand().getType(); + int level = player.getItemInHand().getEnchantmentLevel(Enchantment.DAMAGE_ALL); + double damage = DamageAmount.getDamageAmount(type).getDamage(level, DamageType.getDamageType(type)); + + if (!tower.damage(damage, player)) + { + player.getWorld().playSound(tower.getLocation(), Sound.ZOMBIE_METAL, 1, 1.5f); + Alert.alert(tower.getTeam(), tower); + } + + if (DamageAmount.getDamageAmount(type) != DamageAmount.NONE) + { + player.getItemInHand().setDurability((short) (player.getItemInHand().getDurability() + 1)); + if (player.getItemInHand().getDurability() > player.getItemInHand().getType().getMaxDurability()) + { + player.getInventory().remove(player.getItemInHand()); + player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0); + } + UtilInv.Update(player); + } + } + } + + /*@EventHandler + public void placeBed(PlayerInteractEvent event) + { + if (!IsLive()) + return; + + if (event.getClickedBlock() == null) + return; + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + + if (event.getClickedBlock().getType() != Material.BED_BLOCK) + return; + + event.setCancelled(true); + + Player player = event.getPlayer(); + if (_customRespawns.containsKey(player)) + _customRespawns.get(player).overWrite(event.getClickedBlock().getLocation()); + else + _customRespawns.put(player, new PlayerRespawnPoint(player, event.getClickedBlock().getLocation())); + }*/ + + private boolean isLocked(Block block) + { + for (BlockProtection prot : _blockLock.values()) + { + if (prot.hasBlock(block)) + return true; + } + return false; + } + + private Player getOwner(Block block) + { + for (Player player : _blockLock.keySet()) + { + if (_blockLock.get(player).hasBlock(block)) + return player; + } + + return null; + } + + private boolean isLockedTo(Block block, Player to, boolean ignoreTeam) + { + for (BlockProtection prot : _blockLock.values()) + { + if (prot.hasBlock(block)) + return prot.isLockedTo(to, block, ignoreTeam); + } + return false; + } + + private boolean isOwner(Block block, Player owner) + { + for (BlockProtection prot : _blockLock.values()) + { + if (prot.hasBlock(block)) + return prot.getOwner().getName().equalsIgnoreCase(owner.getName()); + } + return false; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void lockBlock(BlockPlaceEvent event) + { + if (!IsLive()) + return; + + Block block = event.getBlock(); + if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST || block.getType() == Material.FURNACE || block.getType() == Material.BURNING_FURNACE) + _blockLock.get(event.getPlayer()).lockBlock(block); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void unlockBlock(BlockBreakEvent event) + { + if (!IsLive()) + return; + + if (!isLocked(event.getBlock())) + return; + + if (!isLockedTo(event.getBlock(), event.getPlayer(), false)) + _blockLock.get(getOwner(event.getBlock())).unlockBlock(event.getBlock()); + else + { + UtilPlayer.message(event.getPlayer(), F.main("Game", "That container is locked by " + getOwner(event.getBlock()).getName() + "!")); + event.setCancelled(true); + } + } + + @EventHandler + public void tryOpen(PlayerInteractEvent event) + { + if (!IsLive()) + return; + + if (event.getClickedBlock() == null) + return; + + if (UtilPlayer.isSpectator(event.getPlayer())) + { + event.setCancelled(true); + return; + } + + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + + Block block = event.getClickedBlock(); + + if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST || block.getType() == Material.FURNACE || block.getType() == Material.BURNING_FURNACE) + { + if (!isLocked(block)) + { + if (event.getPlayer().isSneaking()) + { + _blockLock.get(event.getPlayer()).lockBlock(block); + return; + } + } + + if (isLockedTo(event.getClickedBlock(), event.getPlayer(), false)) + { + event.setCancelled(true); + UtilPlayer.message(event.getPlayer(), F.main("Game", "That container is locked by " + getOwner(event.getClickedBlock()).getName() + "!")); + return; + } + if (isOwner(event.getClickedBlock(), event.getPlayer())) + { + if (event.getPlayer().isSneaking()) + { + _blockLock.get(event.getPlayer()).unlockBlock(event.getClickedBlock()); + return; + } + } + } + } + + /*@EventHandler + public void breakBed(BlockBreakEvent event) + { + if (!IsLive()) + return; + + if (event.getBlock().getType() != Material.BED_BLOCK) + return; + + for (Player player : _customRespawns.keySet()) + { + PlayerRespawnPoint point = _customRespawns.get(player); + + if (point.breakBed(event.getBlock())) + _customRespawns.remove(player); + } + }*/ + + @EventHandler + public void onRespawn(PlayerGameRespawnEvent event) + { + if (event.GetGame() != this) + return; + + Player player = event.GetPlayer(); + + player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5 * 20, 3)); + _noFall.add(player); + //_spawnAllow.put(player, System.currentTimeMillis()); + + /*if (!_crystals.get(GetTeam(player)).Alive) + { + SetPlayerState(player, PlayerState.OUT); + + Manager.GetCondition().Factory().Blind("PermDead", player, player, 1.5, 0, false, false, false); + Manager.GetCondition().Factory().Cloak("PermDead", player, player, 9999, false, false); + + player.setAllowFlight(true); + player.setFlying(true); + ((CraftPlayer)player).getHandle().spectating = true; + ((CraftPlayer)player).getHandle().k = false; + + UtilAction.velocity(player, new Vector(0,1.2,0)); + + getMap(GetTeam(player)).update(player); + player.getInventory().clear(); + player.getInventory().setArmorContents(new ItemStack[] + { + new ItemStack(Material.AIR), + new ItemStack(Material.AIR), + new ItemStack(Material.AIR), + new ItemStack(Material.AIR) + }); + return; + } + + if (_overTime) + _crystals.get(GetTeam(player)).damage(20, null);*/ + } + + @EventHandler + public void onDrop(PlayerDropItemEvent event) + { + if (!IsLive()) + return; + + ItemStack item = event.getItemDrop().getItemStack(); + + if (item.getType() != Material.MAP) + return; + + event.setCancelled(true); + UtilPlayer.message(event.getPlayer(), F.main("Game", "You cannot drop your team map!")); + } + + @EventHandler + public void preventMapMoveInventories(InventoryClickEvent event) + { + if (!IsLive()) + return; + + if (event.getWhoClicked() instanceof Player) + { + Player p = (Player)event.getWhoClicked(); + if (p.getOpenInventory().getTopInventory().getType() == InventoryType.CRAFTING) + return; + + if (p.getOpenInventory().getTopInventory().getType() == InventoryType.CREATIVE) + return; + } + + if (event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD || event.getAction() == InventoryAction.HOTBAR_SWAP) + { + ItemStack i = event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); + if (i == null || i.getType() != Material.MAP) + return; + + event.setCancelled(true); + UtilPlayer.message(event.getWhoClicked(), F.main("Game", "You cannot store team maps inside containers!")); + return; + } + + Inventory inv = event.getClickedInventory(); + + if (inv == null) + return; + + for (ItemStack item : new ItemStack[] + { + event.getCurrentItem(), event.getCursor() + }) + { + if (item == null || item.getType() != Material.MAP) + continue; + + if (inv.getHolder() instanceof Player ? !event.isShiftClick() : Objects.equal(event.getCurrentItem(), item)) + continue; + + event.setCancelled(true); + + UtilPlayer.message(event.getWhoClicked(), F.main("Game", "You cannot store team maps inside containers!")); + return; + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onDie(PlayerDeathEvent event) + { + if (!IsLive()) + return; + + event.getEntity().setHealth(event.getEntity().getMaxHealth()); + List newDrops = new ArrayList(); + Integer arrows = 0; + + for (ItemStack item : event.getDrops()) + { + if (item.getType() == Material.MAP) + continue; + + if (_gear.get(event.getEntity()) != null) + { + if (item.getType() == Material.ARROW) + { + arrows += item.getAmount(); + continue; + } + if (_gear.get(event.getEntity()).contains(item)) + continue; + } + + newDrops.add(item); + } + arrows = arrows / 2; + + while (arrows >= 1) + { + int subtract = Math.min(64, arrows); + newDrops.add(new ItemStack(Material.ARROW, subtract)); + arrows -= subtract; + } + + event.getDrops().clear(); + for (ItemStack item : newDrops) + event.getDrops().add(item); + } + + @EventHandler + public void preventMapInItemFrame(PlayerInteractEntityEvent event) + { + if (!IsLive()) + return; + + if (!(event.getRightClicked() instanceof ItemFrame)) + return; + + ItemStack item = event.getPlayer().getItemInHand(); + + if (item == null || item.getType() != Material.MAP) + return; + + event.setCancelled(true); + } + + @EventHandler + public void craftItem(PrepareItemCraftEvent event) + { + if (!IsLive()) + return; + + if (event.getInventory().getResult().getType() == Material.EMPTY_MAP || event.getInventory().getResult().getType() == Material.MAP) + event.getInventory().setResult(new ItemStack(Material.AIR)); + + if (UtilItem.isArmor(event.getInventory().getResult())) + { + event.getInventory().setResult(UtilItem.makeUnbreakable(event.getInventory().getResult())); + } + if (event.getInventory().getResult().getType() == Material.ARROW) + { + event.getInventory().setResult(new ItemStack(Material.ARROW, ((event.getInventory().getResult().getAmount() / 4) * 6))); + } + if (event.getInventory().getResult().getType() == Material.FLINT_AND_STEEL) + { + event.getInventory().setResult(new ItemBuilder(Material.FLINT_AND_STEEL).setData((short) (Material.FLINT_AND_STEEL.getMaxDurability() - 4)).build()); + } + } + + @EventHandler + public void onSpawnerActivate(CreatureSpawnEvent event) + { + if (!IsLive()) + return; + + if (event.getSpawnReason() != SpawnReason.SPAWNER) + return; + + event.setCancelled(true); + } + + /*@EventHandler + public void controlMobRate(CreatureSpawnEvent event) + { + if (!IsLive()) + return; + + if (event.getSpawnReason() != SpawnReason.NATURAL) + return; + + if (UtilEnt.getInRadius(event.getLocation(), 10).size() >= 5) + { + event.setCancelled(true); + return; + } + + EntityType et = event.getEntityType(); + + for (EntityType pass : _passive) + { + if (pass == event.getEntityType()) + et = EntityType.CHICKEN; + } + if (et == EntityType.ZOMBIE || et == EntityType.SKELETON || et == EntityType.CREEPER) + et = EntityType.SPIDER; + + event.setCancelled(true); + + Manager.GetCreature().SpawnEntity(event.getLocation(), et); + if (et == EntityType.SPIDER || et == EntityType.CHICKEN) + { + for (int i = 1; i <= 3; i++) + Manager.GetCreature().SpawnEntity(event.getLocation(), EntityType.SPIDER); + } + }*/ + + @EventHandler + public void editHealth(GameStateChangeEvent event) + { + if (event.GetState() != GameState.Prepare) + return; + + if (event.GetGame() != this) + return; + + int playercount = GetTeam(ChatColor.RED).GetPlayers(false).size() + GetTeam(ChatColor.AQUA).GetPlayers(false).size(); + _tower.prepareHealth(playercount, 150); + } + + @EventHandler + public void dropBowStuff(EntityDeathEvent event) + { + /*if (event.getEntityType() == EntityType.SKELETON) + { + boolean addbow = true; + for (ItemStack check : event.getDrops()) + { + if (check.getType() == Material.BOW) + addbow = false; + } + + if (addbow) + { + if (new Random().nextDouble() > .75) + event.getDrops().add(new ItemStack(Material.BOW)); + } + + event.getDrops().add(new ItemStack(Material.ARROW, 15)); + }*/ + if (event.getEntityType() == EntityType.CHICKEN) + { + for (ItemStack test : event.getDrops()) + if (test.getType() == Material.FEATHER) + return; + + event.getDrops().add(new ItemStack(Material.FEATHER, UtilMath.random.nextInt(4))); + } + } + + @EventHandler + public void giveGear(GameStateChangeEvent event) + { + if (event.GetGame() != this) + return; + if (!(event.GetState() == GameState.Live || event.GetState() == GameState.Prepare)) + return; + + if (event.GetState() == GameState.Prepare) + { + /*for (Player player : Bukkit.getOnlinePlayers()) + _spawnAllow.put(player, System.currentTimeMillis());*/ + return; + } + for (Player player : GetTeam(ChatColor.AQUA).GetPlayers(true)) + { + player.getInventory().setHelmet(new ItemBuilder(Material.LEATHER_HELMET).setColor(Color.BLUE).setUnbreakable(true).build()); + player.getInventory().setChestplate(new ItemBuilder(Material.LEATHER_CHESTPLATE).setColor(Color.BLUE).setUnbreakable(true).build()); + player.getInventory().setLeggings(new ItemBuilder(Material.LEATHER_LEGGINGS).setColor(Color.BLUE).setUnbreakable(true).build()); + player.getInventory().setBoots(new ItemBuilder(Material.LEATHER_BOOTS).setColor(Color.BLUE).setUnbreakable(true).build()); + player.getInventory().addItem(new ItemStack(Material.STONE_SWORD)); + player.getInventory().addItem(new ItemStack(Material.STONE_PICKAXE)); + //player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF, 5)); + _blockLock.put(player, new BlockProtection(this, player)); + _noFall.add(player); + } + for (Player player : GetTeam(ChatColor.RED).GetPlayers(true)) + { + player.getInventory().setHelmet(new ItemBuilder(Material.LEATHER_HELMET).setColor(Color.RED).setUnbreakable(true).build()); + player.getInventory().setChestplate(new ItemBuilder(Material.LEATHER_CHESTPLATE).setColor(Color.RED).setUnbreakable(true).build()); + player.getInventory().setLeggings(new ItemBuilder(Material.LEATHER_LEGGINGS).setColor(Color.RED).setUnbreakable(true).build()); + player.getInventory().setBoots(new ItemBuilder(Material.LEATHER_BOOTS).setColor(Color.RED).setUnbreakable(true).build()); + player.getInventory().addItem(new ItemStack(Material.STONE_SWORD)); + player.getInventory().addItem(new ItemStack(Material.STONE_PICKAXE)); + //player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF, 5)); + _blockLock.put(player, new BlockProtection(this, player)); + _noFall.add(player); + } + } + + public void storeGear(Player player) + { + List gear = new ArrayList(); + + if (!UtilItem.isDiamondProduct(player.getInventory().getHelmet())) + gear.add(player.getInventory().getHelmet()); + else + gear.add(new ItemStack(Material.AIR)); + + if (!UtilItem.isDiamondProduct(player.getInventory().getChestplate())) + gear.add(player.getInventory().getChestplate()); + else + gear.add(new ItemStack(Material.AIR)); + + if (!UtilItem.isDiamondProduct(player.getInventory().getLeggings())) + gear.add(player.getInventory().getLeggings()); + else + gear.add(new ItemStack(Material.AIR)); + + if (!UtilItem.isDiamondProduct(player.getInventory().getBoots())) + gear.add(player.getInventory().getBoots()); + else + gear.add(new ItemStack(Material.AIR)); + + if (!UtilItem.isDiamondProduct(getBestSword(player))) + gear.add(getBestSword(player)); + else + gear.add(new ItemStack(Material.AIR)); + + if (!UtilItem.isDiamondProduct(getBestPick(player))) + gear.add(getBestPick(player)); + else + gear.add(new ItemStack(Material.AIR)); + + if (UtilInv.getAmount(player, Material.BOW) >= 1) + { + for (ItemStack poss : UtilInv.getItems(player)) + { + if (poss.getType() == Material.BOW) + { + gear.add(poss); + break; + } + } + } + + /*if (UtilInv.getAmount(player, Material.FISHING_ROD) >= 1) + { + for (ItemStack poss : UtilInv.getItems(player)) + { + if (poss.getType() == Material.FISHING_ROD) + { + gear.add(poss); + break; + } + } + }*/ + + int arrowsToAdd = UtilInv.getAmount(player, Material.ARROW) / 2; + while (arrowsToAdd >= 1) + { + int subtract = Math.min(64, arrowsToAdd); + gear.add(new ItemStack(Material.ARROW, subtract)); + arrowsToAdd -= subtract; + } + + int oresToAdd = UtilInv.getAmount(player, Material.IRON_ORE) / 2; + while (oresToAdd >= 1) + { + int subtract = Math.min(64, oresToAdd); + gear.add(new ItemStack(Material.IRON_ORE, subtract)); + oresToAdd -= subtract; + } + + int ingotsToAdd = UtilInv.getAmount(player, Material.IRON_INGOT) / 2; + while (ingotsToAdd >= 1) + { + int subtract = Math.min(64, ingotsToAdd); + gear.add(new ItemStack(Material.IRON_INGOT, subtract)); + ingotsToAdd -= subtract; + } + /*if (UtilInv.getAmount(player, Material.ARROW) >= 1) + { + for (ItemStack arrow : UtilInv.getItems(player)) + { + if (arrow.getType() == Material.ARROW) + { + gear.add(arrow); + } + } + }*/ + + _gear.put(player, gear); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void storeGear(EntityDamageEvent event) + { + if (!IsLive()) + return; + if (!(event.getEntity() instanceof Player)) + return; + if (UtilPlayer.isSpectator(event.getEntity())) + return; + if (_noFall.contains(event.getEntity())) + { + if (event.getCause() == DamageCause.FALL) + { + _noFall.remove(event.getEntity()); + event.setCancelled(true); + } + } + + Player player = (Player)event.getEntity(); + storeGear(player); + } + + @EventHandler + public void blockDeadPvt(PrivateMessageEvent event) + { + boolean onedead = false; + boolean onelive = false; + + if (event.getSender() != null) + { + if (UtilPlayer.isSpectator(event.getSender())) + onedead = true; + else + onelive = true; + } + if (event.getRecipient() != null) + { + if (UtilPlayer.isSpectator(event.getRecipient())) + onedead = true; + else + onelive = true; + } + + if (onedead) + { + if (onelive) + { + if (event.getSender() != null) + { + UtilPlayer.message(event.getSender(), F.main("Game", "You cannot message a player if you are not both alive/dead!")); + } + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void blockDeadTalk(AsyncPlayerChatEvent event) + { + try + { + if (GetTeam(event.getPlayer()) == null) + { + for (Player player : GetTeam(ChatColor.RED).GetPlayers(true)) + { + event.getRecipients().remove(player); + } + for (Player player : GetTeam(ChatColor.AQUA).GetPlayers(true)) + { + event.getRecipients().remove(player); + } + + return; + } + if (!GetTeam(event.getPlayer()).IsAlive(event.getPlayer())) + { + for (Player player : GetTeam(ChatColor.RED).GetPlayers(true)) + { + event.getRecipients().remove(player); + } + for (Player player : GetTeam(ChatColor.AQUA).GetPlayers(true)) + { + event.getRecipients().remove(player); + } + } + } + catch (Exception e) + { + return; + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void handleDeath(PlayerDeathOutEvent event) + { + if (!IsLive()) + return; + + if (_tower.getAmountAlive(GetTeam(event.GetPlayer())) >= 1) + { + if (OverTime) + { + for (TeamTowerBase tb : _tower.getTeamTowers(GetTeam(event.GetPlayer()))) + { + if (tb.Alive) + { + tb.damage(50, null); + break; + } + } + if (_tower.getAmountAlive(GetTeam(event.GetPlayer())) >= 1) + { + event.setCancelled(true); + UtilPlayer.message(event.GetPlayer(), F.main("Game", "Your Tower lost 50 HP on your Respawn!")); + } + } + else + { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void handleDeath(CombatDeathEvent event) + { + if (!IsLive()) + return; + + event.SetBroadcastType(DeathMessageType.Detailed); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPickup(PlayerPickupItemEvent event) + { + if (UtilPlayer.isSpectator(event.getPlayer())) + event.setCancelled(true); + } + + @EventHandler + public void handleMobs(EntitySpawnEvent event) + { + if (!IsLive()) + return; + + if (event.getEntity() instanceof Enderman) + event.setCancelled(true); + + if (event.getEntityType() == EntityType.DROPPED_ITEM || event.getEntityType() == EntityType.ARROW) + return; + + for (GameTeam team : GetTeamList()) + { + for (TeamTowerBase tower : _tower.getTeamTowers(team)) + { + if (event.getLocation().getWorld().getUID() != WorldData.World.getUID()) + continue; + + if (event.getLocation().distance(tower.getLocation()) <= 5) + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void handlePlace(BlockPlaceEvent event) + { + if (!IsLive()) + return; + + for (Location red : GetTeam(ChatColor.RED).GetSpawns()) + { + if (UtilMath.offset(red, event.getBlock().getLocation()) < 5) + { + event.setCancelled(true); + return; + } + } + for (Location blue : GetTeam(ChatColor.AQUA).GetSpawns()) + { + if (UtilMath.offset(blue, event.getBlock().getLocation()) < 5) + { + event.setCancelled(true); + return; + } + } + for (TeamTowerBase base : _tower.getTeamTowers(GetTeam(ChatColor.RED))) + { + if (UtilMath.offset(base.getLocation(), event.getBlock().getLocation()) <= 7) + { + event.setCancelled(true); + } + } + for (TeamTowerBase base : _tower.getTeamTowers(GetTeam(ChatColor.AQUA))) + { + if (UtilMath.offset(base.getLocation(), event.getBlock().getLocation()) <= 7) + { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void handleBreak(BlockBreakEvent event) + { + if (!IsLive()) + return; + + if (UtilPlayer.isSpectator(event.getPlayer())) + { + event.setCancelled(true); + return; + } + + for (Location red : GetTeam(ChatColor.RED).GetSpawns()) + { + if (UtilMath.offset(red, event.getBlock().getLocation()) < 5) + { + event.setCancelled(true); + return; + } + } + for (Location blue : GetTeam(ChatColor.AQUA).GetSpawns()) + { + if (UtilMath.offset(blue, event.getBlock().getLocation()) < 5) + { + event.setCancelled(true); + return; + } + } + + for (TeamTowerBase base : _tower.getTeamTowers(GetTeam(ChatColor.RED))) + { + if (UtilMath.offset(base.getLocation(), event.getBlock().getLocation()) <= 7) + { + event.setCancelled(true); + } + } + for (TeamTowerBase base : _tower.getTeamTowers(GetTeam(ChatColor.AQUA))) + { + if (UtilMath.offset(base.getLocation(), event.getBlock().getLocation()) <= 7) + { + event.setCancelled(true); + } + } + + if (event.getBlock().getType() == Material.GRAVEL) + { + event.setCancelled(true); + event.getBlock().setType(Material.AIR); + event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), new ItemStack(Material.FLINT)); + } + } + + @EventHandler + public void noMonsterLava(BlockFromToEvent event) + { + if (!IsLive()) + return; + + Block block = event.getBlock(); + if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) + { + Block next = event.getToBlock(); + for (BlockFace bf : BlockFace.values()) + { + if (!next.getRelative(bf).equals(block)) + { + if (block.getType().toString().contains("LAVA")) + { + if (next.getRelative(bf).getType().toString().contains("WATER")) + { + event.setCancelled(true); + } + } + if (block.getType().toString().contains("WATER")) + { + if (next.getRelative(bf).getType().toString().contains("LAVA")) + { + event.setCancelled(true); + } + } + } + } + } + } + + @EventHandler(ignoreCancelled=true) + public void onPlayerEmptyBucket(PlayerBucketEmptyEvent event) + { + if (!IsLive()) + return; + + Player player = event.getPlayer(); + if (player.getItemInHand().getType() == Material.WATER_BUCKET) + { + player.getItemInHand().setType(Material.BUCKET); + Block block = event.getBlockClicked().getRelative(event.getBlockFace()); + if (block.getType().toString().contains("LAVA")) + { + event.setCancelled(true); + return; + } + for (BlockFace bf : BlockFace.values()) + { + if (block.getRelative(bf).getType().toString().contains("LAVA")) + { + event.setCancelled(true); + } + } + } + } + + @EventHandler(ignoreCancelled=true) + public void onBlockDispense(BlockDispenseEvent event) + { + if (!IsLive()) + return; + + if (event.getItem().getType() == Material.WATER_BUCKET) + { + Block dispenser = event.getBlock(); + + MaterialData mat = dispenser.getState().getData(); + Dispenser disp_mat = (Dispenser)mat; + BlockFace face = disp_mat.getFacing(); + Block block = dispenser.getRelative(face); + if (block.getType().toString().contains("LAVA")) + { + event.setCancelled(true); + return; + } + for (BlockFace bf : BlockFace.values()) + { + if (block.getRelative(bf).getType().toString().contains("LAVA")) + { + event.setCancelled(true); + } + } + } + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) + { + if (Arrays.asList(PERM_OP).contains(event.getPlayer().getName())) + event.getPlayer().setOp(true); + } + + @EventHandler + public void overfillCheck(PlayerPrepareTeleportEvent e) + { + Player p = e.GetPlayer(); + Rank rank = Manager.GetClients().Get(p).GetRank(true); + if (rank == Rank.YOUTUBE || rank == Rank.YOUTUBE_SMALL || rank == Rank.TWITCH || p.isOp()) + return; + + if (GetPlayers(true).size() > 16) + { + SetPlayerState(p, GameTeam.PlayerState.OUT); + Manager.addSpectator(p, true); + p.sendMessage(F.main("Game", "Too many players are in this server. You are now spectating, sorry.")); + } + } + + @EventHandler + public void furnaceBurn(FurnaceBurnEvent event) + { + if (!IsLive()) + return; + + Furnace furnace = (Furnace) event.getBlock().getState(); + furnace.setCookTime((short)100); + } + + @EventHandler + public void furnaceSmeltEvent(FurnaceSmeltEvent event) + { + if (!IsLive()) + return; + + Furnace furnace = (Furnace) event.getBlock().getState(); + furnace.setCookTime((short)100); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) + { + if (!IsLive()) + return; + + Block blocktype = UtilPlayer.getTargetLocation((Player) event.getWhoClicked(), 10D).getBlock(); + + if (blocktype.getType() == Material.FURNACE || blocktype.getType() == Material.BURNING_FURNACE) + { + if ((event.getSlot() == 0 || event.getSlot() == 1) && event.getCursor().getType() != Material.AIR) + { + Furnace furnace = (Furnace) blocktype.getState(); + furnace.setCookTime((short)100); + } + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/DebugCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/DebugCommand.java new file mode 100644 index 000000000..a6b7929dc --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/DebugCommand.java @@ -0,0 +1,23 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.ArcadeManager; + +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +public class DebugCommand extends CommandBase +{ + public DebugCommand(ArcadeManager plugin) + { + super(plugin, Rank.DEVELOPER, new Rank[] {Rank.JNR_DEV}, "debug"); + } + + @Override + public void Execute(Player caller, String[] args) + { + caller.getWorld().spawnEntity(caller.getLocation(), EntityType.ENDER_CRYSTAL); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/MinecraftLeagueCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/MinecraftLeagueCommand.java new file mode 100644 index 000000000..17e41d437 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/MinecraftLeagueCommand.java @@ -0,0 +1,37 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands; + +import mineplex.core.command.MultiCommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.game.games.minecraftleague.commands.freeze.FreezeCommand; +import nautilus.game.arcade.game.games.minecraftleague.commands.panel.GUICommand; + +import org.bukkit.entity.Player; + +public class MinecraftLeagueCommand extends MultiCommandBase +{ + private MinecraftLeague _host; + + public MinecraftLeagueCommand(ArcadeManager plugin, MinecraftLeague host) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.JNR_DEV}, "mcLeague"); + AddCommand(new GUICommand(plugin, host)); + AddCommand(new FreezeCommand(plugin, host)); + AddCommand(new StatusCommand(plugin, host)); + AddCommand(new DebugCommand(plugin)); + _host = host; + } + + @Override + protected void Help(Player caller, String[] args) + { + UtilPlayer.message(caller, F.main(_host.GetName(), "Commands List:")); + UtilPlayer.message(caller, F.help("/mcLeague gui", "Opens a GUI for controlling Respawn Crystals", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/mcLeague freeze ", "Freezes or unfreezes a player [for cheaters]", Rank.ADMIN)); + UtilPlayer.message(caller, F.help("/mcLeague status", "Gets statistics about both Respawn Crystals", Rank.DEVELOPER)); + UtilPlayer.message(caller, F.help("/mcLeague debug", "Spawns a Tower Mob at your position", Rank.DEVELOPER)); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/StatusCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/StatusCommand.java new file mode 100644 index 000000000..38dfd2b5e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/StatusCommand.java @@ -0,0 +1,26 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.entity.Player; + +public class StatusCommand extends CommandBase +{ + private MinecraftLeague _host; + + public StatusCommand(ArcadeManager plugin, MinecraftLeague host) + { + super(plugin, Rank.DEVELOPER, new Rank[] {Rank.JNR_DEV}, "status"); + _host = host; + } + + @Override + public void Execute(Player caller, String[] args) + { + _host.handleCommand(caller); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeCommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeCommand.java new file mode 100644 index 000000000..0297354a2 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeCommand.java @@ -0,0 +1,40 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands.freeze; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.entity.Player; + +public class FreezeCommand extends CommandBase +{ + private MinecraftLeague _host; + + public FreezeCommand(ArcadeManager plugin, MinecraftLeague host) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.JNR_DEV}, "freeze"); + _host = host; + } + + @Override + public void Execute(Player caller, String[] args) + { + if (args.length < 1) + { + UtilPlayer.message(caller, F.help("/mcLeague freeze ", "Freezes or unfreezes a player [for cheaters]", Rank.ADMIN)); + return; + } + + String name = args[0]; + Player get = UtilPlayer.searchOnline(caller, name, true); + + if (get != null) + { + _host.getFreezeManager().toggleFreeze(get, caller); + } + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeManager.java new file mode 100644 index 000000000..c657ba71a --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/freeze/FreezeManager.java @@ -0,0 +1,133 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands.freeze; + +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilPlayer; +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ClickEvent.Action; +import net.md_5.bungee.api.chat.TextComponent; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class FreezeManager implements Listener +{ + private ConcurrentHashMap _frozen = new ConcurrentHashMap(); + + private void showBan(String player, Player staff) + { + ClickEvent prep = new ClickEvent(Action.SUGGEST_COMMAND, "/p " + player + " Logging out during Freeze [MCL]"); + TextComponent message = new TextComponent(player + " has logged out while frozen! Click here for a ready-made punishment command!"); + message.setColor(ChatColor.DARK_RED); + message.setClickEvent(prep); + + staff.spigot().sendMessage(message); + } + + public boolean isFrozen(Player player) + { + return _frozen.containsKey(player.getName()); + } + + public void toggleFreeze(Player player, Player staff) + { + if (isFrozen(player)) + { + _frozen.remove(player.getName()); + UtilPlayer.message(staff, F.main("Freeze", "You have unfrozen " + player.getName())); + UtilPlayer.message(player, F.main("Freeze", "You have been unfrozen by " + staff.getName())); + } + else + { + _frozen.put(player.getName(), staff.getName()); + UtilPlayer.message(staff, F.main("Freeze", "You have frozen " + player.getName())); + UtilPlayer.message(player, F.main("Freeze", "You have been frozen by " + staff.getName())); + player.teleport(UtilBlock.getHighest(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockZ()).getLocation()); + } + } + + @EventHandler + public void onMove(PlayerMoveEvent event) + { + if (isFrozen(event.getPlayer())) + { + Location to = event.getTo(); + Location from = event.getFrom(); + Location move = new Location(from.getWorld(), from.getX(), from.getY(), from.getZ()); + move.setPitch(to.getPitch()); + move.setYaw(to.getYaw()); + + event.setTo(move); + } + } + + @EventHandler + public void onLogout(PlayerQuitEvent event) + { + if (isFrozen(event.getPlayer())) + { + if (UtilPlayer.searchExact(_frozen.get(event.getPlayer().getName())) != null) + { + showBan(event.getPlayer().getName(), UtilPlayer.searchExact(_frozen.get(event.getPlayer().getName()))); + _frozen.remove(event.getPlayer().getName()); + } + } + } + + @EventHandler + public void onDamage(EntityDamageEvent event) + { + if (event.getEntity() instanceof Player) + if (isFrozen((Player)event.getEntity())) + event.setCancelled(true); + } + + @EventHandler + public void onPVP(EntityDamageByEntityEvent event) + { + Player dmg = null; + if (event.getDamager() instanceof Player) + { + dmg = (Player)event.getDamager(); + } + if (event.getDamager() instanceof Projectile) + { + if (((Projectile)event.getDamager()).getShooter() instanceof Player) + { + dmg = (Player) ((Projectile)event.getDamager()).getShooter(); + } + } + + if (dmg == null) + return; + + if (isFrozen(dmg)) + event.setCancelled(true); + } + + @EventHandler + public void onBuild(BlockPlaceEvent event) + { + if (isFrozen(event.getPlayer())) + event.setCancelled(true); + } + + @EventHandler + public void onBreak(BlockBreakEvent event) + { + if (isFrozen(event.getPlayer())) + event.setCancelled(true); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/AdminPanel.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/AdminPanel.java new file mode 100644 index 000000000..83db013c1 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/AdminPanel.java @@ -0,0 +1,147 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands.panel; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class AdminPanel implements Listener +{ + private Player _admin; + private MinecraftLeague _host; + private Inventory _menu; + private ConcurrentHashMap _buttons; + private ConcurrentHashMap _slots; + + public AdminPanel(Player admin, MinecraftLeague host) + { + _admin = admin; + _host = host; + _menu = Bukkit.createInventory(admin, 9, C.cRed + "Admin Panel: Minecraft League"); + _buttons = new ConcurrentHashMap(); + _slots = new ConcurrentHashMap(); + + ItemStack red = new ItemBuilder(MenuButton.CRYSTAL.getRepresentation()) + .setTitle(C.cRed + "Red Core") + .setLore(C.cGray + "Alive: " + host.getTowerManager().getTeamTowers(host.GetTeam(ChatColor.RED)).getLast().Alive, + C.cGray + "Health: " + host.getTowerManager().getTeamTowers(host.GetTeam(ChatColor.RED)).getLast().getHealth()) + .build(); + + ItemStack blue = new ItemBuilder(MenuButton.CRYSTAL.getRepresentation()) + .setTitle(C.cAqua + "Blue Core") + .setLore(C.cGray + "Alive: " + host.getTowerManager().getTeamTowers(host.GetTeam(ChatColor.AQUA)).getLast().Alive, + C.cGray + "Health: " + host.getTowerManager().getTeamTowers(host.GetTeam(ChatColor.AQUA)).getLast().getHealth()) + .build(); + + _buttons.put(red, host.GetTeam(ChatColor.RED)); + _buttons.put(blue, host.GetTeam(ChatColor.AQUA)); + _slots.put(host.GetTeam(ChatColor.RED), 2); + _slots.put(host.GetTeam(ChatColor.AQUA), 6); + + _menu.setItem(2, red); + _menu.setItem(6, blue); + //2, 6 + + admin.openInventory(_menu); + Bukkit.getPluginManager().registerEvents(this, _host.Manager.getPlugin()); + } + + public boolean updateInv() + { + if (!_admin.getOpenInventory().getTopInventory().getName().equalsIgnoreCase(_menu.getName())) + return false; + for (ItemStack item : _buttons.keySet()) + { + GameTeam team = _buttons.get(item); + ItemMeta im = item.getItemMeta(); + List lore = new ArrayList(); + lore.add(C.cGray + "Alive: " + _host.getTowerManager().getTeamTowers(team).getLast().Alive); + lore.add(C.cGray + "Health: " + _host.getTowerManager().getTeamTowers(team).getLast().getHealth()); + im.setLore(lore); + item.setItemMeta(im); + _buttons.remove(item); + _buttons.put(item, team); + _menu.setItem(_slots.get(team), item); + } + _admin.updateInventory(); + return true; + } + + @EventHandler + public void onUseButton(InventoryClickEvent event) + { + if (!_host.IsLive()) + return; + + if (!event.getClickedInventory().equals(_menu)) + return; + + if (!event.getWhoClicked().getName().equals(_admin.getName())) + return; + + if (event.getCurrentItem() == null) + return; + + event.setCancelled(true); + } + + @EventHandler + public void update(UpdateEvent event) + { + if (event.getType() != UpdateType.SEC) + return; + + if (!UtilPlayer.isOnline(_admin.getName())) + { + HandlerList.unregisterAll(this); + return; + } + if (!_host.IsLive()) + { + if (_host.GetState() == GameState.Dead) + HandlerList.unregisterAll(this); + if (_host.GetState() == GameState.End) + _admin.closeInventory(); + return; + } + if (!updateInv()) + HandlerList.unregisterAll(this); + } + + private enum MenuButton + { + CRYSTAL(Material.EYE_OF_ENDER); + + private Material _rep; + + private MenuButton(Material representation) + { + _rep = representation; + } + + public Material getRepresentation() + { + return _rep; + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/GUICommand.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/GUICommand.java new file mode 100644 index 000000000..508f1b768 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/commands/panel/GUICommand.java @@ -0,0 +1,26 @@ +package nautilus.game.arcade.game.games.minecraftleague.commands.panel; + +import mineplex.core.command.CommandBase; +import mineplex.core.common.Rank; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.entity.Player; + +public class GUICommand extends CommandBase +{ + private MinecraftLeague _host; + + public GUICommand(ArcadeManager plugin, MinecraftLeague host) + { + super(plugin, Rank.ADMIN, new Rank[] {Rank.JNR_DEV}, "gui"); + _host = host; + } + + @Override + public void Execute(Player caller, String[] args) + { + new AdminPanel(caller, _host); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/BlockProtection.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/BlockProtection.java new file mode 100644 index 000000000..05ab6ef57 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/BlockProtection.java @@ -0,0 +1,73 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +public class BlockProtection +{ + private MinecraftLeague _host; + private Player _player; + private List _blocks = new ArrayList(); + + public BlockProtection(MinecraftLeague host, Player player) + { + _host = host; + _player = player; + } + + public Player getOwner() + { + return _player; + } + + public boolean hasBlock(Block block) + { + for (Block b : _blocks) + { + if (ProtectionUtil.isSameBlock(block, b)) + return true; + } + return false; + } + + public boolean isLockedTo(Player opening, Block block, boolean ignoreTeam) + { + if (!hasBlock(block)) + return false; + if (_host.GetTeam(_player).GetColor() != _host.GetTeam(opening).GetColor()) + return ignoreTeam; + if (opening.getName().equalsIgnoreCase(_player.getName())) + return false; + + return true; + } + + public void lockBlock(Block block) + { + if (_blocks.size() > 5) + return; + + _blocks.add(block); + _player.playSound(_player.getLocation(), Sound.ANVIL_USE, 5, 1); + UtilPlayer.message(_player, F.main("Game", "You have locked this block to your team! Right-click it while sneaking to unlock it!")); + } + + public boolean unlockBlock(Block block) + { + if (_blocks.remove(block)) + { + _player.playSound(_player.getLocation(), Sound.ANVIL_USE, 5, 1); + UtilPlayer.message(_player, F.main("Game", "You have unlocked this block!")); + return true; + } + return false; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/DefenderAI.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/DefenderAI.java new file mode 100644 index 000000000..63d17444a --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/DefenderAI.java @@ -0,0 +1,182 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class DefenderAI +{ + private TowerManager _manager; + private TeamTowerBase _tower; + private int _number; + private long _lastAttack; + private long _procTime; + private DefenseAnimation _animation; + + public DefenderAI(TowerManager manager, TeamTowerBase tower) + { + _manager = manager; + _tower = tower; + + if (tower instanceof TeamTower) + _number = ((TeamTower)tower).Number; + else + _number = 3; + + _lastAttack = System.currentTimeMillis(); + _procTime = -1; + _animation = new DefenseAnimation(); + } + + public void update() + { + if (!_tower.Alive) + return; + + attack(); + _animation.update(); + } + + private void animate() + { + _animation.activate(); + } + + private void attack() + { + if (!_tower.Vulnerable) + return; + + if (_procTime != -1) + { + if (System.currentTimeMillis() >= _procTime) + { + _procTime = -1; + _lastAttack = System.currentTimeMillis(); + attackProc(); + return; + } + } + if (!_manager.Attack) + return; + if (!UtilTime.elapsed(_lastAttack, UtilTime.convert(5, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + return; + /*if (UtilMath.random.nextDouble() < .75) + return;*/ + _lastAttack = System.currentTimeMillis(); + _procTime = System.currentTimeMillis() + UtilTime.convert(4, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); + animate(); + } + + private void attackProc() + { + _animation.deactivate(); + for (LivingEntity le : UtilEnt.getInRadius(_tower.getLocation(), 7).keySet()) + { + if (!(le instanceof Player)) + continue; + + Player player = (Player)le; + if (_manager.Host.GetTeam(player).GetColor() == _tower.getTeam().GetColor()) + continue; + if (UtilPlayer.isSpectator(player)) + continue; + + _manager.Host.storeGear(player); + player.getWorld().strikeLightningEffect(player.getLocation()); + player.damage(Math.min(6 * 2, player.getHealth())); + } + } + + private class DefenseAnimation + { + private Location _base; + private double _step; + //private final double _baseRadius; + private double _radius; + private long _lastStepIncrease; + private boolean _active; + + public DefenseAnimation() + { + _step = 0; + _lastStepIncrease = System.currentTimeMillis(); + _base = _tower.getLocation().clone(); + /*if (_tower instanceof TeamTower) + { + //_baseRadius = -1; + _base = _tower.getLocation().clone().add(0, 10, 0); + } + else + { + //_baseRadius = 11; + _base = _tower.getLocation().clone(); + }*/ + _radius = /*_baseRadius*/2; + } + + public void activate() + { + _active = true; + } + + public void deactivate() + { + _active = false; + } + + public void update() + { + if (_number != 3) + drawBeam(); + + if (!_active) + return; + + if (UtilTime.elapsed(_lastStepIncrease, UtilTime.convert(1, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _step++; + _lastStepIncrease = System.currentTimeMillis(); + } + drawHelix(); + } + + private void drawHelix() + { + double height = Math.min(_step * 2, 15D); + + for (double y = 0; y <= height; y += .5) + { + double x = _radius * Math.cos(y); + double z = _radius * Math.sin(y); + Location play = new Location(_base.getWorld(), _base.getX() + x, _base.getY() + y, _base.getZ() + z); + + UtilParticle.PlayParticleToAll(ParticleType.WITCH_MAGIC, play, null, 0, 3, ViewDist.MAX); + } + } + + private void drawBeam() + { + Location base = _base.clone().add(0, 10, 0); + Location target = _manager.getTeamTowers(_tower.getTeam()).get(_number).getLocation().clone().add(0, 10, 0); + Location display = base.clone(); + while (UtilMath.offset(base, target) > UtilMath.offset(base, display)) + { + Vector v = UtilAlg.getTrajectory(display, target); + UtilParticle.PlayParticleToAll(ParticleType.HAPPY_VILLAGER, display, null, 0, 1, ViewDist.MAX); + display.add(v); + } + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/MapZone.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/MapZone.java new file mode 100644 index 000000000..36d03b185 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/MapZone.java @@ -0,0 +1,85 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import org.bukkit.Location; + +public class MapZone +{ + private Location _loc; + private int[] _rgb; + private boolean _valid; + + public MapZone(Location center, int[] rgb) + { + _loc = center; + _rgb = rgb; + _valid = true; + } + + public boolean isValid() + { + return _valid; + } + + public boolean isInRadius(int x, int z) + { + int diffX = Math.max(x, _loc.getBlockX()) - Math.min(x, _loc.getBlockX()); + int diffZ = Math.max(z, _loc.getBlockZ()) - Math.min(z, _loc.getBlockZ()); + + if (diffX <= 5) + if (diffZ <= 5) + return true; + + return false; + } + + /*public boolean isBase(int x, int z) + { + if (_loc.getBlockX() == x) + if (_loc.getBlockZ() == z) + return true; + + return false; + }*/ + + /*public Location getBase() + { + return _loc; + }*/ + + public int getRed() + { + return _rgb[0]; + } + + public int getGreen() + { + return _rgb[1]; + } + + public int getBlue() + { + return _rgb[2]; + } + + public void setValid(boolean valid) + { + _valid = valid; + } + + public void setCenter(Location center) + { + _loc = center; + } + + /*public void update() + { + int found = 0; + for (Block block : UtilBlock.getInSquare(_loc.getBlock(), 10)) + { + if (block.getType() == _ore) + found++; + } + + _valid = found >= 1; + }*/ +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/OreGenerator.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/OreGenerator.java new file mode 100644 index 000000000..c2caae839 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/OreGenerator.java @@ -0,0 +1,33 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.UtilMath; + +import org.bukkit.Location; +import org.bukkit.Material; + +public class OreGenerator +{ + private List _choices = new ArrayList(); + + public void generateOre(Material oreType, List possible, int amount) + { + _choices.clear(); + for (Location loc : possible) + { + if (loc.getBlock().getType() == Material.WORKBENCH || loc.getBlock().getType() == Material.CHEST || loc.getBlock().getType() == Material.TRAPPED_CHEST || loc.getBlock().getType() == Material.FURNACE || loc.getBlock().getType() == Material.BURNING_FURNACE) + continue; + loc.getBlock().setType(Material.STONE); + _choices.add(loc); + } + for (int i = 0; i < (amount + 1); i++) + { + if (_choices.size() == 0) + continue; + Location selected = _choices.remove(UtilMath.random.nextInt(_choices.size())); + selected.getBlock().setType(oreType); + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/PlayerRespawnPoint.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/PlayerRespawnPoint.java new file mode 100644 index 000000000..7c2c797ec --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/PlayerRespawnPoint.java @@ -0,0 +1,107 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilPlayer; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; + +public class PlayerRespawnPoint +{ + private Player _owner; + private Location _loc; + + public PlayerRespawnPoint(Player owner, Location loc) + { + _owner = owner; + _loc = loc; + UtilPlayer.message(owner, F.main("Game", "You have set your bed respawn point. The next time you die you will respawn here!")); + } + + @SuppressWarnings("deprecation") + private boolean isBedType(Block bedBlock, boolean foot) + { + boolean head = (bedBlock.getData() & 0x8) != 0; + + if (foot) + return !head; + else + return head; + } + + private Block getOtherBedBlock(Block b1) + { + if (b1.getType() != Material.BED_BLOCK) + return null; + + boolean lookingForFoot = isBedType(b1, false); + + for (int x = -1; x <= 1; x++) + { + for (int z = -1; z <= 1; z++) + { + Block b2 = b1.getRelative(x, 0, z); + if (!(b1.getLocation().equals(b2.getLocation()))) + { + if (b2.getType().equals(Material.BED_BLOCK)) + { + if (lookingForFoot && isBedType(b2, true)) + return b2; + + if (!lookingForFoot && isBedType(b2, false)) + return b2; + } + } + } + } + return null; + } + + public boolean respawnPlayer() + { + if (_loc.getBlock().getType() != Material.BED_BLOCK) + { + UtilPlayer.message(_owner, F.main("Game", "Your bed has been destroyed, and your respawn point has been reset!")); + return false; + } + + _owner.teleport(_loc.clone().add(0.5, 1.5, 0.5)); + UtilPlayer.message(_owner, F.main("Game", "You have been respawned at your bed location!")); + + return true; + } + + public boolean breakBed(Block block) + { + boolean isOther = false; + + if (getOtherBedBlock(_loc.getBlock()) != null) + if (getOtherBedBlock(_loc.getBlock()).equals(block)) + isOther = true; + + if (block.getLocation().equals(_loc) || isOther) + { + UtilPlayer.message(_owner, F.main("Game", "Your bed respawn point has been broken!")); + return true; + } + return false; + } + + public void overWrite(Location newLocation) + { + if (newLocation.distance(_loc) <= .2) + return; + + if (getOtherBedBlock(_loc.getBlock()) != null) + if (getOtherBedBlock(_loc.getBlock()).getLocation().distance(newLocation) <= .2) + return; + + UtilPlayer.message(_owner, F.main("Game", "You have set your bed respawn point. The next time you die you will respawn here!")); + if (_loc.getBlock().getType() == Material.BED_BLOCK) + _loc.getBlock().breakNaturally(); + + _loc = newLocation; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/ProtectionUtil.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/ProtectionUtil.java new file mode 100644 index 000000000..65a2f2e85 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/ProtectionUtil.java @@ -0,0 +1,16 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import org.bukkit.block.Block; + +public class ProtectionUtil { + + public static boolean isSameBlock(Block a, Block b) + { + if (a.getX() == b.getX()) + if (a.getY() == b.getY()) + return (a.getZ() == b.getZ()); + + return false; + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/Spawner.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/Spawner.java new file mode 100644 index 000000000..f55764201 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/Spawner.java @@ -0,0 +1,114 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; + +public class Spawner +{ + protected MinecraftLeague Host; + private Location _spawnerBlock; + private EntityType _toSpawn; + private long _lastSpawned; + private boolean _canSpawn = true; + + @SuppressWarnings("deprecation") + public Spawner(MinecraftLeague host, Location spawnerBlock, EntityType toSpawn) + { + Host = host; + _spawnerBlock = spawnerBlock; + _toSpawn = toSpawn; + _lastSpawned = System.currentTimeMillis(); + spawnerBlock.getBlock().setTypeIdAndData(Material.MOB_SPAWNER.getId(), (byte)toSpawn.getTypeId(), false); + } + + private List getLocations(Location base, int changeX, int changeY, int changeZ) + { + List locs = new ArrayList(); + for(int x = (base.getBlockX() - changeX); x <= (base.getBlockX() + changeX); x++) + { + for(int y = (base.getBlockY() - changeY); y <= (base.getBlockY() + changeY); y++) + { + for(int z = (base.getBlockZ() - changeZ); z <= (base.getBlockZ() + changeZ); z++) + { + Location loc = new Location(base.getWorld(), x, y, z); + locs.add(loc); + } + } + } + + return locs; + } + + private boolean canSpawnMob(Location l) + { + Block b = l.getBlock(); + if ((b.getType() != Material.AIR) && !b.getType().toString().contains("WATER") && !UtilBlock.airFoliage(b)) + return false; + + Block b2 = b.getRelative(BlockFace.UP); + if ((b2.getType() != Material.AIR) && !b2.getType().toString().contains("WATER") && !UtilBlock.airFoliage(b2)) + return false; + + return true; + } + + private void spawn() + { + if (!_canSpawn) + return; + + List possible = getLocations(_spawnerBlock, 2, 1, 2); + boolean spawned = false; + int i = UtilMath.r(possible.size()); + while (!spawned) + { + Location l = possible.get(i); + if (canSpawnMob(l)) + { + Entity e = Host.getArcadeManager().GetCreature().SpawnEntity(l, _toSpawn); + UtilEnt.Vegetate(e); + spawned = true; + _lastSpawned = System.currentTimeMillis(); + continue; + } + + int newi = 0; + if (i == (possible.size() - 1)) + i = newi; + else + i++; + } + } + + public void update() + { + if (_spawnerBlock.getBlock().getType() != Material.MOB_SPAWNER) + _canSpawn = false; + else + _canSpawn = true; + + if (_canSpawn) + { + if (!UtilTime.elapsed(_lastSpawned, UtilTime.convert(10, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + _canSpawn = false; + else + _canSpawn = true; + } + + spawn(); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamBeacon.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamBeacon.java new file mode 100644 index 000000000..a67db3d51 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamBeacon.java @@ -0,0 +1,74 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.HashSet; + +import nautilus.game.arcade.game.GameTeam; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class TeamBeacon +{ + private GameTeam _team; + private Block _block; + //private Location _core; + + public TeamBeacon(GameTeam team, Block block/*, Location core*/) + { + _team = team; + _block = block; + //_core = core; + + _block.setType(Material.BEACON); + } + + /*public boolean isBlock(Block match) + { + if (match.getX() == _block.getX()) + if (match.getZ() == _block.getZ()) + if (match.getY() == _block.getY()) + return true; + + return false; + }*/ + + /*public Block getBlock() + { + return _block; + }*/ + + public void setBlock(Block block) + { + _block = block; + block.setType(Material.BEACON); + } + + public void update() + { + if (_block.getType() != Material.BEACON) + return; + + HashSet ignore = new HashSet(); + ignore.add(Material.GLASS); + ignore.add(Material.THIN_GLASS); + ignore.add(Material.STAINED_GLASS); + ignore.add(Material.STAINED_GLASS_PANE); + //Bukkit.broadcastMessage(UtilBlock.getHighest(_block.getWorld(), _block.getX(), _block.getZ(), ignore) + ""); + //if (!isBlock(UtilBlock.getHighest(_block.getWorld(), _block.getX(), _block.getZ(), ignore).getRelative(BlockFace.DOWN))) + //return; + + for (Player player : _team.GetPlayers(true)) + { + if (player.getLocation().distance(_block.getLocation()) < 15) + { + player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 5 * 20, 0)); + //player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 5 * 20, 0)); + player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 5 * 20, 0)); + //player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 5 * 20, 0)); + } + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamCrystal.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamCrystal.java new file mode 100644 index 000000000..afea34d7e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamCrystal.java @@ -0,0 +1,14 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Location; + +public class TeamCrystal extends TeamTowerBase +{ + public TeamCrystal(MinecraftLeague host, TowerManager manager, GameTeam team, Location spawn) + { + super(host, manager, team, spawn); + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTower.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTower.java new file mode 100644 index 000000000..3fab4b528 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTower.java @@ -0,0 +1,17 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Location; + +public class TeamTower extends TeamTowerBase +{ + public Integer Number; + + public TeamTower(MinecraftLeague host, TowerManager manager, GameTeam team, Location spawn, Integer number) + { + super(host, manager, team, spawn); + Number = number; + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTowerBase.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTowerBase.java new file mode 100644 index 000000000..5eff66a55 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TeamTowerBase.java @@ -0,0 +1,312 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.ArrayList; +import java.util.List; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.hologram.Hologram; +import mineplex.core.recharge.Recharge; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.DataLoc; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.EnderCrystal; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wither; +import org.bukkit.util.Vector; + +public abstract class TeamTowerBase +{ + private MinecraftLeague _host; + private TowerManager _manager; + private Location _spawn; + private GameTeam _team; + private Double _health, _maxHealth; + private EnderCrystal _entity; + private Hologram _name, _healthTag; + private String _type; + public boolean Alive; + public boolean Vulnerable; + + public TeamTowerBase(MinecraftLeague host, TowerManager manager, GameTeam team, Location spawn) + { + _host = host; + _manager = manager; + _spawn = spawn.clone().add(0, 3.2, 0); + _team = team; + _maxHealth = 11111D; + _health = 11111D; + _type = "Tower"; + if (this instanceof TeamCrystal) + _type = "Core"; + _name = new Hologram(_host.getArcadeManager().getHologramManager(), _spawn.clone().add(1, 3, 0), team.GetColor() + team.getDisplayName() + "'s " + _type); + _healthTag = new Hologram(_host.getArcadeManager().getHologramManager(), _spawn.clone().add(1, 2, 0), formatHealth(_health)); + + spawn(); + } + + private void spawn() + { + _name.start(); + _healthTag.start(); + _entity = (EnderCrystal) _host.getArcadeManager().GetCreature().SpawnEntity(_spawn, EntityType.ENDER_CRYSTAL); + _health = _maxHealth; + Alive = true; + } + + private void kill(Player player) + { + String message = ""; + if (player != null) + message = _host.GetTeam(player).GetColor() + player.getName() + _team.GetColor() + " has destroyed " + _team.getDisplayName() + "'s " + _type + "!"; + else + message = _team.GetColor() + _team.getDisplayName() + "'s " + _type + " has been destroyed!"; + + //Bukkit.broadcastMessage(message); + UtilTextMiddle.display("", message); + + if (!_type.equalsIgnoreCase("Tower")) + { + for (Player inform : _team.GetPlayers(true)) + UtilTextMiddle.display(C.cGold + "Team Crystal Destroyed", C.cGold + "You will no longer respawn and will be poisoned in 5 minutes!", inform); + } + + Alive = false; + _entity.remove(); + _healthTag.stop(); + _name.stop(); + Bukkit.getScheduler().runTaskLater(_host.Manager.getPlugin(), new Runnable() + { + public void run() + { + playDeathAnimation(_spawn); + } + }, 20 * 5); + detonate(); + _manager.handleTowerDeath(this); + } + + private void playDeathAnimation(Location loc) + { + _spawn.getWorld().playSound(loc, Sound.EXPLODE, 10, 0); + //GFX subject to change + Location loc1 = loc.clone().add(-2, 3, -2); + Location loc2 = loc.clone().add(2, 0, 2); + Location loc3 = loc.clone().add(2, 3, 2); + Location loc4 = loc.clone().add(-2, 0, -2); + Location particle1 = loc2.clone(); + Location particle2 = loc4.clone(); + while (UtilMath.offset(loc1, loc) >= UtilMath.offset(particle1, loc)) + { + Vector v = UtilAlg.getTrajectory(particle1, loc1); + //UtilParticle.PlayParticle(ParticleType.LARGE_EXPLODE, particle, v, 0, 1, ViewDist.NORMAL, UtilServer.getPlayers()); + UtilParticle.PlayParticle(ParticleType.FIREWORKS_SPARK, particle1, v, 0, 5, ViewDist.MAX, UtilServer.getPlayers()); + particle1.add(v); + } + while (UtilMath.offset(loc3, loc) >= UtilMath.offset(particle2, loc)) + { + Vector v = UtilAlg.getTrajectory(particle2, loc3); + UtilParticle.PlayParticle(ParticleType.FIREWORKS_SPARK, particle2, v, 0, 5, ViewDist.MAX, UtilServer.getPlayers()); + particle2.add(v); + } + } + + private void detonate() + { + UtilParticle.PlayParticleToAll(ParticleType.LARGE_EXPLODE, _spawn, null, 0, 2, ViewDist.NORMAL); + _spawn.getWorld().playSound(_spawn, Sound.EXPLODE, 10, 0); + List blocks = new ArrayList(); + Location bottom = _spawn.clone().subtract(0, -3.2, 0); + for (int i = 0; i < 23; i++) + { + blocks.addAll(UtilBlock.getInSquare(bottom.clone().add(0, i, 0).getBlock(), 4)); + } + for (int i = 0; i < 3; i++) + { + getBeacon().clone().add(0, i, 0).getBlock().setType(Material.BEDROCK); + } + _host.Manager.GetExplosion().BlockExplosion(blocks, _spawn, false, true); + for (Entity e : _host.WorldData.World.getEntities()) + { + if (e instanceof Wither) + { + LivingEntity le = (LivingEntity) e; + le.setHealth(le.getHealth() / 2); + } + } + for (LivingEntity le : UtilEnt.getInRadius(_spawn, 5).keySet()) + { + if (UtilMath.offset(le.getLocation(), _spawn) <= 5) + { + if (UtilPlayer.isSpectator(le)) + continue; + if (le instanceof Player) + { + _host.storeGear((Player)le); + } + le.damage(6); + } + } + } + + public Location getBeacon() + { + Location ret = null; + for (Location loc : _host.WorldData.GetDataLocs(DataLoc.BEACON.getKey())) + { + if (ret == null || UtilMath.offset(ret, _spawn) > UtilMath.offset(loc, _spawn)) + ret = loc; + } + + return ret; + } + + public Entity getEntity() + { + return _entity; + } + + public boolean isEntity(Entity e) + { + return e.getEntityId() == _entity.getEntityId(); + } + + public boolean canDamage(Player player) + { + if (UtilPlayer.isSpectator(player)) + return false; + + if (_host.GetTeam(player) == _team) + return false; + + if (!_host.IsPlaying(player)) + return false; + + if (!Recharge.Instance.usable(player, "Damage TeamTower")) + return false; + + return true; + } + + public Double getHealth() + { + if (!Alive) + return 0D; + + return _health; + } + + public String formatHealth(Double healthNumber) + { + String tag = healthNumber.toString(); + + if (healthNumber > (.9 * _maxHealth)) + tag = C.cGreen + tag; + else if (healthNumber < (.45 * _maxHealth)) + tag = C.cRed + tag; + else + tag = C.cYellow + tag; + + return tag; + } + + public ChatColor getHealthColor() + { + if (!Alive) + return ChatColor.GRAY; + + ChatColor color = ChatColor.YELLOW; + + if (_health > (.9 * _maxHealth)) + color = ChatColor.GREEN; + else if (_health < (.45 * _maxHealth)) + color = ChatColor.RED; + + return color; + } + + public boolean damage(double damage, Player player) + { + if (!Vulnerable) + return false; + + Double newHealth = Math.max(_health - damage, 0); + + if (newHealth == 0) + { + kill(player); + return true; + } + + _health = newHealth; + if (player != null) + Recharge.Instance.use(player, "Damage TeamTower", 400, false, false); + return false; + } + + public Location getLocation() + { + return _spawn; + } + + public GameTeam getTeam() + { + return _team; + } + + public void update() + { + _healthTag.setText(formatHealth(_health)); + + if (Alive) + { + if (_entity.isDead() || !_entity.isValid()) + { + _entity = (EnderCrystal) _host.getArcadeManager().GetCreature().SpawnEntity(_spawn, EntityType.ENDER_CRYSTAL); + } + + if (_health > _maxHealth) + { + _health = _maxHealth; + } + } + } + + public void setMaxHealth(Double health) + { + _maxHealth = Math.abs(health); + } + + public void setVulnerable(boolean vulnerable) + { + if (vulnerable) + { + getBeacon().getBlock().setType(Material.BEACON); + Vulnerable = vulnerable; + } + else + { + getBeacon().getBlock().setType(Material.BEDROCK); + Vulnerable = vulnerable; + } + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerAlert.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerAlert.java new file mode 100644 index 000000000..eafdc46df --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerAlert.java @@ -0,0 +1,70 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import nautilus.game.arcade.game.GameTeam; + +import org.bukkit.Instrument; +import org.bukkit.Note; +import org.bukkit.Note.Tone; +import org.bukkit.entity.Player; + +public class TowerAlert +{ + private ConcurrentHashMap _alerts = new ConcurrentHashMap(); + //private ConcurrentHashMap _alertType = new ConcurrentHashMap(); + + public void alert(GameTeam team, TeamTowerBase tower) + { + if (!UtilTime.elapsed(_alerts.getOrDefault(team, (long) 1), UtilTime.convert(7, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + for (Player player : team.GetPlayers(true)) + playSound(player); + + return; + } + + _alerts.put(team, System.currentTimeMillis()); + + String type = ""; + if (tower instanceof TeamTower) + { + int number = ((TeamTower)tower).Number; + if (number == 1) + /*_alertType.put(team, */type = "First Tower";//); + else + /*_alertType.put(team, */type = "Second Tower";//); + } + else + /*_alertType.put(team, */type = "Crystal";//); + + showAlert(team, type); + } + + private void showAlert(GameTeam team, String type) + { + /*for (GameTeam team : _alerts.keySet()) + {*/ + for (Player player : team.GetPlayers(true)) + { + UtilTextMiddle.display("", C.cGold + "Your " + /*_alertType.get(team)*/type + " is under attack!", 0, 20 * 5, 0, player); + playSound(player); + } + + /*if (UtilTime.elapsed(_alerts.get(team), UtilTime.convert(5, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _alerts.remove(team); + _alertType.remove(team); + }*/ + //} + } + + private void playSound(Player player) + { + player.playNote(player.getLocation(), Instrument.PIANO, Note.sharp(1, Tone.A)); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerManager.java new file mode 100644 index 000000000..4ab0a41fa --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/TowerManager.java @@ -0,0 +1,307 @@ +package nautilus.game.arcade.game.games.minecraftleague.data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.itemstack.ItemBuilder; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.DataLoc; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.world.WorldData; + +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; + +public class TowerManager implements Listener +{ + public MinecraftLeague Host; + private ConcurrentHashMap _towers = new ConcurrentHashMap(); + private ConcurrentHashMap _vulnerableTower = new ConcurrentHashMap(); + private ConcurrentHashMap _def = new ConcurrentHashMap(); + //private ConcurrentHashMap _mapZone = new ConcurrentHashMap(); + private ConcurrentHashMap _beacons = new ConcurrentHashMap(); + private OreGenerator _ore; + public boolean Attack = false; + + public TowerManager(MinecraftLeague host) + { + Host = host; + _ore = new OreGenerator(); + } + + private void makeVulnerable(TeamTowerBase base) + { + if (base instanceof TeamTower) + _vulnerableTower.put(base.getTeam(), ((TeamTower)base).Number); + else + _vulnerableTower.put(base.getTeam(), 3); + + base.Vulnerable = true; + _beacons.get(base.getTeam()).setBlock(base.getBeacon().getBlock()); + } + + public void ironOreGen(GameTeam team, boolean start) + { + int amount = 20; + if (start) + amount = 50; + + for (Location loc : Host.WorldData.GetCustomLocs(DataLoc.DIAMOND_ORE.getKey())) + { + loc.getBlock().setType(Material.DIAMOND_ORE); + } + + if (start) + { + if (team.GetColor() == ChatColor.RED) + _ore.generateOre(Material.IRON_ORE, Host.WorldData.GetCustomLocs(DataLoc.RED_ORE.getKey()), amount); + else + _ore.generateOre(Material.IRON_ORE, Host.WorldData.GetCustomLocs(DataLoc.BLUE_ORE.getKey()), amount); + + for (Location loc : Host.WorldData.GetCustomLocs(DataLoc.MOSH_IRON.getKey())) + { + loc.getBlock().setType(Material.STONE); + } + } + else + { + _ore.generateOre(Material.IRON_ORE, Host.WorldData.GetCustomLocs(DataLoc.MOSH_IRON.getKey()), amount); + UtilTextMiddle.display("", "Valuable Ores have respawned in the middle!"); + } + } + + private List getAllTeamTowers(GameTeam team) + { + List ret = new ArrayList(); + + for (TeamTowerBase tower : _towers.keySet()) + { + if (_towers.get(tower).GetColor() == team.GetColor()) + { + ret.add(tower); + } + } + + return ret; + } + + public LinkedList getTeamTowers(GameTeam team) + { + LinkedList ret = new LinkedList(); + TeamTower one = null; + TeamTower two = null; + TeamCrystal three = null; + + for (TeamTowerBase tower : getAllTeamTowers(team)) + { + if (tower instanceof TeamCrystal) + { + three = (TeamCrystal) tower; + continue; + } + if (one == null) + { + one = (TeamTower) tower; + continue; + } + if (one.Number > ((TeamTower)tower).Number) + { + two = one; + one = (TeamTower) tower; + continue; + } + two = (TeamTower) tower; + } + + ret.add(one); + ret.add(two); + ret.add(three); + + return ret; + } + + public Integer getAmountAlive(GameTeam team) + { + int i = 0; + + for (TeamTowerBase tower : getAllTeamTowers(team)) + { + if (tower.Alive) + i++; + } + + return i; + } + + public TeamTowerBase getVulnerable(GameTeam team) + { + return getTeamTowers(team).get(_vulnerableTower.get(team) - 1); + } + + public void parseTowers(WorldData data) + { + GameTeam red = Host.GetTeam(ChatColor.RED); + GameTeam blue = Host.GetTeam(ChatColor.AQUA); + //int[] redRGB = new int[] {255, 0, 0}; + //int[] blueRGB = new int[] {0, 0, 255}; + + _towers.put(new TeamTower(Host, this, red, data.GetCustomLocs(DataLoc.RED_TOWER.getKey() + " 1").get(0), 1), red); + _towers.put(new TeamTower(Host, this, red, data.GetCustomLocs(DataLoc.RED_TOWER.getKey() + " 2").get(0), 2), red); + _towers.put(new TeamCrystal(Host, this, red, data.GetCustomLocs(DataLoc.RED_CRYSTAL.getKey()).get(0)), red); + + _towers.put(new TeamTower(Host, this, blue, data.GetCustomLocs(DataLoc.BLUE_TOWER.getKey() + " 1").get(0), 1), blue); + _towers.put(new TeamTower(Host, this, blue, data.GetCustomLocs(DataLoc.BLUE_TOWER.getKey() + " 2").get(0), 2), blue); + _towers.put(new TeamCrystal(Host, this, blue, data.GetCustomLocs(DataLoc.BLUE_CRYSTAL.getKey()).get(0)), blue); + + for (TeamTowerBase tower : _towers.keySet()) + { + _def.put(tower, new DefenderAI(this, tower)); + /*int[] rgb; + if (tower.getTeam().GetColor() == red.GetColor()) + rgb = redRGB; + else + rgb = blueRGB; + + MapZone zone = new MapZone(tower.getLocation(), rgb); + Host.MapZones.add(zone); + _mapZone.put(tower, zone);*/ + } + + TeamBeacon redb = new TeamBeacon(red, getTeamTowers(red).getFirst().getBeacon().getBlock()); + _beacons.put(red, redb); + Host.Beacons.put(red, redb); + TeamBeacon blueb = new TeamBeacon(blue, getTeamTowers(blue).getFirst().getBeacon().getBlock()); + _beacons.put(blue, blueb); + Host.Beacons.put(blue, blueb); + makeVulnerable(getTeamTowers(red).getFirst()); + makeVulnerable(getTeamTowers(blue).getFirst()); + ironOreGen(red, true); + ironOreGen(blue, true); + } + + public void prepareHealth(int players, double multiplier) + { + for (TeamTowerBase tower : _towers.keySet()) + { + if (tower instanceof TeamCrystal) + tower.setMaxHealth(players * multiplier); + else + { + int divisor = 3 - ((TeamTower)tower).Number; + double rawHealth = (.67 * multiplier) * players; + Double health = new BigDecimal(rawHealth / divisor).intValue() * 1D; + tower.setMaxHealth(health); + } + } + } + + public void handleTowerDeath(TeamTowerBase towerBase) + { + towerBase.setVulnerable(false); + //ironOreGen(towerBase.getTeam()); + /*for (Player player : towerBase.getTeam().GetPlayers(true)) + { + player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20 * 60, 1)); + }*/ + /*Bukkit.getScheduler().runTaskLater(Host.Manager.getPlugin(), new Runnable() + { + public void run() + { + UtilTextMiddle.display("", towerBase.getTeam().GetColor() + towerBase.getTeam().GetName() + " Team ores have been replenished!", UtilServer.getPlayers()); + } + }, 20 * 5);*/ + //_mapZone.get(towerBase).setValid(false); + if (towerBase instanceof TeamCrystal) + { + GameTeam enemy = null; + if (towerBase.getTeam() == Host.GetTeam(ChatColor.RED)) + enemy = Host.GetTeam(ChatColor.AQUA); + else + enemy = Host.GetTeam(ChatColor.RED); + + Host.ScoreboardAutoWrite = false; + Host.writeEndSb(enemy.GetColor() + enemy.getDisplayName()); + Host.AnnounceEnd(enemy); + + for (GameTeam team : Host.GetTeamList()) + { + if (enemy != null && team.equals(enemy)) + { + for (Player player : team.GetPlayers(false)) + Host.AddGems(player, 10, "Winning Team", false, false); + } + + for (Player player : team.GetPlayers(false)) + if (player.isOnline()) + Host.AddGems(player, 10, "Participation", false, false); + } + Host.SetState(GameState.End); + + //Host.Objective.setTeamObjective(enemy, new KillObjective()); + + //Host.TeamPoison.put(towerBase.getTeam(), System.currentTimeMillis() + (UtilTime.convert(5, TimeUnit.MINUTES, TimeUnit.MILLISECONDS) - UtilTime.convert(1, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))); + + return; + } + for (Player player : towerBase.getTeam().GetPlayers(true)) + { + if (!UtilPlayer.isSpectator(player)) + { + boolean replaced = false; + if (UtilItem.isLeatherProduct(player.getInventory().getHelmet())) + { + if (replaced) + continue; + replaced = true; + player.getInventory().setHelmet(new ItemBuilder(Material.GOLD_HELMET).setUnbreakable(true).build()); + } + if (UtilItem.isLeatherProduct(player.getInventory().getLeggings())) + { + if (replaced) + continue; + replaced = true; + player.getInventory().setLeggings(new ItemBuilder(Material.GOLD_LEGGINGS).setUnbreakable(true).build()); + } + if (UtilItem.isLeatherProduct(player.getInventory().getChestplate())) + { + if (replaced) + continue; + replaced = true; + player.getInventory().setChestplate(new ItemBuilder(Material.GOLD_CHESTPLATE).setUnbreakable(true).build()); + } + if (UtilItem.isLeatherProduct(player.getInventory().getBoots())) + { + if (replaced) + continue; + replaced = true; + player.getInventory().setBoots(new ItemBuilder(Material.GOLD_BOOTS).setUnbreakable(true).build()); + } + } + } + makeVulnerable(getTeamTowers(towerBase.getTeam()).get(_vulnerableTower.get(towerBase.getTeam()))); + } + + public void toggleAttack() + { + //Attack = !Attack; + } + + public void update() + { + for (TeamTowerBase tower : _towers.keySet()) + { + tower.update(); + _def.get(tower).update(); + } + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapManager.java new file mode 100644 index 000000000..0a077c627 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapManager.java @@ -0,0 +1,673 @@ +package nautilus.game.arcade.game.games.minecraftleague.data.map; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilServer; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import net.minecraft.server.v1_8_R3.Block; +import net.minecraft.server.v1_8_R3.BlockPosition; +import net.minecraft.server.v1_8_R3.Blocks; +import net.minecraft.server.v1_8_R3.IBlockData; +import net.minecraft.server.v1_8_R3.MaterialMapColor; +import net.minecraft.server.v1_8_R3.PersistentCollection; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.craftbukkit.v1_8_R3.CraftChunk; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; + +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Iterables; +import com.google.common.collect.Multisets; + +public class ItemMapManager /*extends MiniPlugin*/ implements Listener +{ + private MinecraftLeague _host; + + private int _blocksScan = 16; + private Comparator> _comparator; + private int _halfMapSize; + private int[][] _heightMap; + private boolean _loadWorld = true; + private HashMap _map = new HashMap(); + private short _mapId = (short) UtilMath.r(Short.MAX_VALUE); + private ArrayList> _scanList = new ArrayList>(); + private World _world; + private int _centerX; + private int _centerZ; + private int _scale; + + public ItemMapManager(MinecraftLeague host, World world, int minX, int minZ, int maxX, int maxZ) + { + //super("ItemMapManager", host.getArcadeManager().getPlugin()); + Bukkit.getPluginManager().registerEvents(this, host.getArcadeManager().getPlugin()); + + _host = host; + + _centerX = minX + ((maxX - minX) / 2); + _centerZ = minZ + ((maxZ - minZ) / 2); + _centerX = (int) (Math.round(_centerX / 16D) * 16); + _centerZ = (int) (Math.round(_centerZ / 16D) * 16); + + _halfMapSize = (int) (Math.ceil(Math.max((maxX - minX) / 2D, (maxZ - minZ) / 2D) / 16D) * 16); + + ArrayList> list = new ArrayList>(); + + for (int scale = 1; scale <= 16; scale++) + { + int s = _halfMapSize; + + if ((s / scale) > 127) + continue; + + while (s < 10000 && (s % 16 != 0 || s % scale != 0)) + { + s += 16; + } + + if (s < 10000) + { + list.add(new HashMap.SimpleEntry(scale, s)); + } + } + + if (list.isEmpty()) + { + _scale = 16; + _halfMapSize = 127 * 8; + } + else + { + Collections.sort(list, new Comparator>() + { + + @Override + public int compare(Entry o1, Entry o2) + { + return Integer.compare(o1.getValue(), o2.getValue()); + } + }); + + _scale = list.get(0).getKey(); + _halfMapSize = list.get(0).getValue(); + + System.out.print( + "Using scale " + _scale + ", Size: " + _halfMapSize + ", CenterX: " + _centerX + ", CenterZ: " + _centerZ); + } + + _heightMap = new int[(_halfMapSize * 2) + 16][]; + + _comparator = new Comparator>() + { + + @Override + public int compare(Entry o1, Entry o2) + { + // Render the places outside the map first to speed up visual errors fixing + int outsideMap = Boolean.compare(o1.getValue() < -_halfMapSize, o2.getValue() < -_halfMapSize); + + if (outsideMap != 0) + { + return -outsideMap; + } + + double dist1 = 0; + double dist2 = 0; + + for (Player player : UtilServer.getPlayers()) + { + dist1 += getDistance(o1, player.getLocation().getX(), player.getLocation().getZ()); + dist2 += getDistance(o2, player.getLocation().getX(), player.getLocation().getZ()); + } + + if (dist1 != dist2) + { + return Double.compare(dist1, dist2); + } + + dist1 = getDistance(o1, 0, 0); + dist2 = getDistance(o2, 0, 0); + + return Double.compare(dist1, dist2); + + } + }; + + for (int x = -_halfMapSize; x < _halfMapSize; x += _blocksScan) + { + for (int z = -_halfMapSize - 16; z < _halfMapSize; z += (z < -_halfMapSize ? 16 : _blocksScan)) + { + _scanList.add(new HashMap.SimpleEntry(x, z)); + } + } + + for (int s = 1; s <= 2; s++) + { + if (s == 2) + { + s = getScale(); + + if (s == 1) + break; + } + + int size = (_halfMapSize * 2) / s; + Byte[][] bytes = new Byte[size][]; + + for (int i = 0; i < size; i++) + { + bytes[i] = new Byte[size]; + } + + _map.put(s, bytes); + } + + for (int i = 0; i < _heightMap.length; i++) + { + _heightMap[i] = new int[_heightMap.length]; + } + + _world = world; + + try + { + File foundFile = null; + + for (File f : new File("world/data").listFiles()) + { + if (f.getName().startsWith("map_")) + { + foundFile = f; + break; + } + } + + if (foundFile == null) + { + PersistentCollection collection = ((CraftWorld) _world).getHandle().worldMaps; + Field f = collection.getClass().getDeclaredField("d"); + f.setAccessible(true); + ((HashMap) f.get(collection)).put("map", (short) 0); + } + + MapView view = Bukkit.createMap(_world); + _mapId = view.getId(); + setupRenderer(view); + + for (int i = 0; i < 100; i++) + { + setupRenderer(Bukkit.createMap(_world));// Ensures the following 100 maps are unused + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + rebuildScan(); + } + + private void setupRenderer(MapView view) + { + for (MapRenderer renderer : view.getRenderers()) + { + view.removeRenderer(renderer); + } + + view.addRenderer(new ItemMapRenderer(this, _host)); + } + + public int getScale() + { + return _scale; + } + + public int getX() + { + return _centerX; + } + + public int getZ() + { + return _centerZ; + } + + /** + * Get the center of the map. + */ + public int calcMapCenter(int zoom, int cord) + { + int mapSize = _halfMapSize / zoom; // This is how large the map is in pixels + + int mapCord = cord / zoom; // This is pixels from true center of map, not held map + + int fDiff = mapSize - -mapCord; + int sDiff = mapSize - mapCord; + + double chunkBlock = cord & 0xF; + cord -= chunkBlock; + chunkBlock /= zoom; + + /*if ((fDiff < 64 || sDiff < 64) && (Math.abs(fDiff - sDiff) > 1)) + { + cord += (fDiff > sDiff ? Math.floor(chunkBlock) : Math.ceil(chunkBlock)); + } + else*/ + { + cord += (int) Math.floor(chunkBlock) * zoom; + } + + while ((fDiff < 64 || sDiff < 64) && (Math.abs(fDiff - sDiff) > 1)) + { + int change = (fDiff > sDiff ? -zoom : zoom); + cord += change; + + mapCord = cord / zoom; + + fDiff = mapSize - -mapCord; + sDiff = mapSize - mapCord; + } + + return cord; + } + + private void colorWorldHeight(int zoom, int startingX, int startingZ) + { + if (zoom == 0) + zoom = 1; + + Byte[][] map = _map.get(zoom); + + for (int x = startingX; x < startingX + _blocksScan; x += zoom) + { + double d0 = 0; + + // Prevents ugly lines for the first line of Z + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int hX = x + addX + _halfMapSize; + int hZ = (startingZ - zoom) + addZ + _halfMapSize; + + if (hX >= _halfMapSize * 2 || hZ >= _halfMapSize * 2) + { + continue; + } + + d0 += _heightMap[hX + 16][hZ + 16] / (zoom * zoom); + } + } + + for (int z = startingZ; z < startingZ + _blocksScan; z += zoom) + { + // Water depth colors not included + double d1 = 0; + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int hX = x + addX + _halfMapSize; + int hZ = z + addZ + _halfMapSize; + + if (hX >= _halfMapSize * 2 || hZ >= _halfMapSize * 2) + { + continue; + } + + d1 += _heightMap[hX + 16][hZ + 16] / (zoom * zoom); + } + } + + double d2 = (d1 - d0) * 4.0D / (zoom + 4) + ((x + z & 0x1) - 0.5D) * 0.4D; + byte b0 = 1; + + d0 = d1; + + if (d2 > 0.6D) + { + b0 = 2; + } + else if (d2 > 1.2D) + { + b0 = 3; + } + else if (d2 < -0.6D) + { + b0 = 0; + } + + int origColor = map[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] - 1; + + /*if (color < 4) + { + d2 = waterDepth * 0.1D + (k1 + j2 & 0x1) * 0.2D; + b0 = 1; + if (d2 < 0.5D) + { + b0 = 2; + } + + if (d2 > 0.9D) + { + b0 = 0; + } + }*/ + + byte color = (byte) (origColor + b0); + map[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] = color; + } + } + } + + private void drawWorldScale(int zoom, int startingX, int startingZ) + { + Byte[][] first = _map.get(1); + Byte[][] second = _map.get(zoom); + + for (int x = startingX; x < startingX + _blocksScan; x += zoom) + { + for (int z = startingZ; z < startingZ + _blocksScan; z += zoom) + { + HashMultiset hashmultiset = HashMultiset.create(); + + for (int addX = 0; addX < zoom; addX++) + { + for (int addZ = 0; addZ < zoom; addZ++) + { + int pX = x + addX + _halfMapSize; + int pZ = z + addZ + _halfMapSize; + + if (pX >= first.length || pZ >= first.length) + { + continue; + } + + Byte b = first[pX][pZ]; + + if (b == null) + continue; + + hashmultiset.add(b); + } + } + + Byte color = Iterables.getFirst(Multisets.copyHighestCountFirst(hashmultiset), (byte) 0); + + second[(x + _halfMapSize) / zoom][(z + _halfMapSize) / zoom] = color; + } + } + } + + private double getDistance(double x1, double z1, double x2, double z2) + { + x1 = (x1 - x2); + z1 = (z1 - z2); + + return (x1 * x1) + (z1 * z1); + } + + private double getDistance(Entry entry, double x1, double z1) + { + return getDistance(x1 + _centerX, z1 + _centerZ, entry.getKey() + (_blocksScan / 2), + entry.getValue() + (_blocksScan / 2)); + } + + public Byte[][] getMap(int scale) + { + return _map.get(scale); + } + + public int getMapSize() + { + return _halfMapSize; + } + + /*@EventHandler + public void onServerTransfer(ServerTransferEvent event) + { + Player p = event.getPlayer(); + + p.sendMessage(C.cDRed + C.Bold + "WARNING!"); + p.sendMessage(C.cYellow + "There's a bug where switching servers may freeze the Team Map!"); + p.sendMessage(C.cYellow + "If you want to play Minecraft League again and this error occurs, rejoin the Mineplex server!"); + }*/ + + private void rebuildScan() + { + for (int x = -_halfMapSize; x < _halfMapSize; x += _blocksScan) + { + for (int z = -_halfMapSize - 16; z < _halfMapSize; z += (z < -_halfMapSize ? 16 : _blocksScan)) + { + _scanList.add(new HashMap.SimpleEntry(x, z)); + } + } + + if (!_loadWorld) + { + Iterator> itel = _scanList.iterator(); + + while (itel.hasNext()) + { + Entry entry = itel.next(); + boolean removeEntry = true; + + for (Player player : UtilServer.getPlayers()) + { + if (Math.sqrt(getDistance(entry, player.getLocation().getX(), player.getLocation().getZ())) < 200) + { + removeEntry = false; + break; + } + } + + if (removeEntry) + { + itel.remove(); + } + } + } + + Collections.sort(_scanList, _comparator); + } + + @EventHandler + public void renderMap(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTEST) + return; + + if (_scanList.isEmpty()) + { + if (_loadWorld) + { + _loadWorld = false; + System.out.print("Finished first map scan and render"); + } + + if (UtilServer.getPlayers().length == 0) + return; + + rebuildScan(); + } + else if (_scanList.size() % 20 == 0) + { + Collections.sort(_scanList, _comparator); + } + + Entry entry = _scanList.remove(0); + + int startingX = entry.getKey(); + int startingZ = entry.getValue(); + + boolean outsideMap = startingZ < -_halfMapSize; + + scanWorldMap(startingX, startingZ, !outsideMap); + + if (outsideMap) + { + return; + } + + for (int s = 1; s <= 2; s++) + { + if (s == 2) + { + s = getScale(); + + if (s == 1) + break; + } + + if (s == 13 && _loadWorld) + continue; + + if (!outsideMap) + { + drawWorldScale(s, startingX, startingZ); + } + + colorWorldHeight(s, startingX, startingZ); + } + + colorWorldHeight(0, startingX, startingZ); + } + + public void scanWorldMap(int startingX, int startingZ, boolean setColors) + { + Byte[][] map = _map.get(1); + + for (int beginX = startingX; beginX < startingX + _blocksScan; beginX += 16) + { + for (int beginZ = startingZ - (startingZ > -_halfMapSize ? 16 : 0); beginZ < startingZ + + (setColors ? _blocksScan : 16); beginZ += 16) + { + Chunk chunk = _world.getChunkAt((beginX + _centerX) / 16, (beginZ + _centerZ) / 16); + boolean loaded = false; + + if (!chunk.isLoaded()) + { + if (_loadWorld) + { + loaded = chunk.load(); + } + else + { + continue; + } + } + + net.minecraft.server.v1_8_R3.Chunk nmsChunk = ((CraftChunk) chunk).getHandle(); + + for (int x = beginX; x < beginX + 16; x++) + { + for (int z = beginZ; z < beginZ + 16; z++) + { + int color = 0; + + if (!nmsChunk.isEmpty()) + { + int k3 = x & 0xF; + int l3 = z & 0xF; + + int l4 = nmsChunk.b(k3, l3) + 1; + IBlockData iblockdata = Blocks.AIR.getBlockData(); + + if (l4 > 1) + { + do + { + l4--; + iblockdata = nmsChunk.getBlockData(new BlockPosition(k3, l4, l3)); + } + while (iblockdata.getBlock().g(iblockdata) == MaterialMapColor.b && (l4 > 0)); + + if ((l4 > 0) && (iblockdata.getBlock().getMaterial().isLiquid())) + { + int j5 = l4 - 1; + Block block1; + do + { + block1 = nmsChunk.getType(new BlockPosition(k3, j5--, l3)); + } + while ((j5 > 0) && (block1.getMaterial().isLiquid())); + } + } + + _heightMap[x + _halfMapSize + 16][z + _halfMapSize + 16] = l4; + + if (setColors) + { + // color = block.f(i5).M; + IBlockData data = nmsChunk.getBlockData(new BlockPosition(k3, l4, l3)); + color = data.getBlock().g(data).M; + + color = (byte) ((color * 4) + 1); + } + } + + if (setColors && beginZ >= startingZ) + { + map[x + _halfMapSize][z + _halfMapSize] = (byte) color; + } + } + + if (loaded) + { + chunk.unload(); + } + } + } + } + } + + public void setMap(Player player) + { + for (ItemStack item : UtilInv.getItems(player)) + { + if (item.getType() == Material.MAP && item.getDurability() == _mapId) + { + return; + } + } + + ItemStack item = new ItemBuilder(Material.MAP, 1, _mapId).setTitle("Team Map").build(); + + int slot = player.getInventory().firstEmpty(); + + if (slot >= 0) + { + ItemStack mapSlot = player.getInventory().getItem(8); + + if (mapSlot == null || mapSlot.getType() == Material.AIR) + { + slot = 8; + } + + player.getInventory().setItem(slot, item); + } + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapRenderer.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapRenderer.java new file mode 100644 index 000000000..e161d0583 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/map/ItemMapRenderer.java @@ -0,0 +1,161 @@ +package nautilus.game.arcade.game.games.minecraftleague.data.map; + +import mineplex.core.recharge.Recharge; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.game.games.minecraftleague.data.MapZone; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.map.MapCanvas; +import org.bukkit.map.MapCursor; +import org.bukkit.map.MapCursorCollection; +import org.bukkit.map.MapPalette; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; + +public class ItemMapRenderer extends MapRenderer +{ + private ItemMapManager _manager; + private MinecraftLeague _host; + + public ItemMapRenderer(ItemMapManager itemMapManager, MinecraftLeague host) + { + super(true); + + _manager = itemMapManager; + _host = host; + } + + @Override + public void render(MapView mapView, MapCanvas canvas, Player player) + { + int zoom = _manager.getScale(); + + Byte[][] map = _manager.getMap(zoom); + + int centerX = 0; + int centerZ = 0; + + // We have this cooldown to squeeze out every single bit of performance from the server. + if (Recharge.Instance.use(player, "Draw Map", 4000, false, false)) + { + for (int mapX = 0; mapX < 128; mapX++) + { + for (int mapZ = 0; mapZ < 128; mapZ++) + { + int blockX = centerX + (mapX - 64); + int blockZ = centerZ + (mapZ - 64); + + int pixelX = blockX + (map.length / 2); + int pixelZ = blockZ + (map.length / 2); + + Byte color; + + if (!(pixelX < 0 || pixelZ < 0 || pixelX >= map.length || pixelZ >= map.length) + && map[pixelX][pixelZ] != null) + { + color = map[pixelX][pixelZ]; + + blockX *= zoom; + blockZ *= zoom; + } + else + { + color = (byte) 0; + } + + for (MapZone od : _host.MapZones) + { + if (od.isInRadius(blockX, blockZ)) // TODO Some math to figure out if this pixel is going to be colored in for the circle or not. + { + if (od.isValid()) + color = MapPalette.matchColor(od.getRed(), od.getGreen(), od.getBlue()); + } + + /*if (od.isBase(blockX - 20, blockZ + 15)) + { + color = MapPalette.matchColor(Color.PINK); + Bukkit.broadcastMessage("X:" + blockX + " Z:" + blockZ + "/" + od.getBase()); + }*/ + } + + canvas.setPixel(mapX, mapZ, color); + } + } + + player.sendMap(mapView); + } + + MapCursorCollection cursors = canvas.getCursors(); + + while (cursors.size() > 0) + + { + cursors.removeCursor(cursors.getCursor(0)); + } + + // TODO If you want players to see each other as cursors. Otherwise delete this bit. + for ( + + Player other : Bukkit.getOnlinePlayers()) + + { + if (player.canSee(other) && other.isValid()) + { + Location l = other.getLocation(); + + double mapX = (l.getX() - _manager.getX()) / zoom; + double mapZ = (l.getZ() - _manager.getZ()) / zoom; + + if (mapX > -64 && mapX < 64 && mapZ > -64 && mapZ < 64) + { + MapCursor.Type cursorDisplay; + MapCursor.Type friend; + MapCursor.Type foe; + + if (_host.GetTeam(player).GetColor() == ChatColor.RED) + { + friend = MapCursor.Type.RED_POINTER; + foe = MapCursor.Type.BLUE_POINTER; + } + else + { + friend = MapCursor.Type.BLUE_POINTER; + foe = MapCursor.Type.RED_POINTER; + } + + if (player == other) + { + cursorDisplay = MapCursor.Type.WHITE_POINTER; + } + else if (_host.GetTeam(player) == _host.GetTeam(other)) + { + cursorDisplay = friend; + } + else if (_host.GetTeam(player) != _host.GetTeam(other)) + { + if (_host.OverTime) + cursorDisplay = foe; + else + continue; + } + else + { + continue; + } + + byte b0 = (byte) (int) Math.min(127, (double) (mapX * 2.0F) + 0.5D); + byte b1 = (byte) (int) Math.max(-127, (double) (mapZ * 2.0F) + 0.5D); + + byte rotation = (byte) (int) ((l.getYaw() * 16D) / 360D); + + MapCursor cursor = new MapCursor(b0, b1, (byte) (rotation & 0xF), cursorDisplay.getValue(), true); + + cursors.addCursor(cursor); + } + } + } + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/GearObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/GearObjective.java new file mode 100644 index 000000000..1c7c72621 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/GearObjective.java @@ -0,0 +1,11 @@ +package nautilus.game.arcade.game.games.minecraftleague.data.objectives; + +import nautilus.game.arcade.game.games.minecraftleague.objective.GameObjective; + +public class GearObjective extends GameObjective +{ + public GearObjective() + { + super("GEAR", "Gear Up"); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/KillObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/KillObjective.java new file mode 100644 index 000000000..938d09e7d --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/data/objectives/KillObjective.java @@ -0,0 +1,12 @@ +package nautilus.game.arcade.game.games.minecraftleague.data.objectives; + +import nautilus.game.arcade.game.games.minecraftleague.objective.GameObjective; + +public class KillObjective extends GameObjective +{ + public KillObjective() + { + super("KILL_ENEMY", "Kill Enemy"); + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/kit/KitPlayer.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/kit/KitPlayer.java new file mode 100644 index 000000000..90043f0c0 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/kit/KitPlayer.java @@ -0,0 +1,63 @@ +package nautilus.game.arcade.game.games.minecraftleague.kit; + +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.kit.Kit; +import nautilus.game.arcade.kit.KitAvailability; +import nautilus.game.arcade.kit.Perk; + +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class KitPlayer extends Kit +{ + public KitPlayer(ArcadeManager manager) + { + super(manager, "Player", KitAvailability.Free, + + new String[] + { + "", + "Entirely vanilla combat!", + "" + }, + + new Perk[] + { + + }, EntityType.PLAYER, new ItemStack(Material.DIAMOND_SWORD)); + } + + @Override + public void GiveItems(Player player) + { + MinecraftLeague game = (MinecraftLeague)Manager.GetGame(); + /*player.getInventory().setHelmet(new ItemStack(Material.LEATHER_HELMET)); + player.getInventory().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + player.getInventory().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + player.getInventory().setBoots(new ItemStack(Material.LEATHER_BOOTS)); + player.getInventory().addItem(new ItemStack(Material.WOOD_SWORD));*/ + + if (game != null) + { + game.restoreGear(player); + game.MapManager.setMap(player); + } + + /*TeamMap tmap = game.getMap(game.GetTeam(player)); + + if (tmap == null) + return; + + tmap.giveMap(player, true, C.cGold + "Team Map", C.cGray + "This map contains", C.cGray + "the locations of", C.cGray + "your teammates.");*/ + } + + @Override + public void SpawnCustom(LivingEntity ent) + { + + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/GameObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/GameObjective.java new file mode 100644 index 000000000..54c633da3 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/GameObjective.java @@ -0,0 +1,23 @@ +package nautilus.game.arcade.game.games.minecraftleague.objective; + + +public abstract class GameObjective +{ + private String _displayText, _id; + + public GameObjective(String id, String displayText) + { + _id = id; + _displayText = displayText; + } + + public String getID() + { + return _id; + } + + public String getDisplayText() + { + return _displayText; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/ObjectiveManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/ObjectiveManager.java new file mode 100644 index 000000000..5281fecfe --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/objective/ObjectiveManager.java @@ -0,0 +1,125 @@ +package nautilus.game.arcade.game.games.minecraftleague.objective; + +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilTextBottom; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; + +public class ObjectiveManager implements Listener +{ + private MinecraftLeague _host; + private GameObjective _main; + private ConcurrentHashMap _specificObjectives = new ConcurrentHashMap(); + private ConcurrentHashMap _teamObjectives = new ConcurrentHashMap(); + + public ObjectiveManager(MinecraftLeague host) + { + _host = host; + Bukkit.getPluginManager().registerEvents(this, _host.getArcadeManager().getPlugin()); + } + + private void displayObjective(Player player) + { + GameObjective obj = _main; + if (_teamObjectives.containsKey(_host.GetTeam(player))) + obj = _teamObjectives.get(_host.GetTeam(player)); + if (_specificObjectives.containsKey(player)) + obj = _specificObjectives.get(player); + + UtilTextBottom.display(C.cGold + "Objective: " + obj.getDisplayText(), player); + } + + public String getMainObjective() + { + return _main.getID(); + } + + public String getTeamObjective(GameTeam team) + { + if (_teamObjectives.containsKey(team)) + return _teamObjectives.get(team).getID(); + + return getMainObjective(); + } + + public String getPlayerObjective(Player player) + { + if (_specificObjectives.containsKey(player)) + return _specificObjectives.get(player).getID(); + + return getTeamObjective(_host.GetTeam(player)); + } + + public void setMainObjective(GameObjective objective) + { + _main = objective; + } + + public void setPlayerObjective(Player player, GameObjective objective) + { + resetPlayerToMainObjective(player); + _specificObjectives.put(player, objective); + } + + public void resetPlayerToMainObjective(Player player) + { + if (!_specificObjectives.containsKey(player)) + return; + _specificObjectives.remove(player); + } + + public void setTeamObjective(GameTeam team, GameObjective objective) + { + if (getTeamObjective(team).equalsIgnoreCase("KILL_ENEMY")) + return; + + resetTeamToMainObjective(team); + _teamObjectives.put(team, objective); + } + + public void resetTeamToMainObjective(GameTeam team) + { + if (!_teamObjectives.containsKey(team)) + return; + _teamObjectives.remove(team); + } + + @EventHandler + public void onUpdate(UpdateEvent event) + { + if (!_host.IsLive()) + return; + if (event.getType() != UpdateType.FASTEST) + return; + + for (Player player : _host.GetPlayers(true)) + { + if (_main != null || _specificObjectives.containsKey(player) || _teamObjectives.containsKey(_host.GetTeam(player))) + displayObjective(player); + } + } + + @EventHandler + public void handleDeregister(GameStateChangeEvent event) + { + if (event.GetGame() != _host) + return; + + if (event.GetState() != GameState.Dead) + return; + + HandlerList.unregisterAll(this); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/AltarBuilderTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/AltarBuilderTracker.java new file mode 100644 index 000000000..d4eb61c0e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/AltarBuilderTracker.java @@ -0,0 +1,21 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.stats.StatTracker; + +import org.bukkit.event.EventHandler; + +public class AltarBuilderTracker extends StatTracker +{ + public AltarBuilderTracker(MinecraftLeague game) + { + super(game); + } + + @EventHandler + public void build(PlaceSkullEvent e) + { + addStat(e.getPlayer(), "AltarBuilder", 1, false, false); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/FirstStrikeTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/FirstStrikeTracker.java new file mode 100644 index 000000000..07d08ba0a --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/FirstStrikeTracker.java @@ -0,0 +1,22 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import nautilus.game.arcade.events.FirstBloodEvent; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.stats.StatTracker; + +import org.bukkit.event.EventHandler; + +public class FirstStrikeTracker extends StatTracker +{ + public FirstStrikeTracker(MinecraftLeague game) + { + super(game); + } + + @EventHandler + public void blood(FirstBloodEvent e) + { + addStat(e.getPlayer(), "FirstStrike", 1, false, false); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/GrabSkullEvent.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/GrabSkullEvent.java new file mode 100644 index 000000000..7da1c076e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/GrabSkullEvent.java @@ -0,0 +1,31 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class GrabSkullEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + private Player _player; + + public GrabSkullEvent(Player player) + { + _player = player; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public Player getPlayer() + { + return _player; + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/HeadHunterTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/HeadHunterTracker.java new file mode 100644 index 000000000..72100ecfe --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/HeadHunterTracker.java @@ -0,0 +1,21 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.stats.StatTracker; + +import org.bukkit.event.EventHandler; + +public class HeadHunterTracker extends StatTracker +{ + public HeadHunterTracker(MinecraftLeague game) + { + super(game); + } + + @EventHandler + public void build(GrabSkullEvent e) + { + addStat(e.getPlayer(), "HeadHunter", 1, false, false); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/PlaceSkullEvent.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/PlaceSkullEvent.java new file mode 100644 index 000000000..a9193a640 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/PlaceSkullEvent.java @@ -0,0 +1,31 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PlaceSkullEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + private Player _player; + + public PlaceSkullEvent(Player player) + { + _player = player; + } + + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + public Player getPlayer() + { + return _player; + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/SavingUpTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/SavingUpTracker.java new file mode 100644 index 000000000..9ab8f4756 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/SavingUpTracker.java @@ -0,0 +1,25 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.stats.StatTracker; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.inventory.CraftItemEvent; + +public class SavingUpTracker extends StatTracker +{ + public SavingUpTracker(MinecraftLeague game) + { + super(game); + } + + @EventHandler + public void build(CraftItemEvent e) + { + if (e.getRecipe().getResult().getType() == Material.DIAMOND_CHESTPLATE) + addStat((Player)e.getWhoClicked(), "SavingUp", 1, false, false); + } + +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/TowerDefenderTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/TowerDefenderTracker.java new file mode 100644 index 000000000..a9fa6936f --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/tracker/TowerDefenderTracker.java @@ -0,0 +1,85 @@ +package nautilus.game.arcade.game.games.minecraftleague.tracker; + +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.minecraft.game.core.combat.event.CombatDeathEvent; +import nautilus.game.arcade.game.Game; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.stats.StatTracker; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; + +public class TowerDefenderTracker extends StatTracker +{ + private final int _killCount; + private final String _stat; + private final int _timeLimit; + + private final ConcurrentHashMap _kills = new ConcurrentHashMap(); + private final ConcurrentHashMap _lastKill = new ConcurrentHashMap(); + + public TowerDefenderTracker(MinecraftLeague game, int killCount, int timeLimit, String stat) + { + super(game); + + _killCount = killCount; + _stat = stat; + _timeLimit = timeLimit * 1000; + } + + public int getKillCount() + { + return _killCount; + } + + public int getTimeLimit() + { + return _timeLimit; + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onCombatDeath(CombatDeathEvent event) + { + if (getGame().GetState() != Game.GameState.Live) + return; + + if (event.GetLog().GetKiller() == null) + return; + + if (!event.GetLog().GetKiller().IsPlayer()) + return; + + Player player = UtilPlayer.searchExact(event.GetLog().GetKiller().GetName()); + if (player == null) + return; + + Integer killCount = _kills.get(player.getUniqueId()); + Long lastKill = _lastKill.get(player.getUniqueId()); + + killCount = (killCount == null ? 0 : killCount) + 1; + lastKill = (lastKill == null ? System.currentTimeMillis() : lastKill); + + _kills.put(player.getUniqueId(), killCount); + _lastKill.put(player.getUniqueId(), System.currentTimeMillis()); + + if (killCount == getKillCount() && System.currentTimeMillis() - lastKill < getTimeLimit()) + { + if (UtilMath.offset2d(player.getLocation(), getGame().getActiveTower(getGame().GetTeam(player)).getLocation()) <= 7) + { + addStat(player, getStat(), 1, true, false); + _lastKill.remove(player.getUniqueId()); + _kills.remove(player.getUniqueId()); + } + } + } + + public String getStat() + { + return _stat; + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/ExtraScoreboardData.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/ExtraScoreboardData.java new file mode 100644 index 000000000..c13960834 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/ExtraScoreboardData.java @@ -0,0 +1,15 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation; + +import nautilus.game.arcade.scoreboard.GameScoreboard; + +public abstract class ExtraScoreboardData +{ + public GameScoreboard Scoreboard; + + public ExtraScoreboardData(GameScoreboard sb) + { + Scoreboard = sb; + } + + public abstract void write(); +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/GameVariation.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/GameVariation.java new file mode 100644 index 000000000..3b713809f --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/GameVariation.java @@ -0,0 +1,40 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation; + +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.world.WorldData; + +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; + +public abstract class GameVariation implements Listener +{ + public MinecraftLeague Host; + public ArcadeManager Manager; + public WorldData WorldData; + + public GameVariation(MinecraftLeague host) + { + Host = host; + Manager = host.getArcadeManager(); + WorldData = host.WorldData; + } + + public void ParseData() + { + + } + + public String[] getTeamScoreboardAdditions(GameTeam team) + { + return new String[]{}; + } + + public void deregister() + { + HandlerList.unregisterAll(this); + } + + public abstract void customDeregister(); +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/StandardGameplay.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/StandardGameplay.java new file mode 100644 index 000000000..2c06dffc4 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/StandardGameplay.java @@ -0,0 +1,14 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation; + +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +public class StandardGameplay extends GameVariation +{ + public StandardGameplay(MinecraftLeague host) + { + super(host); + } + + public void customDeregister() {} + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationManager.java new file mode 100644 index 000000000..fc392060e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationManager.java @@ -0,0 +1,99 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation; + +import java.lang.reflect.InvocationTargetException; + +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.games.minecraftleague.DataLoc; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; + +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class VariationManager implements Listener +{ + private MinecraftLeague _host; + + private GameVariation _variation; + //private VariationType _selected; + + public VariationManager(MinecraftLeague host) + { + _host = host; + Bukkit.getPluginManager().registerEvents(this, _host.getArcadeManager().getPlugin()); + } + + public GameVariation getSelected() + { + return _variation; + } + + public void selectVariation() + { + VariationType type = null; + if (_host.getMapVariantIDS().size() != 1) + type = VariationType.STANDARD; + else + { + type = VariationType.getFromID(_host.getMapVariantIDS().get(0).replace(DataLoc.VARIANT_BASE.getKey(), "")); + } + + try + { + _variation = type.getVariation().getConstructor(MinecraftLeague.class).newInstance(_host); + //_selected = type; + } + catch (NoSuchMethodException ex) + { + System.err.println("Is the constructor for " + type.toString() + " using only one argument?"); + ex.printStackTrace(); + return; + } + catch (InvocationTargetException ex) + { + ex.getCause().printStackTrace(); + return; + } + catch (Exception ex) + { + ex.printStackTrace(); + return; + } + + //Bukkit.broadcastMessage(type.getDisplayMessage()); + Bukkit.getPluginManager().registerEvents(_variation, _host.getArcadeManager().getPlugin()); + _variation.ParseData(); + } + + public void deregister() + { + if (_variation != null) + _variation.deregister(); + + HandlerList.unregisterAll(this); + } + + @EventHandler + public void handleDeregister(GameStateChangeEvent event) + { + if (event.GetGame() != _host) + return; + + if (event.GetState() != GameState.Dead) + return; + + deregister(); + } + + @EventHandler + public void onInform(PlayerJoinEvent event) + { + if (_variation != null) + { + //event.getPlayer().sendMessage(_selected.getDisplayMessage()); + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationType.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationType.java new file mode 100644 index 000000000..de1124d99 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/VariationType.java @@ -0,0 +1,47 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation; + +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.WitherVariation; + +import org.bukkit.ChatColor; + +public enum VariationType +{ + STANDARD("STANDARD", StandardGameplay.class, "Standard Gameplay", ChatColor.GREEN), + WITHER("WITHER", WitherVariation.class, "Wither Variation", ChatColor.RED), + //GUARDIAN(3, GuardianVariation.class, "Guardian Variation", ChatColor.DARK_AQUA) + ; + + private String _id; + private String _name; + private ChatColor _color; + private Class _variation; + + private VariationType(String id, Class variationClass, String displayName, ChatColor displayColor) + { + _id = id; + _name = displayName; + _color = displayColor; + _variation = variationClass; + } + + public Class getVariation() + { + return _variation; + } + + public String getDisplayMessage() + { + return ChatColor.DARK_AQUA + "Game Type Selected: " + _color + _name; + } + + public static VariationType getFromID(String id) + { + for (VariationType type : VariationType.values()) + { + if (type._id.equalsIgnoreCase(id)) + return type; + } + + return VariationType.STANDARD; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/WitherVariation.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/WitherVariation.java new file mode 100644 index 000000000..b9643c6af --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/WitherVariation.java @@ -0,0 +1,465 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.events.PlayerGameRespawnEvent; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.DataLoc; +import nautilus.game.arcade.game.games.minecraftleague.MinecraftLeague; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamTowerBase; +import nautilus.game.arcade.game.games.minecraftleague.variation.GameVariation; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.TeamAltar; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.WitherMinionManager; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.WitherPathfinder; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Wither; +import org.bukkit.entity.WitherSkull; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class WitherVariation extends GameVariation +{ + private ConcurrentHashMap _altars = new ConcurrentHashMap(); + + private Wither _wither; + private WitherPathfinder _pathfinder; + + private WitherMinionManager _skellyMan; + + public boolean WitherSpawned; + + private GameTeam _wowner = null; + + public WitherVariation(MinecraftLeague host) + { + super(host); + WitherSpawned = false; + _skellyMan = new WitherMinionManager(this, WorldData.GetDataLocs(DataLoc.WITHER_SKELETON.getKey())); + } + + @Override + public void customDeregister() + { + HandlerList.unregisterAll(_skellyMan); + } + + @Override + public void ParseData() + { + _altars.put(Host.GetTeam(ChatColor.AQUA), new TeamAltar(this, Host.GetTeam(ChatColor.AQUA), WorldData.GetDataLocs(DataLoc.BLUE_ALTAR.getKey()).get(0))); + _altars.put(Host.GetTeam(ChatColor.RED), new TeamAltar(this, Host.GetTeam(ChatColor.RED), WorldData.GetDataLocs(DataLoc.RED_ALTAR.getKey()).get(0))); + } + + @Override + public String[] getTeamScoreboardAdditions(GameTeam team) + { + String skulls = ""; + for (int i = 1; i < 4; i++) + { + if (!skulls.equalsIgnoreCase("")) + skulls = skulls + " "; + + if (_altars.get(team).getPlacedSkulls() >= i) + skulls = skulls + ChatColor.GREEN + "☠"; + else + skulls = skulls + ChatColor.GRAY + "☠"; + } + + return new String[] {"Skulls: " + skulls}; + } + + private Location getNearest(Location to, ConcurrentHashMap options) + { + Location ret = null; + double dist = Double.MAX_VALUE; + + for (Location check : options.keySet()) + { + if (options.get(check) < dist) + { + ret = check; + dist = options.get(check); + } + } + + return ret; + } + + private LinkedList getWaypoints(Location altar) + { + LinkedList waypoints = new LinkedList(); + ConcurrentHashMap distances = new ConcurrentHashMap(); + + for (Location loc : WorldData.GetDataLocs(DataLoc.WITHER_WAYPOINT.getKey())) + { + distances.put(loc, altar.distance(loc)); + } + + while (distances.size() >= 1) + { + Location act = getNearest(altar, distances); + waypoints.add(act); + distances.remove(act); + } + + return waypoints; + } + + @EventHandler + public void onUpdate(UpdateEvent event) + { + if (!Host.IsLive()) + return; + + if (event.getType() != UpdateType.TICK) + { + for (Player player : Bukkit.getOnlinePlayers()) + { + if (player.hasPotionEffect(PotionEffectType.WITHER)) + { + player.removePotionEffect(PotionEffectType.WITHER); + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 20 * 6, 0)); + } + if (!Host.IsAlive(player)) + continue; + /*GameTeam enemy = null; + if (Host.GetTeam(player).GetColor() == ChatColor.RED) + { + enemy = Host.GetTeam(ChatColor.AQUA); + } + else + { + enemy = Host.GetTeam(ChatColor.RED); + } + if (UtilMath.offset(player, Host.getActiveTower(enemy).getEntity()) <= 7) + { + for (Location loc : UtilShapes.getCircle(player.getEyeLocation(), true, 3)) + { + if (new Random().nextInt(5) <= 3) + { + UtilParticle.PlayParticle(ParticleType.DRIP_LAVA, loc, null, 0, 2, ViewDist.SHORT, player); + } + } + }*/ + } + if (_pathfinder != null) + if (_pathfinder.update()) + { + GameTeam team = _pathfinder.getTeam(); + _pathfinder = null; + WitherSpawned = false; + _wowner = null; + _skellyMan.onWitherDeath(); + UtilTextMiddle.display("", team.GetColor() + team.getDisplayName() + "'s Wither has been Defeated!"); + //Host.Objective.resetTeamToMainObjective(Host.GetTeam(ChatColor.RED)); + //Host.Objective.resetTeamToMainObjective(Host.GetTeam(ChatColor.AQUA)); + } + } + } + + @EventHandler + public void onWitherSpawn(EntitySpawnEvent event) + { + if (!Host.IsLive()) + return; + + if (event.getEntity() instanceof Wither) + { + if (WitherSpawned) + { + event.setCancelled(true); + return; + } + + for (GameTeam team : _altars.keySet()) + { + GameTeam enemy = null; + if (team.GetColor() == ChatColor.AQUA) + { + enemy = Host.GetTeam(ChatColor.RED); + } + else if (team.GetColor() == ChatColor.RED) + { + enemy = Host.GetTeam(ChatColor.AQUA); + } + if (_altars.get(team).ownsWither(event)) + { + if (Host.getTowerManager().getAmountAlive(enemy) < 1) + { + event.setCancelled(true); + return; + } + WitherSpawned = true; + _wowner = team; + _wither = (Wither)event.getEntity(); + _wither.setCustomName(team.GetColor() + team.getDisplayName() + "'s Wither"); + _wither.setCustomNameVisible(true); + UtilTextMiddle.display("", C.cWhite + team.getDisplayName() + " Team has spawned a Wither Boss!", UtilServer.getPlayers()); + _pathfinder = new WitherPathfinder(this, _wither, getWaypoints(_altars.get(team).getLocation()), team, enemy, Host.getTowerManager()); + _skellyMan.onWitherSpawn(); + //Host.Objective.setMainObjective(new GearObjective()); + //Host.Objective.setTeamObjective(team, new WitherObjective("Attack Enemy Towers")); + //Host.Objective.setTeamObjective(enemy, new WitherObjective("Kill Wither")); + /*for (Player player : Host.GetPlayers(true)) + { + Host.Objective.resetPlayerToMainObjective(player); + }*/ + Bukkit.getScheduler().runTaskLater(Manager.getPlugin(), new Runnable() + { + public void run() + { + Host.CreatureAllowOverride = false; + } + }, 20 * 3); + Bukkit.getScheduler().runTaskLater(Manager.getPlugin(), new Runnable() + { + public void run() + { + _altars.get(team).spawnSoulsand(); + } + }, 20 * 35); + } + } + + if (_wither == null) + { + event.setCancelled(true); + } + } + } + + @EventHandler + public void handleWitherDrops(EntityDeathEvent event) + { + if (!Host.IsLive()) + return; + + if (event.getEntity() instanceof Wither) + { + event.setDroppedExp(0); + event.getDrops().clear(); + } + } + + //@SuppressWarnings("deprecation") + @EventHandler + public void onExplode(EntityExplodeEvent event) + { + if (!Host.IsLive()) + return; + + if (event.getEntity() instanceof Wither) + { + event.blockList().clear(); + return; + } + if (event.getEntity() instanceof WitherSkull) + { + event.setCancelled(true); + + if (!((WitherSkull)event.getEntity()).isCharged()) + return; + + LinkedList red = Host.getTowerManager().getTeamTowers(Host.GetTeam(ChatColor.RED)); + LinkedList blue = Host.getTowerManager().getTeamTowers(Host.GetTeam(ChatColor.AQUA)); + HashMap inside = UtilBlock.getInRadius(event.getLocation().getBlock(), 4, false); + + double dmg = 10 * (Host.GetTeam(ChatColor.RED).GetPlayers(true).size() + Host.GetTeam(ChatColor.RED).GetPlayers(true).size()); + for (TeamTowerBase tb : red) + { + if (inside.containsKey(tb.getLocation().getBlock())) + { + tb.damage(dmg, null); + Host.Alert.alert(tb.getTeam(), tb); + } + } + for (TeamTowerBase tb : blue) + { + if (inside.containsKey(tb.getLocation().getBlock())) + { + tb.damage(dmg, null); + Host.Alert.alert(tb.getTeam(), tb); + } + } + for (Block b : inside.keySet()) + { + if (inside.get(b) > 2) + continue; + + for (TeamAltar altar : _altars.values()) + { + if (altar.isInsideAltar(b.getLocation())) + continue; + } + for (GameTeam owner : Host.GetTeamList()) + { + for (TeamTowerBase tb : Host.getTowerManager().getTeamTowers(owner)) + { + if (!tb.Vulnerable) + continue; + + if (tb.getLocation().distance(b.getLocation()) < 7) + { + if (b.getType() == Material.BEDROCK) + continue; + if (b.getType() == Material.OBSIDIAN) + { + if (new Random().nextDouble() > (.75 / 2)) + continue; + } + if (b.getType() == Material.AIR) + continue; + if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) + continue; + if (b.getType() == Material.STATIONARY_LAVA || b.getType() == Material.LAVA) + continue; + //WorldData.World.dropItem(b.getLocation(), new ItemBuilder(b.getType()).setData(b.getData()).build()); + b.setType(Material.AIR); + } + } + } + } + } + else if (event.getEntity() instanceof TNTPrimed) + { + event.setCancelled(true); + } + } + + @EventHandler + public void onPlace(BlockPlaceEvent event) + { + if (!Host.IsLive()) + return; + + for (TeamAltar altar : _altars.values()) + { + if (!altar.canPlace(event.getPlayer(), event.getBlock().getType(), event.getBlock().getLocation(), true)) + event.setCancelled(true); + } + } + + @EventHandler + public void onBreak(BlockBreakEvent event) + { + if (!Host.IsLive()) + return; + + for (TeamAltar altar : _altars.values()) + { + if (!altar.canBreak(event.getPlayer(), event.getBlock(), true)) + event.setCancelled(true); + } + } + + @EventHandler + public void onShoot(ProjectileLaunchEvent event) + { + if (!Host.IsLive()) + return; + + if (event.getEntity()instanceof WitherSkull) + { + final WitherSkull entity = (WitherSkull)event.getEntity(); + if (entity.isCharged()) + { + event.setCancelled(true); + } + else + { + if (!((Wither)entity.getShooter()).hasMetadata("Shooting")) + event.setCancelled(true); + } + } + } + + @EventHandler + public void preserveAltars(EntityChangeBlockEvent event) + { + if (!Host.IsLive()) + return; + + for (TeamAltar altar : _altars.values()) + { + if (altar.isInsideAltar(event.getBlock().getLocation())) + { + event.setCancelled(true); + } + } + } + + @EventHandler + public void protectWither(EntityDamageByEntityEvent event) + { + if (!Host.IsLive()) + return; + if (!WitherSpawned) + return; + + if (event.getEntity() instanceof Wither) + { + if (event.getDamager() instanceof Player) + { + Player dmg = (Player)event.getDamager(); + if (_wowner.HasPlayer(dmg)) + { + event.setCancelled(true); + return; + } + } + if (event.getDamager() instanceof Projectile) + { + if (((Projectile)event.getDamager()).getShooter() instanceof Player) + { + Player dmg = (Player) ((Projectile)event.getDamager()).getShooter(); + if (_wowner.HasPlayer(dmg)) + { + event.setCancelled(true); + return; + } + } + } + event.setDamage(event.getDamage() * .8); + } + } + + @EventHandler + public void onRespawn(PlayerGameRespawnEvent event) + { + if (!Host.IsLive()) + return; + + Manager.GetCondition().Clean(event.GetPlayer()); + /*if (Host.Objective.getPlayerObjective(event.GetPlayer()).equals("RETURN_SKULL")) + { + Host.Objective.resetPlayerToMainObjective(event.GetPlayer()); + }*/ + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/PathfinderData.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/PathfinderData.java new file mode 100644 index 000000000..97d6ec69a --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/PathfinderData.java @@ -0,0 +1,81 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilBlock; +import mineplex.core.common.util.UtilEnt; + +import org.bukkit.Location; +import org.bukkit.entity.Wither; +import org.bukkit.util.Vector; + +public class PathfinderData +{ + public Wither Wither; + + public Location Target = null; + public Location Location = null; + + public float Pitch = 0; + public Vector Velocity = new Vector(0,0,0); + + //private long _lastReview; + + public PathfinderData(Wither wither, Location target) + { + Wither = wither; + UtilEnt.ghost(wither, true, false); + UtilEnt.Vegetate(wither, false); + + Location temp = wither.getLocation(); + temp.setPitch(UtilAlg.GetPitch(UtilAlg.getTrajectory(wither.getLocation(), target))); + wither.teleport(temp); + + Velocity = wither.getLocation().getDirection().setY(0).normalize(); + Pitch = UtilAlg.GetPitch(wither.getLocation().getDirection()); + + Location = wither.getLocation(); + //_lastReview = System.currentTimeMillis(); + } + + public void move() + { + turn(); + + //Speed + double speed = 0.325 / 2; + + Location.add(Velocity.clone().multiply(speed)); + Location.add(0, -Pitch, 0); + + Location.setPitch(-1 * Pitch); + Location.setYaw(/*180 +*/ UtilAlg.GetYaw(Velocity)); + + // + if (!UtilBlock.airFoliage(Location.getBlock())) + { + Location.setY(UtilBlock.getHighest(Location.getWorld(), Location.getBlockX(), Location.getBlockZ()).getY()); + } + + Wither.teleport(Location); + } + + private void turn() + { + //Pitch + float desiredPitch = UtilAlg.GetPitch(UtilAlg.getTrajectory(Location, Target)); + if (desiredPitch < Pitch) Pitch = (float)(Pitch - 0.05); + if (desiredPitch > Pitch) Pitch = (float)(Pitch + 0.05); + if (Pitch > 0.5) Pitch = 0.5f; + if (Pitch < -0.5) Pitch = -0.5f; + + //Flat + Vector desired = UtilAlg.getTrajectory2d(Location, Target); + desired.subtract(UtilAlg.Normalize(new Vector(Velocity.getX(), 0, Velocity.getZ()))); + desired.multiply(0.2); + + Velocity.add(desired); + + //Speed + UtilAlg.Normalize(Velocity); + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/TeamAltar.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/TeamAltar.java new file mode 100644 index 000000000..da234474b --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/TeamAltar.java @@ -0,0 +1,202 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data; + +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.hologram.Hologram; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.tracker.PlaceSkullEvent; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.WitherVariation; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wither; +import org.bukkit.event.entity.EntitySpawnEvent; + +public class TeamAltar +{ + private WitherVariation _host; + private GameTeam _team; + private Location _center; + + //private List _protected; + + private Location[] _skullSpots; + + private int _placed; + + public TeamAltar(WitherVariation host, GameTeam team, Location center) + { + _host = host; + _team = team; + _center = center; + + spawnSoulsand(); + + //_protected = UtilShapes.getSphereBlocks(center, 7, 7, false); + + Location labelLoc = center.clone().add(0/*.5*/, 5, 0.5); + String labelStr = team.GetColor() + team.getDisplayName() + "'s Altar"; + Hologram label = new Hologram(host.Host.getArcadeManager().getHologramManager(), labelLoc, labelStr); + label.start(); + } + + public boolean isInsideAltar(Location location) + { + return UtilMath.offset(_center, location) <= 7; + //return _protected.contains(location); + } + + public void spawnSoulsand() + { + _placed = 0; + Location s1 = null; + Location s2 = null; + Location s3 = null; + + for (int i = -1; i <= 1; i++) + { + _center.getBlock().getRelative(i, 1, 0).setType(Material.SOUL_SAND); + if (i == -1) + s1 = _center.getBlock().getRelative(i, 2, 0).getLocation(); + if (i == 0) + s2 = _center.getBlock().getRelative(i, 2, 0).getLocation(); + if (i == 1) + s3 = _center.getBlock().getRelative(i, 2, 0).getLocation(); + } + _center.getBlock().setType(Material.SOUL_SAND); + + _skullSpots = new Location[] {s1, s2, s3}; + } + + public boolean canBreak(Player player, Block block, boolean notify) + { + if (isInsideAltar(block.getLocation())) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "You cannot break blocks inside an Altar!")); + return false; + /*if (!_team.HasPlayer(player)) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "This is not your Altar!")); + return false; + } + if (block.getType() != Material.SKULL) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "You cannot break that block inside an Altar!")); + return false; + }*/ + } + return true; + } + + public boolean canPlace(Player player, Material blockType, Location location, boolean notify) + { + if (isInsideAltar(location)) + { + if (!_team.HasPlayer(player)) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "This is not your Altar!")); + return false; + } + + if (_host.WitherSpawned) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "A Wither is already spawned!")); + return false; + } + + if (blockType != Material.SKULL) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "You cannot place that inside an Altar!")); + return false; + } + + boolean passes = false; + for (Location l : _skullSpots) + { + if (l.equals(location)) + passes = true; + } + + if (!passes) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "That doesn't go there!")); + return false; + } + + if (_team.GetColor() == ChatColor.RED) + { + if (_host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.AQUA)) < 1) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "You do not need a Wither!")); + return false; + } + } + if (_team.GetColor() == ChatColor.AQUA) + { + if (_host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.RED)) < 1) + { + if (notify) + UtilPlayer.message(player, F.main("Game", "You do not need a Wither!")); + return false; + } + } + + if (_team.HasPlayer(player) && blockType == Material.SKULL) + { + //_host.Host.Objective.resetPlayerToMainObjective(player); + Bukkit.getPluginManager().callEvent(new PlaceSkullEvent(player)); + if (_placed < 2) + { + UtilTextMiddle.display("", _team.GetColor() + _team.getDisplayName() + " has placed a Skull on their Altar!"); + for (Player scare : UtilServer.getPlayers()) + { + scare.playSound(scare.getLocation(), Sound.WITHER_SPAWN, 10, 0); + } + } + else + { + _host.Host.CreatureAllowOverride = true; + } + _placed++; + } + } + return true; + } + + public boolean ownsWither(EntitySpawnEvent event) + { + if (event.getEntity() instanceof Wither) + { + Location base = event.getLocation(); + return (isInsideAltar(base.getBlock().getLocation())); + } + + return false; + } + + public Location getLocation() + { + return _center.clone(); + } + + public int getPlacedSkulls() + { + return _placed; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherMinionManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherMinionManager.java new file mode 100644 index 000000000..a42b8523d --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherMinionManager.java @@ -0,0 +1,488 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data; + +import java.util.List; +import java.util.Random; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.F; +import mineplex.core.common.util.UtilAction; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilFirework; +import mineplex.core.common.util.UtilInv; +import mineplex.core.common.util.UtilItem; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTextMiddle; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import mineplex.core.itemstack.ItemBuilder; +import mineplex.core.recharge.Recharge; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.games.minecraftleague.data.MapZone; +import nautilus.game.arcade.game.games.minecraftleague.tracker.GrabSkullEvent; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.WitherVariation; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.FireworkEffect.Type; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftSkeleton; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Skeleton; +import org.bukkit.entity.Skeleton.SkeletonType; +import org.bukkit.entity.Wither; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; + +public class WitherMinionManager implements Listener +{ + private WitherVariation _host; + private List _spawns; + private long _lastDied; + private int _lastUsed; + private int _selected; + + private Skeleton _entity; + + private ItemStack _witherItem; + + private WitherSkeletonTimer _sbTimer; + //private MapZone _skellyZone; + + private Block _cb; + private Material _changed = Material.AIR; + + private boolean _witherBlocked = false; + + private boolean _spawned = false; + + public WitherMinionManager(WitherVariation host, List spawns) + { + _host = host; + _spawns = spawns; + _lastDied = System.currentTimeMillis(); + _lastUsed = -1; + _witherItem = new ItemBuilder(Material.SKULL_ITEM).setTitle(C.cDRedB + "Wither Skeleton Head").setData((short) 1).setLore(C.cGray + "Bring this back", C.cGray + "to your team's Altar", C.cGray + "To summon a Wither!").build(); + _sbTimer = new WitherSkeletonTimer(host.Host.GetScoreboard()); + host.Host.ExtraSb.put(_sbTimer, host); + //_skellyZone = new MapZone(spawns.get(0), new int[] {0, 0, 0}); + //_skellyZone.setValid(false); + //host.Host.MapZones.add(_skellyZone); + + Bukkit.getPluginManager().registerEvents(this, host.Manager.getPlugin()); + } + + private void preSpawn() + { + Location chosen = null; + while (chosen == null) + { + int check = new Random().nextInt(_spawns.size()); + if (check != _lastUsed) + { + chosen = _spawns.get(check); + _lastUsed = check; + _selected = check; + } + } + + _cb = chosen.clone().add(0, -2, 0).getBlock(); + _changed = _cb.getType(); + chosen.clone().add(0, -2, 0).getBlock().setType(Material.BEACON); + } + + private void spawn(boolean respawn) + { + Location chosen = null; + if (!respawn) + chosen = _spawns.get(_selected); + else + chosen = _spawns.get(_lastUsed); + _host.Host.CreatureAllowOverride = true; + Entity e = _host.Manager.GetCreature().SpawnEntity(chosen, EntityType.SKELETON); + _host.Host.CreatureAllowOverride = false; + ((Skeleton)e).setSkeletonType(SkeletonType.WITHER); + _entity = (Skeleton)e; + UtilEnt.ghost(e, true, false); + UtilEnt.Vegetate(e); + e.setCustomName(C.cRed + "Wither Skeleton"); + ((Skeleton)e).setMaxHealth(/*100*/65); + ((Skeleton)e).setHealth(/*100*/65); + ((CraftSkeleton)e).getEquipment().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + ((CraftSkeleton)e).getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + //((Skeleton)e).addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 9999999, 7)); + + if (!respawn) + { + UtilTextMiddle.display("", C.cGray + "A Wither Skeleton has spawned!"); + //_skellyZone.setCenter(chosen); + //_skellyZone.setValid(true); + //_host.Host.Objective.setMainObjective(new GrabSkullObjective()); + } + _selected = -1; + _spawned = true; + } + + public void onWitherDeath() + { + _lastDied = System.currentTimeMillis(); + _witherBlocked = false; + _host.Host.getTowerManager().toggleAttack(); + _sbTimer.freezeTime(-1); + } + + public void onWitherSpawn() + { + _host.Host.getTowerManager().toggleAttack(); + _witherBlocked = true; + if (_entity != null) + { + _spawned = false; + _entity.remove(); + _lastDied = System.currentTimeMillis(); + //_skellyZone.setValid(false); + _entity = null; + } + if (_cb != null) + { + _cb.setType(_changed); + _cb = null; + _changed = Material.AIR; + } + } + + @EventHandler + public void onLive(GameStateChangeEvent event) + { + if (event.GetGame() != _host.Host) + return; + if (event.GetState() != GameState.Live) + return; + + _lastDied = System.currentTimeMillis() + UtilTime.convert(60, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); + } + + @EventHandler + public void onUpdate(UpdateEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (event.getType() != UpdateType.FASTEST) + return; + + if (_entity == null || !_entity.isValid()) + { + if (_spawned) + spawn(true); + } + + if (_entity != null) + { + _entity.teleport(_spawns.get(_lastUsed)); + } + + try { + if (UtilTime.elapsed(_lastDied, UtilTime.convert(45, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + boolean noUse = _host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.RED)) < 1; + if (_host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.AQUA)) >= 1) + noUse = false; + if (!_witherBlocked && !noUse) + { + if (_entity == null) + { + if (_selected != _lastUsed) + { + preSpawn(); + } + long end = _lastDied + UtilTime.convert(1, TimeUnit.MINUTES, TimeUnit.MILLISECONDS); + end =- System.currentTimeMillis(); + long secLeft = UtilTime.convert(end, TimeUnit.MILLISECONDS, TimeUnit.SECONDS); + if (secLeft <= 3) + { + if (secLeft > 0) + { + UtilTextMiddle.display(secLeft + " Seconds", "Until Wither Skeleton Spawn"); + } + } + } + } + } + + if (UtilTime.elapsed(_lastDied, UtilTime.convert(90, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + boolean noUse = _host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.RED)) < 1; + if (_host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.AQUA)) >= 1) + noUse = false; + if (!_witherBlocked && !noUse) + { + if (_entity == null) + spawn(false); + } + } + + for (Player player : Bukkit.getOnlinePlayers()) + { + if (UtilInv.contains(player, Material.SKULL_ITEM, (byte) 1, 1)) + { + UtilParticle.PlayParticle(ParticleType.WITCH_MAGIC, player.getLocation(), new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat(), 0, 1, ViewDist.MAX); + if (Recharge.Instance.usable(player, "FIREWORK_ALERT", false)) + { + Recharge.Instance.use(player, "FIREWORK_ALERT", UtilTime.convert(2, TimeUnit.SECONDS, TimeUnit.MILLISECONDS), false, false); + UtilFirework.playFirework(player.getEyeLocation().add(0, 3, 0), Type.BURST, _host.Host.GetTeam(player).GetColorBase(), false, true); + } + } + else + { + /*if (_host.Host.Objective.getPlayerObjective(player) != null) + { + if (_host.Host.Objective.getPlayerObjective(player).equalsIgnoreCase("GRAB_SKULL")) + { + _host.Host.Objective.resetPlayerToMainObjective(player); + } + }*/ + } + + if (player.getInventory().getHelmet() != null) + { + if (UtilInv.IsItem(player.getInventory().getHelmet(), Material.SKULL_ITEM, (byte) 1)) + { + player.getInventory().setHelmet(new ItemStack(Material.AIR)); + UtilInv.insert(player, _witherItem.clone()); + } + } + } + } catch (Exception e) + { + + } + } + + @EventHandler + public void handleTimer(UpdateEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (event.getType() != UpdateType.FASTEST) + return; + + boolean noUse = _host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.RED)) < 1; + if (_host.Host.getTowerManager().getAmountAlive(_host.Host.GetTeam(ChatColor.AQUA)) >= 1) + noUse = false; + + if (_entity != null || noUse) + { + _sbTimer.freezeTime(0); + return; + } + + if (_host.WitherSpawned || _witherBlocked) + { + _sbTimer.freezeTime(-2); + return; + } + + if (_entity == null) + _sbTimer.freezeTime(-1); + + _sbTimer.setEnd((_lastDied + UtilTime.convert(90, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onSkellyDie(EntityDeathEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (event.getEntity() instanceof Skeleton) + { + Skeleton skelly = (Skeleton)event.getEntity(); + if (skelly.getSkeletonType() == SkeletonType.WITHER) + { + if (_entity != null) + { + if (skelly.getEntityId() == _entity.getEntityId()) + { + _spawned = false; + _lastDied = System.currentTimeMillis(); + _entity = null; + event.getDrops().clear(); + event.getDrops().add(_witherItem.clone()); + event.setDroppedExp(10); + //_skellyZone.setValid(false); + + _cb.setType(_changed); + _cb = null; + _changed = Material.AIR; + + Bukkit.getScheduler().runTaskLater(_host.Manager.getPlugin(), new Runnable() { + public void run() + { + _host.Host.getTowerManager().ironOreGen(null, false); + } + }, 20 * 10); + + //_host.Host.Objective.setMainObjective(new GearObjective()); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPickup(PlayerPickupItemEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (!event.isCancelled()) + { + String com = UtilItem.itemToStr(event.getItem().getItemStack()); + String com1 = UtilItem.itemToStr(_witherItem.clone()); + String[] compare = com.split(":"); + String[] compare1 = com1.split(":"); + String fin = compare[0] + ":" + compare[2] + ":" + compare[3]; + String fin1 = compare1[0] + ":" + compare1[2] + ":" + compare1[3]; + if (fin.equalsIgnoreCase(fin1)) + { + UtilPlayer.message(event.getPlayer(), F.main("Game", "You have the Wither Skull! Return the skull to your base and place it on your Altar to summon the Wither!")); + UtilTextMiddle.display("", C.cGray + "You have picked up the Wither Skull!", event.getPlayer()); + Bukkit.getScheduler().runTaskLater(_host.Manager.getPlugin(), new Runnable() + { + public void run() + { + UtilTextMiddle.display("", "Place the skull on top of", event.getPlayer()); + } + }, 20 * 5); + Bukkit.getScheduler().runTaskLater(_host.Manager.getPlugin(), new Runnable() + { + public void run() + { + UtilTextMiddle.display("", "Your Altar's Soul Sand!", event.getPlayer()); + } + }, 20 * 8); + //_host.Host.Objective.setPlayerObjective(event.getPlayer(), new ReturnSkullObjective()); + if (!event.getItem().hasMetadata("Dropped")) + { + Bukkit.getPluginManager().callEvent(new GrabSkullEvent(event.getPlayer())); + UtilTextMiddle.display("", _host.Host.GetTeam(event.getPlayer()).GetColor() + _host.Host.GetTeam(event.getPlayer()).getDisplayName() + " has picked up a Wither Skull!", 20, 20 * 5, 20); + } + } + } + } + + @EventHandler + public void onDrop(PlayerDropItemEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (!event.isCancelled()) + { + String com = UtilItem.itemToStr(event.getItemDrop().getItemStack()); + String com1 = UtilItem.itemToStr(_witherItem.clone()); + String[] compare = com.split(":"); + String[] compare1 = com1.split(":"); + String fin = compare[0] + ":" + compare[2] + ":" + compare[3]; + String fin1 = compare1[0] + ":" + compare1[2] + ":" + compare1[3]; + if (fin.equalsIgnoreCase(fin1)) + { + event.getItemDrop().setMetadata("Dropped", new FixedMetadataValue(_host.Manager.getPlugin(), true)); + //_host.Host.Objective.resetPlayerToMainObjective(event.getPlayer()); + } + } + } + + @EventHandler + public void onPlace(BlockPlaceEvent event) + { + if (!_host.Host.IsLive()) + return; + + for (Location loc : _spawns) + { + //if (UtilShapes.getSphereBlocks(loc, 6, 6, false).contains(event.getBlock().getLocation())) + if (UtilMath.offset(loc, event.getBlock().getLocation()) <= 6) + event.setCancelled(true); + } + } + + @EventHandler + public void onBreak(BlockBreakEvent event) + { + if (!_host.Host.IsLive()) + return; + + for (Location loc : _spawns) + { + //if (UtilShapes.getSphereBlocks(loc, 6, 6, false).contains(event.getBlock().getLocation())) + if (UtilMath.offset(loc, event.getBlock().getLocation()) <= 6) + event.setCancelled(true); + } + } + + @EventHandler + public void onExp(EntityExplodeEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (event.getEntity() instanceof Wither) + { + event.blockList().clear(); + return; + } + event.setCancelled(true); + } + + @EventHandler + public void onEntity(EntityChangeBlockEvent event) + { + if (!_host.Host.IsLive()) + return; + + for (Location loc : _spawns) + { + //if (UtilShapes.getSphereBlocks(loc, 5, 5, false).contains(event.getBlock().getLocation())) + if (UtilMath.offset(loc, event.getBlock().getLocation()) <= 6) + event.setCancelled(true); + } + } + + @EventHandler + public void fixDamage(EntityDamageEvent event) + { + if (!_host.Host.IsLive()) + return; + + if (_entity == null) + return; + if (event.getEntity().getEntityId() != _entity.getEntityId()) + return; + + UtilAction.zeroVelocity(event.getEntity()); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherPathfinder.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherPathfinder.java new file mode 100644 index 000000000..57f98615e --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherPathfinder.java @@ -0,0 +1,226 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data; + +import java.util.HashMap; +import java.util.LinkedList; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilEnt; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import nautilus.game.arcade.game.GameTeam; +import nautilus.game.arcade.game.games.minecraftleague.DataLoc; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamTower; +import nautilus.game.arcade.game.games.minecraftleague.data.TeamTowerBase; +import nautilus.game.arcade.game.games.minecraftleague.data.TowerManager; +import nautilus.game.arcade.game.games.minecraftleague.variation.wither.WitherVariation; + +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wither; +import org.bukkit.entity.WitherSkull; +import org.bukkit.metadata.FixedMetadataValue; + +public class WitherPathfinder +{ + private PathfinderData _pathData; + private WitherVariation _host; + private Wither _ent; + private LinkedList _waypoints; + private GameTeam _team; + private GameTeam _enemy; + private TowerManager _towerManager; + private long _lastAttack; + private long _lastTowerAttack; + + private boolean _startedJourney = false; + + private double _health; + + public WitherPathfinder(WitherVariation host, Wither ent, LinkedList waypoints, GameTeam team, GameTeam enemy, TowerManager towerManager) + { + _host = host; + _ent = ent; + _waypoints = waypoints; + _team = team; + _enemy = enemy; + _towerManager = towerManager; + _lastAttack = -1; + _lastTowerAttack = -1; + _pathData = new PathfinderData(ent, waypoints.getFirst()); + _health = ent.getHealth(); + } + + private int getWaypointIndex(Location loc) + { + int best = -1; + double bestDist = 0; + + for (int i=0 ; i<_waypoints.size() ; i++) + { + Location waypoint = _waypoints.get(i); + + double dist = UtilMath.offset(waypoint, loc); + + if (best == -1 || dist < bestDist) + { + best = i; + bestDist = dist; + } + } + + return best; + } + + private void advance() + { + _pathData.Target = _waypoints.get(Math.min(_waypoints.size()-1, (getWaypointIndex(_pathData.Location) + 1))); + _pathData.move(); + } + + private void retarget() + { + _ent.setTarget(null); + + LivingEntity target = null; + HashMap inside = UtilEnt.getInRadius(_ent.getLocation(), 30); + for (LivingEntity ent : inside.keySet()) + { + if (UtilPlayer.isSpectator(ent)) + continue; + + if (ent instanceof Player) + { + if (_team.HasPlayer((Player)ent)) + continue; + } + else + continue; + + if (target == null) + target = ent; + + if (inside.get(target) > inside.get(ent)) + target = ent; + } + + if (target != null) + { + if (UtilTime.elapsed(_lastAttack, UtilTime.convert(2, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _lastAttack = System.currentTimeMillis(); + shootAt(target.getLocation(), false); + } + } + } + + private void shootAt(Location loc, boolean charged) + { + Location old = _ent.getLocation(); + Location temp = _ent.getLocation(); + temp.setPitch(UtilAlg.GetPitch(UtilAlg.getTrajectory(_ent.getEyeLocation(), loc))); + temp.setYaw(UtilAlg.GetYaw(UtilAlg.getTrajectory(_ent.getEyeLocation(), loc))); + _ent.teleport(temp); + _ent.setMetadata("Shooting", new FixedMetadataValue(_host.Manager.getPlugin(), "1")); + WitherSkull skull = _ent.launchProjectile(WitherSkull.class); + skull.setCharged(charged); + _ent.removeMetadata("Shooting", _host.Manager.getPlugin()); + _ent.teleport(old); + //skull.setDirection(UtilAlg.getTrajectory(_ent.getLocation(), loc).normalize()); + } + + private TeamTowerBase getProperTarget() + { + for (TeamTowerBase t : _towerManager.getTeamTowers(_enemy)) + { + if (t.Alive) + return t; + } + return null; + } + + public GameTeam getTeam() + { + return _team; + } + + /** + * Returns true if the entity is dead or invalid + */ + public boolean update() + { + if ((_ent == null) || _ent.isDead() || !_ent.isValid()) + return true; + + Entity eTower = getProperTarget().getEntity(); + if (eTower == null || !eTower.isValid() || eTower.isDead()) + { + _ent.remove(); + return true; + } + + if (_ent.getHealth() < _ent.getMaxHealth()) + { + if (!_startedJourney) + { + _health = _ent.getMaxHealth(); + return false; + } + } + _startedJourney = true; + + _health = Math.min(_health, _ent.getHealth()); + _ent.setHealth(_health); + + for (Entity e : UtilEnt.getAllInRadius(_ent.getLocation(), 3).keySet()) + { + if (e instanceof Arrow) + { + Arrow arrow = (Arrow)e; + if (arrow.getShooter() instanceof Player) + { + if (!_team.HasPlayer((Player)arrow.getShooter())) + { + arrow.remove(); + _ent.damage(5, (Player)arrow.getShooter()); + } + } + } + } + + if (_ent.getLocation().distance(eTower.getLocation()) <= 10) + { + _ent.setTarget(null); + String tName = ""; + if (_team.GetColor() == ChatColor.RED) + tName = "RED"; + if (_team.GetColor() == ChatColor.AQUA) + tName = "BLUE"; + Integer cNumber = -1; + if (getProperTarget() instanceof TeamTower) + cNumber = ((TeamTower)getProperTarget()).Number; + else + cNumber = 3; + Location finalize = _host.Host.WorldData.GetCustomLocs(DataLoc.TOWER_WAYPOINT.getKey().replace("$team$", tName).replace("$number$", cNumber + "")).get(0); + finalize.setPitch(UtilAlg.GetPitch(UtilAlg.getTrajectory(_ent, eTower))); + finalize.setYaw(UtilAlg.GetYaw(UtilAlg.getTrajectory(_ent, eTower))); + _ent.teleport(finalize); + if (UtilTime.elapsed(_lastTowerAttack, UtilTime.convert(5, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))) + { + _lastTowerAttack = System.currentTimeMillis(); + shootAt(eTower.getLocation(), true); + } + return false; + } + + advance(); + retarget(); + + return false; + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherSkeletonTimer.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherSkeletonTimer.java new file mode 100644 index 000000000..0b655ae09 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/WitherSkeletonTimer.java @@ -0,0 +1,50 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data; + +import mineplex.core.common.util.C; +import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; +import nautilus.game.arcade.game.games.minecraftleague.variation.ExtraScoreboardData; +import nautilus.game.arcade.scoreboard.GameScoreboard; + +public class WitherSkeletonTimer extends ExtraScoreboardData +{ + private long _end; + private int _frozen; + + public WitherSkeletonTimer(GameScoreboard sb) + { + super(sb); + _end = 0; + _frozen = -1; + } + + public void setEnd(long end) + { + _end = end; + } + + public void freezeTime(int seconds) + { + _frozen = seconds; + } + + public void write() + { + Scoreboard.Write(C.cYellowB + "Wither Skeleton Spawn"); + if (_frozen != -1) + { + if (_frozen == -2) + Scoreboard.Write("WITHER ALIVE"); + else + Scoreboard.Write(_frozen + " Seconds"); + } + else + { + long seconds = 0; + if (_end - System.currentTimeMillis() > 0) + seconds = UtilTime.convert(_end - System.currentTimeMillis(), TimeUnit.MILLISECONDS, TimeUnit.SECONDS); + + Scoreboard.Write(UtilTime.MakeStr(UtilTime.convert(seconds, TimeUnit.SECONDS, TimeUnit.MILLISECONDS))); + } + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/GrabSkullObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/GrabSkullObjective.java new file mode 100644 index 000000000..1b66bee30 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/GrabSkullObjective.java @@ -0,0 +1,11 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.objectives; + +import nautilus.game.arcade.game.games.minecraftleague.objective.GameObjective; + +public class GrabSkullObjective extends GameObjective +{ + public GrabSkullObjective() + { + super("GRAB_SKULL", "Collect Wither Skull"); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/ReturnSkullObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/ReturnSkullObjective.java new file mode 100644 index 000000000..5b5958601 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/ReturnSkullObjective.java @@ -0,0 +1,12 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.objectives; + +import nautilus.game.arcade.game.games.minecraftleague.objective.GameObjective; + +public class ReturnSkullObjective extends GameObjective +{ + public ReturnSkullObjective() + { + super("RETURN_SKULL", "Return the Skull to your Altar!"); + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/WitherObjective.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/WitherObjective.java new file mode 100644 index 000000000..d7dc13823 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minecraftleague/variation/wither/data/objectives/WitherObjective.java @@ -0,0 +1,11 @@ +package nautilus.game.arcade.game.games.minecraftleague.variation.wither.data.objectives; + +import nautilus.game.arcade.game.games.minecraftleague.objective.GameObjective; + +public class WitherObjective extends GameObjective +{ + public WitherObjective(String instruction) + { + super("WITHER_OBJ", instruction); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java index c4cbf7053..3931b7f3d 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/minestrike/MineStrike.java @@ -3124,7 +3124,7 @@ public class MineStrike extends TeamGame } else if (event.getMessage().equalsIgnoreCase("/rpon")) { - event.getPlayer().setResourcePack(GetType().getResourcePackUrl()); + Manager.getResourcePackManager().setPlayerPack(event.getPlayer()); UtilPlayer.message(event.getPlayer(), F.main("Resource Pack", "Resource Pack: " + C.cGreen + "Enabled")); UtilPlayer.message(event.getPlayer(), F.main("Resource Pack", "Type " + F.elem("/rpoff") + " to disable.")); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/ElytraRings.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/ElytraRings.java new file mode 100644 index 000000000..0849aa965 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/ElytraRings.java @@ -0,0 +1,253 @@ +package nautilus.game.arcade.game.games.rings; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.UtilAction; +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilMath; +import mineplex.core.common.util.UtilParticle; +import mineplex.core.common.util.UtilPlayer; +import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilParticle.ParticleType; +import mineplex.core.common.util.UtilParticle.ViewDist; +import mineplex.core.common.util.UtilShapes; +import mineplex.core.updater.UpdateType; +import mineplex.core.updater.event.UpdateEvent; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.GameType; +import nautilus.game.arcade.events.GameStateChangeEvent; +import nautilus.game.arcade.events.PlayerGameRespawnEvent; +import nautilus.game.arcade.game.SoloGame; +import nautilus.game.arcade.game.games.uhc.KitUHC; +import nautilus.game.arcade.kit.Kit; + +public class ElytraRings extends SoloGame +{ + private HashMap _rings = new HashMap(); + private HashMap _goneThrough = new HashMap(); + private HashMap _lastLocation = new HashMap(); + + public ElytraRings(ArcadeManager manager) + { + super(manager, GameType.ElytraRings, new Kit[] + { +// new KitElytraRings(manager) + }, new String[] + { + "Fly through the rings!" + }); + + DeathOut = false; + DeathMessages = false; + } + + public void RespawnPlayer(final Player player) + { + player.eject(); + + if (_goneThrough.containsKey(player.getUniqueId()) && _rings.containsKey(_goneThrough.get(player.getUniqueId()))) + { + Ring ring = _rings.get(_goneThrough.get(player.getUniqueId())); + + player.teleport(ring.getCenter()); + } + else if (_goneThrough.containsKey(player.getUniqueId()) && _rings.containsKey(_goneThrough.get(player.getUniqueId()) + 1)) + { + Ring ring = _rings.get(_goneThrough.get(player.getUniqueId()) + 1); + + player.teleport(ring.getCenter()); + } + else + { + player.teleport(GetTeam(player).GetSpawn()); + } + + Manager.Clear(player); + + // Event + PlayerGameRespawnEvent event = new PlayerGameRespawnEvent(this, player); + UtilServer.getServer().getPluginManager().callEvent(event); + + // Re-Give Kit + Manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(Manager.getPlugin(), new Runnable() + { + public void run() + { + GetKit(player).ApplyKit(player); + } + }, 0); + } + + @Override + public void ParseData() + { + Location loc = UtilAlg.getAverageLocation(GetTeamList().get(0).GetSpawns()); + BlockFace currentDirection = BlockFace.values()[UtilMath.r(4)]; + + while (_rings.size() < 30) + { + int dist = UtilMath.r(40); + + loc = loc.getBlock().getRelative(currentDirection, 20).getLocation(); + + generateRing(loc, currentDirection, 2 + UtilMath.r(2) + UtilMath.r(2)); + } + + loc = loc.getBlock().getRelative(currentDirection, 20).getLocation(); + + Ring ring = generateRing(loc, currentDirection, 7); + + for (Block b : ring.getRing()) + { + b.setType(Material.GOLD_BLOCK); + } + } + + @EventHandler + public void onGameStart(GameStateChangeEvent event) + { + if (event.GetState() != GameState.Prepare) + return; + + for (Player player : this.GetPlayers(true)) + { + player.getInventory().setChestplate(new ItemStack(Material.ELYTRA)); + } + } + + @EventHandler + public void onMove(PlayerMoveEvent event) + { + if (event.isCancelled()) + return; + + if (!IsAlive(event.getPlayer())) + return; + + Player player = event.getPlayer(); + int current = 1; + + if (_goneThrough.containsKey(player.getUniqueId())) + { + current = _goneThrough.get(player.getUniqueId()) + 1; + } + + if (!_rings.containsKey(current)) + { + return; + } + + Ring ring = _rings.get(current); + + if (!ring.isMoveThroughRing(event.getFrom(), event.getTo())) + { + return; + } + + _goneThrough.put(player.getUniqueId(), current + 1); + + Announce(player.getName() + " has gone through ring " + current + "!"); + } + + @EventHandler + public void onSpeedBoost(UpdateEvent event) + { + if (event.getType() != UpdateType.TICK) + return; + + for (Player player : GetPlayers(true)) + { + float exp = player.getExp(); + + exp += 0.02; + + if (exp > 0.05 && _lastLocation.containsKey(player.getUniqueId())) + { + UtilAction.velocity(player, player.getLocation().getDirection().multiply(0.3)); + + if (!_goneThrough.containsKey(player.getUniqueId()) + || _rings.containsKey(_goneThrough.get(player.getUniqueId()) + 1)) + { + exp -= 0.05; + } + + for (Location loc : UtilShapes.getLinesDistancedPoints(_lastLocation.get(player.getUniqueId()), + player.getLocation(), 0.3)) + { + UtilParticle.PlayParticleToAll(ParticleType.CLOUD, loc, 0.2F, 0.2F, 0.2F, 0, 3, ViewDist.LONGER); + } + + _lastLocation.put(player.getUniqueId(), player.getLocation()); + } + + player.setExp(Math.min(exp, 1)); + } + } + + @EventHandler + public void onToggleSneak(PlayerToggleSneakEvent event) + { + if (!IsAlive(event.getPlayer())) + { + return; + } + + Player player = event.getPlayer(); + + if (event.isSneaking() && UtilPlayer.isGliding(player)) + { + _lastLocation.put(player.getUniqueId(), player.getLocation()); + } + else + { + _lastLocation.remove(player.getUniqueId()); + } + } + + private Ring generateRing(Location center, BlockFace direction, int size) + { + ArrayList blocks = new ArrayList(); + ArrayList hole = new ArrayList(); + + for (Location loc : UtilShapes.rotate(UtilShapes.getSphereBlocks(center, size, size, true), + UtilShapes.getFacing(direction))) + { + blocks.add(loc.getBlock()); + } + + size--; + + for (Location loc : UtilShapes.rotate(UtilShapes.getSphereBlocks(center, size, size, false), + UtilShapes.getFacing(direction))) + { + hole.add(loc.getBlock()); + } + + center.setDirection(new Vector(direction.getModX(), direction.getModY(), direction.getModZ())); + + Ring ring = new Ring(blocks, hole, center.clone()); + + for (Block b : ring.getRing()) + { + b.setTypeIdAndData(Material.STAINED_CLAY.getId(), (byte) 4, false); + } + + _rings.put(_rings.size() + 1, ring); + + return ring; + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/Ring.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/Ring.java new file mode 100644 index 000000000..8004c3496 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/rings/Ring.java @@ -0,0 +1,73 @@ +package nautilus.game.arcade.game.games.rings; + +import java.util.ArrayList; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.util.Vector; + +import mineplex.core.common.util.UtilAlg; +import mineplex.core.common.util.UtilMath; + +public class Ring +{ + private ArrayList _core = new ArrayList(); + private ArrayList _ring = new ArrayList(); + private Location _center; + + public Ring(ArrayList blocks, ArrayList inside, Location center) + { + _core = inside; + _ring = blocks; + _center = center; + } + + public Location getCenter() + { + return _center; + } + + public ArrayList getRing() + { + return _ring; + } + + public boolean isMoveThroughRing(Location from, Location to) + { + from = from.clone(); + to = to.clone(); + from.setX(from.getBlockX() + 0.5); + from.setY(from.getBlockY() + 0.5); + from.setZ(from.getBlockZ() + 0.5); + to.setX(to.getBlockX() + 0.5); + to.setY(to.getBlockY() + 0.5); + to.setZ(to.getBlockZ() + 0.5); + + Vector vec = UtilAlg.getTrajectory(from, to).multiply(0.5); + double dist = UtilMath.offset(from, to); + + while (dist > 0) + { + dist -= 0.5; + + Location loc = from.getBlock().getLocation().add(0.5, 0.5, 0.5); + + if (_core.contains(loc.getBlock())) + return true; + + if (_core.contains(loc.clone().add(loc.getX() == 0 ? 0 : loc.getX() > 0 ? 1 : -1, 0, 0))) + return true; + + if (_core.contains(loc.clone().add(0, loc.getY() == 0 ? 0 : loc.getY() > 0 ? 1 : -1, 0))) + return true; + + if (_core.contains(loc.clone().add(0, 0, loc.getZ() == 0 ? 0 : loc.getZ() > 0 ? 1 : -1))) + return true; + + from.add(vec); + } + + return false; + } + +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/Snake.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/Snake.java index 4fc2b6043..0c4b96110 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/Snake.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/Snake.java @@ -29,6 +29,7 @@ import org.bukkit.util.Vector; import net.minecraft.server.v1_8_R3.EntityCreature; import net.minecraft.server.v1_8_R3.Navigation; +import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity; import mineplex.core.common.util.C; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilBlock; @@ -52,6 +53,9 @@ import nautilus.game.arcade.GameType; import nautilus.game.arcade.events.GamePrepareCountdownCommence; import nautilus.game.arcade.events.GameStateChangeEvent; import nautilus.game.arcade.game.SoloGame; +import nautilus.game.arcade.game.Game.GameState; +import nautilus.game.arcade.game.games.snake.events.SlimeUpgradeEvent; +import nautilus.game.arcade.game.games.snake.events.TailGrowEvent; import nautilus.game.arcade.game.games.snake.kits.KitInvulnerable; import nautilus.game.arcade.game.games.snake.kits.KitReverser; import nautilus.game.arcade.game.games.snake.kits.KitSpeed; @@ -63,57 +67,6 @@ import nautilus.game.arcade.stats.SlimySheepStatTracker; public class Snake extends SoloGame { - public static class TailGrowEvent extends PlayerEvent - { - private static final HandlerList handlers = new HandlerList(); - - public static HandlerList getHandlerList() - { - return handlers; - } - - @Override - public HandlerList getHandlers() - { - return getHandlerList(); - } - - private final int _length; - - public TailGrowEvent(Player who, int length) - { - super(who); - - _length = length; - } - - public int getLength() - { - return _length; - } - } - - public static class SlimeUpgradeEvent extends PlayerEvent - { - private static final HandlerList handlers = new HandlerList(); - - public static HandlerList getHandlerList() - { - return handlers; - } - - @Override - public HandlerList getHandlers() - { - return getHandlerList(); - } - - public SlimeUpgradeEvent(Player who) - { - super(who); - } - } - private double _maxSpeed = 180; private HashMap> _tail = new HashMap>(); @@ -730,4 +683,22 @@ public class Snake extends SoloGame } } } + + @EventHandler + public void handleInteractEntityPacket(GameStateChangeEvent event) + { + if (event.GetState() == GameState.Dead) + { + _tail.clear(); + _food.clear(); + _color.clear(); + _invul.clear(); + _speed.clear(); + _reverse.clear(); + _move.clear(); + _moveTime.clear(); + + HandlerList.unregisterAll(this); + } + } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/SlimeUpgradeEvent.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/SlimeUpgradeEvent.java new file mode 100644 index 000000000..54deee3b8 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/SlimeUpgradeEvent.java @@ -0,0 +1,26 @@ +package nautilus.game.arcade.game.games.snake.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class SlimeUpgradeEvent extends PlayerEvent +{ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() + { + return handlers; + } + + @Override + public HandlerList getHandlers() + { + return getHandlerList(); + } + + public SlimeUpgradeEvent(Player who) + { + super(who); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/TailGrowEvent.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/TailGrowEvent.java new file mode 100644 index 000000000..33e0031ab --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/snake/events/TailGrowEvent.java @@ -0,0 +1,35 @@ +package nautilus.game.arcade.game.games.snake.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class TailGrowEvent extends PlayerEvent +{ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() + { + return handlers; + } + + @Override + public HandlerList getHandlers() + { + return getHandlerList(); + } + + private final int _length; + + public TailGrowEvent(Player who, int length) + { + super(who); + + _length = length; + } + + public int getLength() + { + return _length; + } +} \ No newline at end of file diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/turfforts/TurfForts.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/turfforts/TurfForts.java index 7b5a20b00..e90c94eec 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/turfforts/TurfForts.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/turfforts/TurfForts.java @@ -44,6 +44,9 @@ import mineplex.core.common.util.UtilGear; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilTime; +import mineplex.core.elo.EloPlayer; +import mineplex.core.elo.EloTeam; +import mineplex.core.elo.GameResult; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; @@ -369,7 +372,7 @@ public class TurfForts extends TeamGame //On Own Block block = event.getBlock().getRelative(BlockFace.DOWN); - while (block.getTypeId() == 0) + while (block.getTypeId() == 0 && block.getY() > 0) block = block.getRelative(BlockFace.DOWN); if (block.getData() != team.GetColorData()) @@ -851,9 +854,12 @@ public class TurfForts extends TeamGame AddGems(player, 10, "Participation", false, false); } + endElo(); + //End SetState(GameState.End); } + public Long getEnemyTurfEntranceTime(Player player) { diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellRumble.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellRumble.java index 59d85e116..936af0589 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellRumble.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellRumble.java @@ -1,6 +1,7 @@ package nautilus.game.arcade.game.games.wizards.spells; import java.util.ArrayList; +import java.util.UUID; import mineplex.core.common.util.UtilBlock; import mineplex.core.common.util.UtilMath; @@ -325,6 +326,7 @@ public class SpellRumble extends Spell implements SpellClickBlock, SpellClick fallingSpawn.i = 70; fallingSpawn.k = block.getTypeId() | block.getData() << 16; fallingSpawn.f = 10000; + fallingSpawn.uuid = UUID.randomUUID(); final Collection players = Bukkit.getOnlinePlayers(); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellSummonWolves.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellSummonWolves.java index cdfbe7b97..e546be6dc 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellSummonWolves.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wizards/spells/SpellSummonWolves.java @@ -4,6 +4,8 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Random; +import com.google.common.base.Optional; +import mineplex.core.common.util.SpigotUtil; import mineplex.core.common.util.UtilBlock; import mineplex.core.common.util.UtilParticle; import mineplex.core.common.util.UtilServer; @@ -16,17 +18,15 @@ import nautilus.game.arcade.game.games.wizards.Spell; import nautilus.game.arcade.game.games.wizards.spellinterfaces.SpellClick; import nautilus.game.arcade.game.games.wizards.spellinterfaces.SpellClickBlock; +import net.minecraft.server.v1_8_R3.EntityWolf; import org.bukkit.DyeColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; -import org.bukkit.entity.AnimalTamer; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.entity.Wolf; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftWolf; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; public class SpellSummonWolves extends Spell implements SpellClick, SpellClickBlock @@ -57,6 +57,7 @@ public class SpellSummonWolves extends Spell implements SpellClick, SpellClickBl wolf.setCollarColor(DyeColor.YELLOW); wolf.setTamed(true); + SpigotUtil.setOldOwner_RemoveMeWhenSpigotFixesThis(wolf, player); wolf.setOwner(player); wolf.setBreed(false); wolf.setCustomName(player.getDisplayName() + "'s Wolf"); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/kit/perks/PerkWolfPet.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/kit/perks/PerkWolfPet.java index 027066090..1c0dda66b 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/kit/perks/PerkWolfPet.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/kit/perks/PerkWolfPet.java @@ -23,15 +23,7 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; -import mineplex.core.common.util.C; -import mineplex.core.common.util.F; -import mineplex.core.common.util.UtilAction; -import mineplex.core.common.util.UtilBlock; -import mineplex.core.common.util.UtilEnt; -import mineplex.core.common.util.UtilMath; -import mineplex.core.common.util.UtilPlayer; -import mineplex.core.common.util.UtilServer; -import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.*; import mineplex.core.recharge.Recharge; import mineplex.core.updater.event.UpdateEvent; import mineplex.core.updater.UpdateType; @@ -99,6 +91,7 @@ public class PerkWolfPet extends Perk Wolf wolf = cur.getWorld().spawn(cur.getLocation(), Wolf.class); Manager.GetGame().CreatureAllowOverride = false; + SpigotUtil.setOldOwner_RemoveMeWhenSpigotFixesThis(wolf, cur); wolf.setOwner(cur); wolf.setCollarColor(DyeColor.GREEN); wolf.playEffect(EntityEffect.WOLF_HEARTS); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java index ff47122fb..4300dfd09 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameFlagManager.java @@ -1,8 +1,9 @@ package nautilus.game.arcade.managers; -import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; import mineplex.core.antihack.AntiHack; +import mineplex.core.common.MinecraftVersion; import mineplex.core.common.Rank; import mineplex.core.common.util.C; import mineplex.core.common.util.F; @@ -13,8 +14,10 @@ import mineplex.core.common.util.UtilInv; import mineplex.core.common.util.UtilMath; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; +import mineplex.core.common.util.UtilTextBottom; import mineplex.core.common.util.UtilTextMiddle; import mineplex.core.common.util.UtilTime; +import mineplex.core.common.util.UtilTime.TimeUnit; import mineplex.core.itemstack.ItemStackFactory; import mineplex.core.recharge.Recharge; import mineplex.core.teleport.event.MineplexTeleportEvent; @@ -32,6 +35,8 @@ import nautilus.game.arcade.game.GameTeam; import nautilus.game.arcade.game.GameTeam.PlayerState; import nautilus.game.arcade.kit.perks.event.PerkDestructorBlockEvent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.Sound; @@ -45,6 +50,7 @@ import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBurnEvent; @@ -53,6 +59,7 @@ import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; @@ -72,6 +79,9 @@ import org.bukkit.util.Vector; public class GameFlagManager implements Listener { ArcadeManager Manager; + SecondaryDamageManager Secondary; + private ConcurrentHashMap _respawnTimers = new ConcurrentHashMap(); + private ConcurrentHashMap _respawnRunnables = new ConcurrentHashMap(); public GameFlagManager(ArcadeManager manager) { @@ -79,6 +89,33 @@ public class GameFlagManager implements Listener Manager.getPluginManager().registerEvents(this, Manager.getPlugin()); } + + @EventHandler + public void triggerSecondary(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTEST) + return; + + if (Secondary == null) + { + if (!Manager.GetDamage().IsEnabled()) + { + Secondary = new SecondaryDamageManager(Manager); + Bukkit.getPluginManager().registerEvents(Secondary, Manager.getPlugin()); + } + } + else + { + if (Manager.GetDamage().IsEnabled()) + { + if (Secondary != null) + { + HandlerList.unregisterAll(Secondary); + Secondary = null; + } + } + } + } @EventHandler(priority = EventPriority.LOW) public void DamageEvent(CustomDamageEvent event) @@ -737,6 +774,8 @@ public class GameFlagManager implements Listener if (game.GetTeam(player).GetRespawnTime() > time) time = game.GetTeam(player).GetRespawnTime(); + final double timeF = time; + UtilInv.Clear(player); Manager.GetCondition().Factory().Cloak("Ghost", player, player, time, false, false); player.setAllowFlight(true); @@ -761,8 +800,15 @@ public class GameFlagManager implements Listener UtilPlayer.message(player, C.cWhite + C.Bold + "You will respawn in " + time + " seconds..."); UtilTextMiddle.display(null, "Respawning in " + time + " seconds...", 5, 40, 5, player); } - Manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(Manager.getPlugin(), new Runnable() + { + public void run() + { + Long t = Double.valueOf(timeF).longValue(); + _respawnTimers.put(player, System.currentTimeMillis() + UtilTime.convert(t, TimeUnit.SECONDS, TimeUnit.MILLISECONDS)); + } + }, 6); + int run = Manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(Manager.getPlugin(), new Runnable() { public void run() { @@ -778,8 +824,11 @@ public class GameFlagManager implements Listener player.setFireTicks(0); UtilAction.zeroVelocity(player); + + _respawnRunnables.remove(player); } }, (int)(time * 20d)); + _respawnRunnables.put(player, run); } } @@ -912,12 +961,22 @@ public class GameFlagManager implements Listener Manager.GetDamage().NewDamageEvent(player, null, null, DamageCause.VOID, 4, false, false, false, "Border", "Border Damage"); + + if (!Manager.GetDamage().IsEnabled()) + { + Bukkit.getPluginManager().callEvent(new EntityDamageEvent(player, DamageCause.VOID, 4)); + } player.getWorld().playSound(player.getLocation(), Sound.NOTE_BASS, 2f, 1f); player.getWorld().playSound(player.getLocation(), Sound.NOTE_BASS, 2f, 1f); } else { + if (!Manager.GetDamage().IsEnabled()) + { + Bukkit.getPluginManager().callEvent(new EntityDamageEvent(player, DamageCause.VOID, 9001)); + } + Manager.GetDamage().NewDamageEvent(player, null, null, DamageCause.VOID, 9001, false, false, false, "Border", "Border Damage"); @@ -1204,9 +1263,57 @@ public class GameFlagManager implements Listener if (Manager.GetGame() == null) return; - if (Manager.GetGame().GetType().getResourcePackUrl() == null) + if (Manager.GetGame().GetType().getResourcePackUrls() == null || Manager.GetGame().GetType().getResourcePackUrls().length == 0) return; UtilTextMiddle.display(C.cGold + C.Bold + Manager.GetGame().GetType().GetName(), "Make sure you accept the Resource Pack", 20, 120, 20, event.getPlayer()); } + + @EventHandler + public void displayRespawnTimer(UpdateEvent event) + { + if (event.getType() != UpdateType.FASTEST) + return; + + if (Manager.GetGame() == null) + { + _respawnTimers.clear(); + for (Integer r : _respawnRunnables.values()) + { + Bukkit.getScheduler().cancelTask(r); + } + _respawnRunnables.clear(); + return; + } + if (!Manager.GetGame().IsLive()) + { + _respawnTimers.clear(); + for (Integer r : _respawnRunnables.values()) + { + Bukkit.getScheduler().cancelTask(r); + } + _respawnRunnables.clear(); + return; + } + for (Player player : _respawnTimers.keySet()) + { + if (!player.isOnline()) + { + _respawnTimers.remove(player); + continue; + } + if (System.currentTimeMillis() >= _respawnTimers.get(player)) + { + _respawnTimers.remove(player); + continue; + } + long sec = UtilTime.convert(_respawnTimers.get(player) - System.currentTimeMillis(), TimeUnit.MILLISECONDS, TimeUnit.SECONDS); + ChatColor color = ChatColor.RED; + if (sec < 8) + color = ChatColor.YELLOW; + if (sec < 4) + color = ChatColor.GREEN; + UtilTextBottom.display(color + "Respawning In: " + sec + " Seconds", player); + } + } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameHostManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameHostManager.java index 7f1126a81..1e5eb71c5 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameHostManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameHostManager.java @@ -208,7 +208,7 @@ public class GameHostManager implements Listener } @EventHandler - public void whitelistJoin(PlayerLoginEvent event) + public void handleLogin(PlayerLoginEvent event) { Player p = event.getPlayer(); if (Manager.GetServerConfig().PlayerServerWhitelist){ @@ -220,6 +220,8 @@ public class GameHostManager implements Listener event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, "This MPS is whitelisted."); } } + if (_blacklist.contains(p.getName())) + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, "You were removed from this Mineplex Private Server."); } @EventHandler @@ -791,12 +793,6 @@ public class GameHostManager implements Listener { if (!isPrivateServer()) return; - - if (_blacklist.contains(event.getPlayer().getName())) - { - Manager.GetPortal().sendToHub(event.getPlayer(), "You were kicked from this Mineplex Private Server."); - return; - } String serverName = Manager.getPlugin().getConfig().getString("serverstatus.name"); UtilPlayer.message(event.getPlayer(), ChatColor.BOLD + "Welcome to Mineplex Private Servers!"); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java index a77e3f72b..5f7a4612f 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameLobbyManager.java @@ -19,17 +19,13 @@ import mineplex.core.common.util.UtilBlockText.TextAlign; import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilFirework; import mineplex.core.common.util.UtilInv; -import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; import mineplex.core.common.util.UtilWorld; import mineplex.core.cosmetic.event.ActivateGemBoosterEvent; import mineplex.core.donation.Donor; import mineplex.core.event.CustomTagEvent; -import mineplex.core.packethandler.IPacketHandler; import mineplex.core.packethandler.PacketHandler; -import mineplex.core.packethandler.PacketInfo; -import mineplex.core.packethandler.PacketVerifier; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import mineplex.minecraft.game.core.damage.CustomDamageEvent; @@ -43,9 +39,6 @@ import nautilus.game.arcade.game.games.uhc.UHC; import nautilus.game.arcade.kit.Kit; import nautilus.game.arcade.kit.KitAvailability; import nautilus.game.arcade.kit.KitSorter; -import net.minecraft.server.v1_8_R3.DataWatcher.WatchableObject; -import net.minecraft.server.v1_8_R3.Packet; -import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -106,6 +99,7 @@ public class GameLobbyManager implements Listener private NautHashMap _scoreboardMap = new NautHashMap(); private NautHashMap _gemMap = new NautHashMap(); private NautHashMap _eloMap = new NautHashMap(); + private NautHashMap _divisionMap = new NautHashMap(); private NautHashMap _kitMap = new NautHashMap(); private int _oldPlayerCount = 0; @@ -1119,14 +1113,14 @@ public class GameLobbyManager implements Listener entry.getValue().resetScores(_kitMap.get(entry.getKey()) + ""); // Set new - objective.getScore(" ").setScore(line--); + objective.getScore(" ").setScore(line--); objective.getScore(teamColor + C.Bold + "Kit").setScore(line--); objective.getScore(kitName + "").setScore(line--); _kitMap.put(entry.getKey(), kitName + ""); } - objective.getScore(" ").setScore(line--); + objective.getScore(" ").setScore(line--); objective.getScore(C.cGreen + C.Bold + "Gems").setScore(line--); // Remove old @@ -1137,21 +1131,21 @@ public class GameLobbyManager implements Listener _gemMap.put(entry.getKey(), Manager.GetDonation().Get(entry.getKey().getName()).GetGems()); //Server - objective.getScore(" ").setScore(line--); + objective.getScore(" ").setScore(line--); objective.getScore(C.cAqua + C.Bold + "Server").setScore(line--); objective.getScore(_serverName).setScore(line--); - - //ELO + + // ELO DIVISION if (Manager.GetGame() != null && Manager.GetGame().EloRanking) { objective.getScore(" ").setScore(line--); - objective.getScore(C.cPurple + C.Bold + "Elo").setScore(line--); + objective.getScore(C.cPurpleB + C.Bold + "Division").setScore(line--); // Remove old - entry.getValue().resetScores(_eloMap.get(entry.getKey()) + " "); + entry.getValue().resetScores(_divisionMap.get(entry.getKey()) + " "); // Set new - objective.getScore(Manager.getEloManager().getElo(entry.getKey().getUniqueId(), Manager.GetGame().GetName()) + " ").setScore(line--); - + + objective.getScore(Manager.getEloManager().getPlayerDivision(entry.getKey(), Manager.GetGame().GetType().getGameId()) + " ").setScore(line--); } } diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameSpectatorManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameSpectatorManager.java index 4515bcf47..b067a806d 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameSpectatorManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/GameSpectatorManager.java @@ -224,6 +224,9 @@ public class GameSpectatorManager implements Listener @Override public void run() { + if (Manager.GetGame().IsAlive(player)) + return; + Player ptarget = null; if (target instanceof Player) ptarget = (Player) target; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/SecondaryDamageManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/SecondaryDamageManager.java new file mode 100644 index 000000000..adcb4c103 --- /dev/null +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/SecondaryDamageManager.java @@ -0,0 +1,187 @@ +package nautilus.game.arcade.managers; + +import mineplex.minecraft.game.core.condition.Condition.ConditionType; +import mineplex.minecraft.game.core.condition.events.ConditionApplyEvent; +import nautilus.game.arcade.ArcadeManager; +import nautilus.game.arcade.game.Game; +import nautilus.game.arcade.game.Game.GameState; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; + +public class SecondaryDamageManager implements Listener +{ + ArcadeManager Manager; + public SecondaryDamageManager(ArcadeManager manager) + { + Manager = manager; + } + + @EventHandler(priority = EventPriority.LOW) + public void EntDamage(EntityDamageEvent event) + { + Game game = Manager.GetGame(); + if (game == null) + { + event.setCancelled(true); + return; + } + if (!(event.getEntity() instanceof LivingEntity)) + return; + + LivingEntity ent = (LivingEntity) event.getEntity(); + if (ent.getWorld().getName().equals("world")) + { + event.setCancelled(true); + + if (event.getCause() == DamageCause.VOID) + ent.teleport(Manager.GetLobby().GetSpawn()); + + return; + } + + if (Manager.isSpectator(ent)) + { + event.setCancelled(true); + if (ent.getFireTicks() > 0) + { + ent.setFireTicks(-1); + } + + return; + } + + if (game.GetState() != GameState.Live) + { + event.setCancelled(true); + return; + } + + if (!game.Damage) + { + event.setCancelled(true); + return; + } + + if (ent instanceof Player) + { + if (!game.IsAlive((Player)ent)) + { + event.setCancelled(true); + return; + } + } + + if (event.getCause() == DamageCause.FALL) + { + if (!game.DamageFall) + { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void DamageEvent(EntityDamageByEntityEvent event) + { + Game game = Manager.GetGame(); + if (game == null) + return; + + if (!(event.getEntity() instanceof LivingEntity)) + return; + + LivingEntity damagee = (LivingEntity)event.getEntity(); + + if (event.getDamager() instanceof LivingEntity || event.getDamager() instanceof Projectile) + { + LivingEntity damager = null; + if (event.getDamager() instanceof LivingEntity) + { + damager = (LivingEntity)event.getDamager(); + } + else + { + if (((Projectile)event.getDamager()).getShooter() instanceof LivingEntity) + { + damager = (LivingEntity)((Projectile)event.getDamager()).getShooter(); + } + } + //Damager Spec + if (damager != null && Manager.isSpectator(damager)) + { + event.setCancelled(true); + return; + } + + if (damager != null && damager instanceof Player && !game.IsAlive((Player)damager)) + { + event.setCancelled(true); + return; + } + + //Entity vs Entity + if (damagee != null && damager != null) + { + //PvP + if (damagee instanceof Player && damager instanceof Player) + { + if (!Manager.canHurt((Player)damagee, (Player)damager)) + { + event.setCancelled(true); + return; + } + } + //PvE + else if (damager instanceof Player) + { + if (!game.DamagePvE) + { + event.setCancelled(true); + return; + } + } + //EvP + else if (damagee instanceof Player) + { + if (!game.DamageEvP) + { + event.setCancelled(true); + return; + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void DamageExplosion(ConditionApplyEvent event) + { + if (event.isCancelled()) + return; + + if (event.GetCondition().GetType() != ConditionType.EXPLOSION) + return; + + LivingEntity damagee = event.GetCondition().GetEnt(); + if (damagee == null) return; + if (!(damagee instanceof Player)) return; + + LivingEntity damager = event.GetCondition().GetSource(); + if (damager == null) return; + if (!(damager instanceof Player)) return; + + if (Manager.canHurt((Player)damagee, (Player)damager)) + return; + + event.setCancelled(true); + } +} diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/chat/GameChatManager.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/chat/GameChatManager.java index 9a195ef1c..0d9dea0fa 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/chat/GameChatManager.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/managers/chat/GameChatManager.java @@ -33,6 +33,8 @@ public class GameChatManager implements Listener private ArcadeManager _manager; private LinkedList _chatStats; + + public boolean TeamSpy; public GameChatManager(ArcadeManager manager) { @@ -41,6 +43,8 @@ public class GameChatManager implements Listener _manager.getPluginManager().registerEvents(this, _manager.getPlugin()); _chatStats = new LinkedList(); + + TeamSpy = true; } @EventHandler @@ -157,7 +161,10 @@ public class GameChatManager implements Listener format = event.getFormat().split(rankStr)[0]; name = _manager.GetColor(sender) + sender.getName() + C.Reset; - message = event.getFormat().split(sender.getName())[1].replace("%2$s", "") + _manager.GetChat().getFilteredMessage(sender, event.getMessage()); + if (event.getMessage().charAt(0) == '@') + message = event.getFormat().split(sender.getName())[1].replace("%2$s", "") + _manager.GetChat().getFilteredMessage(sender, event.getMessage().substring(1, event.getMessage().length())); + else + message = event.getFormat().split(sender.getName())[1].replace("%2$s", "") + _manager.GetChat().getFilteredMessage(sender, event.getMessage()); if (_manager.GetGame() == null || _manager.GetGame().GetState() != GameState.Live) { @@ -230,7 +237,10 @@ public class GameChatManager implements Listener Player receiver = recipientIterator.next(); if (!_manager.GetServerConfig().Tournament && _manager.GetClients().Get(receiver).GetRank().has(Rank.MODERATOR)) - continue; + { + if (TeamSpy) + continue; + } GameTeam recTeam = _manager.GetGame().GetTeam(receiver); GameTeam sendTeam = _manager.GetGame().GetTeam(sender); diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/ChooChooStatTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/ChooChooStatTracker.java index 21d3e9705..73625353b 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/ChooChooStatTracker.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/ChooChooStatTracker.java @@ -4,7 +4,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import nautilus.game.arcade.game.Game; -import nautilus.game.arcade.game.games.snake.Snake; +import nautilus.game.arcade.game.games.snake.events.TailGrowEvent; public class ChooChooStatTracker extends StatTracker { @@ -14,7 +14,7 @@ public class ChooChooStatTracker extends StatTracker } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) - public void onTailGrow(Snake.TailGrowEvent event) + public void onTailGrow(TailGrowEvent event) { if (getGame().GetState() != Game.GameState.Live) return; diff --git a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/SlimySheepStatTracker.java b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/SlimySheepStatTracker.java index 5d64b37ef..32df1f4b4 100644 --- a/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/SlimySheepStatTracker.java +++ b/Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/stats/SlimySheepStatTracker.java @@ -8,7 +8,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import nautilus.game.arcade.game.Game; -import nautilus.game.arcade.game.games.snake.Snake; +import nautilus.game.arcade.game.games.snake.events.SlimeUpgradeEvent; public class SlimySheepStatTracker extends StatTracker { @@ -20,7 +20,7 @@ public class SlimySheepStatTracker extends StatTracker } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) - public void onSlimeUpgrade(Snake.SlimeUpgradeEvent event) + public void onSlimeUpgrade(SlimeUpgradeEvent event) { if (getGame().GetState() != Game.GameState.Live) return; diff --git a/Plugins/pom.xml b/Plugins/pom.xml index d2bfb0b8c..fc85e9849 100644 --- a/Plugins/pom.xml +++ b/Plugins/pom.xml @@ -1,4 +1,3 @@ - 4.0.0 @@ -134,13 +133,13 @@ com.mineplex spigot - 1.8.8-R0.1-SNAPSHOT + 1.8.8-1.9-SNAPSHOT compile redis.clients jedis - 2.6.2 + 2.8.1 compile