Merge pull request #193 from Mineplex-LLC/develop

PPC Changes from Connor
This commit is contained in:
LCastr0 2016-09-02 17:32:02 -03:00 committed by GitHub
commit b335039749
100 changed files with 7738 additions and 951 deletions

View File

@ -19,7 +19,33 @@
package com.java.sk89q.jnbt;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.NBTBase;
import net.minecraft.server.v1_8_R3.NBTTagByte;
import net.minecraft.server.v1_8_R3.NBTTagByteArray;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.NBTTagDouble;
import net.minecraft.server.v1_8_R3.NBTTagEnd;
import net.minecraft.server.v1_8_R3.NBTTagFloat;
import net.minecraft.server.v1_8_R3.NBTTagInt;
import net.minecraft.server.v1_8_R3.NBTTagIntArray;
import net.minecraft.server.v1_8_R3.NBTTagList;
import net.minecraft.server.v1_8_R3.NBTTagLong;
import net.minecraft.server.v1_8_R3.NBTTagShort;
import net.minecraft.server.v1_8_R3.NBTTagString;
/**
* A class which contains NBT-related utility methods.
@ -166,5 +192,250 @@ public final class NBTUtils {
}
return expected.cast(tag);
}
public static byte[] toBytesCompressed(String name, CompoundTag tag)
{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try (NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(byteStream)))
{
nbtStream.writeNamedTag(name, tag);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return byteStream.toByteArray();
}
public static NamedTag getFromBytesCompressed(byte[] bytes)
{
try (NBTInputStream stream = new NBTInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)));)
{
return stream.readNamedTag();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public static NBTBase toNative(Tag tag) {
if (tag instanceof IntArrayTag) {
return toNative((IntArrayTag) tag);
} else if (tag instanceof ListTag) {
return toNative((ListTag) tag);
} else if (tag instanceof LongTag) {
return toNative((LongTag) tag);
} else if (tag instanceof StringTag) {
return toNative((StringTag) tag);
} else if (tag instanceof IntTag) {
return toNative((IntTag) tag);
} else if (tag instanceof ByteTag) {
return toNative((ByteTag) tag);
} else if (tag instanceof ByteArrayTag) {
return toNative((ByteArrayTag) tag);
} else if (tag instanceof CompoundTag) {
return toNative((CompoundTag) tag);
} else if (tag instanceof FloatTag) {
return toNative((FloatTag) tag);
} else if (tag instanceof ShortTag) {
return toNative((ShortTag) tag);
} else if (tag instanceof DoubleTag) {
return toNative((DoubleTag) tag);
} else {
throw new IllegalArgumentException("Can't convert tag of type " + tag.getClass().getCanonicalName());
}
}
public static NBTTagIntArray toNative(IntArrayTag tag) {
int[] value = tag.getValue();
return new NBTTagIntArray(Arrays.copyOf(value, value.length));
}
public static NBTTagList toNative(ListTag tag) {
NBTTagList list = new NBTTagList();
for (Tag child : tag.getValue()) {
if (child instanceof EndTag) {
continue;
}
list.add(toNative(child));
}
return list;
}
public static NBTTagLong toNative(LongTag tag) {
return new NBTTagLong(tag.getValue());
}
public static NBTTagString toNative(StringTag tag) {
return new NBTTagString(tag.getValue());
}
public static NBTTagInt toNative(IntTag tag) {
return new NBTTagInt(tag.getValue());
}
public static NBTTagByte toNative(ByteTag tag) {
return new NBTTagByte(tag.getValue());
}
public static NBTTagByteArray toNative(ByteArrayTag tag) {
byte[] value = tag.getValue();
return new NBTTagByteArray(Arrays.copyOf(value, value.length));
}
public static NBTTagCompound toNative(CompoundTag tag) {
NBTTagCompound compound = new NBTTagCompound();
for (Entry<String, Tag> child : tag.getValue().entrySet()) {
compound.set(child.getKey(), toNative(child.getValue()));
}
return compound;
}
public static NBTTagFloat toNative(FloatTag tag) {
return new NBTTagFloat(tag.getValue());
}
public static NBTTagShort toNative(ShortTag tag) {
return new NBTTagShort(tag.getValue());
}
public static NBTTagDouble toNative(DoubleTag tag) {
return new NBTTagDouble(tag.getValue());
}
public static Tag fromNative(NBTBase other) {
if (other instanceof NBTTagIntArray) {
return fromNative((NBTTagIntArray) other);
} else if (other instanceof NBTTagList) {
return fromNative((NBTTagList) other);
} else if (other instanceof NBTTagEnd) {
return fromNative((NBTTagEnd) other);
} else if (other instanceof NBTTagLong) {
return fromNative((NBTTagLong) other);
} else if (other instanceof NBTTagString) {
return fromNative((NBTTagString) other);
} else if (other instanceof NBTTagInt) {
return fromNative((NBTTagInt) other);
} else if (other instanceof NBTTagByte) {
return fromNative((NBTTagByte) other);
} else if (other instanceof NBTTagByteArray) {
return fromNative((NBTTagByteArray) other);
} else if (other instanceof NBTTagCompound) {
return fromNative((NBTTagCompound) other);
} else if (other instanceof NBTTagFloat) {
return fromNative((NBTTagFloat) other);
} else if (other instanceof NBTTagShort) {
return fromNative((NBTTagShort) other);
} else if (other instanceof NBTTagDouble) {
return fromNative((NBTTagDouble) other);
} else {
throw new IllegalArgumentException("Can't convert other of type " + other.getClass().getCanonicalName());
}
}
public static IntArrayTag fromNative(NBTTagIntArray other) {
int[] value = other.c();
return new IntArrayTag(Arrays.copyOf(value, value.length));
}
public static ListTag fromNative(NBTTagList other) {
other = (NBTTagList) other.clone();
List<Tag> list = new ArrayList<Tag>();
Class<? extends Tag> listClass = StringTag.class;
int size = other.size();
for (int i = 0; i < size; i++) {
Tag child = fromNative(other.a(0));
list.add(child);
listClass = child.getClass();
}
return new ListTag(listClass, list);
}
public static EndTag fromNative(NBTTagEnd other) {
return new EndTag();
}
public static LongTag fromNative(NBTTagLong other) {
return new LongTag(other.c());
}
public static StringTag fromNative(NBTTagString other) {
return new StringTag(other.a_());
}
public static IntTag fromNative(NBTTagInt other) {
return new IntTag(other.d());
}
public static ByteTag fromNative(NBTTagByte other) {
return new ByteTag(other.f());
}
public static ByteArrayTag fromNative(NBTTagByteArray other) {
byte[] value = other.c();
return new ByteArrayTag(Arrays.copyOf(value, value.length));
}
public static CompoundTag fromNative(NBTTagCompound other) {
@SuppressWarnings("unchecked") Collection<String> tags = other.c();
Map<String, Tag> map = new HashMap<String, Tag>();
for (String tagName : tags) {
map.put(tagName, fromNative(other.get(tagName)));
}
return new CompoundTag(map);
}
public static FloatTag fromNative(NBTTagFloat other) {
return new FloatTag(other.h());
}
public static ShortTag fromNative(NBTTagShort other) {
return new ShortTag(other.e());
}
public static DoubleTag fromNative(NBTTagDouble other) {
return new DoubleTag(other.g());
}
public static NBTTagList doubleArrayToList(double... doubles)
{
NBTTagList nbttaglist = new NBTTagList();
for(double d : doubles)
{
nbttaglist.add(new NBTTagDouble(d));
}
return nbttaglist;
}
public static Vector getVector(CompoundTag tag)
{
return new Vector(tag.asDouble("x"), tag.asDouble("y"), tag.asDouble("z"));
}
}

View File

@ -9,16 +9,20 @@ import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.CraftChunk;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.util.BlockVector;
import mineplex.core.common.util.MapUtil;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import net.minecraft.server.v1_8_R3.Chunk;
import net.minecraft.server.v1_8_R3.ChunkCoordIntPair;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayOutMapChunk;
import net.minecraft.server.v1_8_R3.PacketPlayOutMultiBlockChange;
import net.minecraft.server.v1_8_R3.PacketPlayOutMultiBlockChange.MultiBlockChangeInfo;
import net.minecraft.server.v1_8_R3.TileEntity;
import net.minecraft.server.v1_8_R3.WorldServer;
/**
* An agent used to easily record and send multi-block update packets to players. The agent handles if the packet should be a
@ -85,13 +89,13 @@ public class MultiBlockUpdaterAgent
int chunkDist = Math.max(Math.abs(c.locX-x), Math.abs(c.locZ-z));
if(chunkDist > Bukkit.getViewDistance()) continue;
sendPacket(c, players);
sendPacket(c, p);
}
}
}
private void sendPacket(Chunk c, Collection<? extends Player> players)
private void sendPacket(Chunk c, Player...players)
{
List<BlockVector> list = _chunks.get(c);
@ -101,7 +105,7 @@ public class MultiBlockUpdaterAgent
{
for(Player p : players)
{
MapUtil.SendChunkForPlayer(c, p);
UtilPlayer.sendPacket(p, new PacketPlayOutMapChunk(c, true, 65535));
}
}
else
@ -121,6 +125,25 @@ public class MultiBlockUpdaterAgent
UtilPlayer.sendPacket(p, packet);
}
}
Packet<?>[] tileEntities = new Packet[c.tileEntities.size()];
int i = 0;
for(TileEntity te : c.tileEntities.values())
{
tileEntities[i++] = te.getUpdatePacket();
}
for(Player p : players)
{
UtilPlayer.sendPacket(p, tileEntities);
((WorldServer)c.world).getTracker().untrackPlayer(((CraftPlayer)p).getHandle());
}
Bukkit.getScheduler().runTaskLater(UtilServer.getPlugin(), () ->
{
for(Player p : players)
{
((WorldServer)c.world).getTracker().a(((CraftPlayer)p).getHandle(), c);
}
}, 5);
}
}

View File

@ -1,14 +1,34 @@
package mineplex.core.common.block.schematic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;
import com.mysql.jdbc.Util;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.DoubleTag;
import com.java.sk89q.jnbt.NBTUtils;
import com.java.sk89q.jnbt.Tag;
import mineplex.core.common.block.DataLocationMap;
import mineplex.core.common.util.MapUtil;
import mineplex.core.common.util.UtilBlock;
import net.minecraft.server.v1_8_R3.Entity;
import net.minecraft.server.v1_8_R3.EntityTypes;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.NBTTagInt;
import net.minecraft.server.v1_8_R3.TileEntity;
import net.minecraft.server.v1_8_R3.WorldServer;
public class Schematic
{
@ -18,8 +38,11 @@ public class Schematic
private final short[] _blocks;
private final byte[] _blockData;
private final Vector _weOffset;
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData, Vector worldEditOffset)
private final Map<BlockVector, Map<String, Tag>> _tileEntities;
private final List<Tag> _entities;
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData, Vector worldEditOffset, Map<BlockVector, Map<String, Tag>> tileEntities, List<Tag> entities)
{
_width = width;
_height = height;
@ -27,6 +50,18 @@ public class Schematic
_blocks = blocks;
_blockData = blockData;
_weOffset = worldEditOffset;
_tileEntities = tileEntities;
_entities = entities;
}
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData, Vector worldEditOffset, Map<BlockVector, Map<String, Tag>> tileEntities)
{
this(width, height, length, blocks, blockData, worldEditOffset, tileEntities, new ArrayList<>());
}
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData, Vector worldEditOffset)
{
this(width, height, length, blocks, blockData, worldEditOffset, new HashMap<>());
}
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData)
@ -34,29 +69,33 @@ public class Schematic
this(width, height, length, blocks, blockData, null);
}
public DataLocationMap paste(Location originLocation)
public SchematicData paste(Location originLocation)
{
return paste(originLocation, false);
}
public DataLocationMap paste(Location originLocation, boolean ignoreAir)
public SchematicData paste(Location originLocation, boolean ignoreAir)
{
return paste(originLocation, ignoreAir, false);
}
public DataLocationMap paste(Location originLocation, boolean ignoreAir, boolean worldEditOffset)
public SchematicData paste(Location originLocation, boolean ignoreAir, boolean worldEditOffset)
{
if(worldEditOffset && hasWorldEditOffset())
{
originLocation = originLocation.clone().add(_weOffset);
}
DataLocationMap locationMap = new DataLocationMap();
SchematicData output = new SchematicData(locationMap, originLocation.getWorld());
int startX = originLocation.getBlockX();
int startY = originLocation.getBlockY();
int startZ = originLocation.getBlockZ();
UtilBlock.startQuickRecording();
WorldServer nmsWorld = ((CraftWorld)originLocation.getWorld()).getHandle();
for (int x = 0; x < _width; x++)
{
@ -106,16 +145,63 @@ public class Schematic
continue;
}
}
UtilBlock.setQuick(originLocation.getWorld(), startX + x, startY + y, startZ + z, materialId, _blockData[index]);
BlockVector bv = new BlockVector(x,y,z);
output.getBlocksRaw().add(bv);
Map<String, Tag> map = _tileEntities.get(bv);
if(map != null)
{
TileEntity te = nmsWorld.getTileEntity(MapUtil.getBlockPos(bv.add(originLocation.toVector())));
if(te == null) continue;
CompoundTag weTag = new CompoundTag(map);
NBTTagCompound tag = NBTUtils.toNative(weTag);
tag.set("x", new NBTTagInt(tag.getInt("x") + startX));
tag.set("y", new NBTTagInt(tag.getInt("y") + startY));
tag.set("z", new NBTTagInt(tag.getInt("z") + startZ));
te.a(tag);
output.getTileEntitiesRaw().add(bv);
}
}
}
}
UtilBlock.stopQuickRecording();
for(Tag tag : _entities)
{
if(tag instanceof CompoundTag)
{
CompoundTag ctag = (CompoundTag) tag;
NBTTagCompound nmsTag = NBTUtils.toNative(ctag);
List<DoubleTag> list = ctag.getList("Pos", DoubleTag.class);
Vector pos = new Vector(list.get(0).getValue(), list.get(1).getValue(), list.get(2).getValue());
pos.add(originLocation.toVector());
UtilSchematic.setPosition(nmsTag, pos);
list = NBTUtils.fromNative(nmsTag).getList("Pos", DoubleTag.class);
Entity nmsEntity = EntityTypes.a(nmsTag, nmsWorld);
nmsWorld.addEntity(nmsEntity, SpawnReason.CUSTOM);
if(nmsEntity == null) continue;
output.getEntitiesRaw().add(nmsEntity.getBukkitEntity());
}
}
return locationMap;
return output;
}
/**
@ -174,6 +260,13 @@ public class Schematic
{
return _weOffset != null;
}
public Vector getWorldEditOffset()
{
if(!hasWorldEditOffset()) return null;
return _weOffset.clone();
}
public int getSize()
{
@ -187,7 +280,7 @@ public class Schematic
public boolean hasIndex(int index)
{
return index < _blocks.length;
return index < _blocks.length && index >= 0;
}
public Short getBlock(int x, int y, int z)
@ -240,6 +333,16 @@ public class Schematic
{
return _blockData;
}
public List<Tag> getEntities()
{
return _entities;
}
public Map<BlockVector, Map<String, Tag>> getTileEntities()
{
return _tileEntities;
}
@Override
public String toString()

View File

@ -0,0 +1,86 @@
package mineplex.core.common.block.schematic;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.util.BlockVector;
import mineplex.core.common.block.DataLocationMap;
/**
* Wrapper class for holding the output from pasting a schematic
*/
public class SchematicData
{
private final List<BlockVector> _blocks;
private final DataLocationMap _dataMap;
private final List<Entity> _entities;
private final List<BlockVector> _tileEntities;
private final World _world;
public SchematicData(DataLocationMap dataMap, World world)
{
_dataMap = dataMap;
_blocks = new ArrayList<>();
_tileEntities = new ArrayList<>();
_entities = new ArrayList<>();
_world = world;
}
/**
* @return Returns a list of blocks which has been edited by the schematic
*/
public List<BlockVector> getBlocks()
{
return new ArrayList<>(_blocks);
}
/**
* @return Returns the DataLocationMap which was utilized while pasting
*/
public DataLocationMap getDataLocationMap()
{
return _dataMap;
}
/**
* @return Returns a entities which was spawned by the schematic
*/
public List<Entity> getEntities()
{
return new ArrayList<>(_entities);
}
/**
* @return Returns a list of blocks who are tile entities which have been edited by the schematic. All the blocks in this list is also
* inside the {@link #getBlocks()} method
*/
public List<BlockVector> getTileEntities()
{
return new ArrayList<>(_tileEntities);
}
public World getWorld()
{
return _world;
}
List<BlockVector> getBlocksRaw()
{
return _blocks;
}
List<BlockVector> getTileEntitiesRaw()
{
return _tileEntities;
}
List<Entity> getEntitiesRaw()
{
return _entities;
}
}

View File

@ -1,27 +1,65 @@
package mineplex.core.common.block.schematic;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;
import com.java.sk89q.jnbt.ByteArrayTag;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.IntTag;
import com.java.sk89q.jnbt.ListTag;
import com.java.sk89q.jnbt.NBTInputStream;
import com.java.sk89q.jnbt.NBTOutputStream;
import com.java.sk89q.jnbt.NBTUtils;
import com.java.sk89q.jnbt.NamedTag;
import com.java.sk89q.jnbt.ShortTag;
import com.java.sk89q.jnbt.StringTag;
import com.java.sk89q.jnbt.Tag;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.NBTTagInt;
import net.minecraft.server.v1_8_R3.TileEntity;
import net.minecraft.server.v1_8_R3.WorldServer;
public class UtilSchematic
{
public static Schematic loadSchematic(File file) throws IOException
{
FileInputStream fis = new FileInputStream(file);
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(fis));
return loadSchematic(fis);
}
public static Schematic loadSchematic(byte[] bytes) throws IOException
{
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
return loadSchematic(bis);
}
public static Schematic loadSchematic(InputStream input) throws IOException
{
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(input));
NamedTag rootTag = nbtStream.readNamedTag();
nbtStream.close();
@ -35,9 +73,11 @@ public class UtilSchematic
short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
short height = getChildTag(schematic, "Height", ShortTag.class).getValue();
short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
byte[] blockId = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] addId = new byte[0];
short[] blocks = new short[blockId.length];
short[] blocks = new short[blockId.length]; // Have to later combine IDs
byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
Vector weOffset = null;
@ -49,11 +89,14 @@ public class UtilSchematic
weOffset = new Vector(x, y, z);
}
// We support 4096 block IDs using the same method as vanilla Minecraft, where
// the highest 4 bits are stored in a separate byte array.
if (schematic.containsKey("AddBlocks"))
{
addId = getChildTag(schematic, "AddBlocks", ByteArrayTag.class).getValue();
}
// Combine the AddBlocks data with the first 8-bit block ID
for (int index = 0; index < blockId.length; index++)
{
if ((index >> 1) >= addId.length)
@ -66,9 +109,254 @@ public class UtilSchematic
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF));
}
}
// Need to pull out tile entities
List<Tag> tileEntities = getChildTag(schematic, "TileEntities", ListTag.class).getValue();
Map<BlockVector, Map<String, Tag>> tileEntitiesMap = new HashMap<>();
for (Tag tag : tileEntities)
{
if (!(tag instanceof CompoundTag)) {
continue;
}
CompoundTag t = (CompoundTag) tag;
int x = 0;
int y = 0;
int z = 0;
Map<String, Tag> values = new HashMap<>();
for (Map.Entry<String, Tag> entry : t.getValue().entrySet())
{
if (entry.getValue() instanceof IntTag)
{
if (entry.getKey().equals("x"))
{
x = ((IntTag) entry.getValue()).getValue();
} else if (entry.getKey().equals("y"))
{
y = ((IntTag) entry.getValue()).getValue();
} else if (entry.getKey().equals("z"))
{
z = ((IntTag) entry.getValue()).getValue();
}
}
values.put(entry.getKey(), entry.getValue());
}
BlockVector vec = new BlockVector(x, y, z);
tileEntitiesMap.put(vec, values);
}
List<Tag> entityTags = getChildTag(schematic, "Entities", ListTag.class).getValue();
return new Schematic(width, height, length, blocks, blockData, weOffset);
return new Schematic(width, height, length, blocks, blockData, weOffset, tileEntitiesMap, entityTags);
}
/**
* @param schematic The schematic you want to turn into bytes
* @return Returns a byte array of the schematic which may be used for saving the schematic to DB or file
*/
public static byte[] getBytes(Schematic schematic)
{
ByteArrayOutputStream output = new ByteArrayOutputStream();
writeBytes(schematic, output);
return output.toByteArray();
}
/**
* @param schematic The scheamtic you want save somewhere
* @return Writes out this schematic on byte form
*/
public static void writeBytes(Schematic schematic, OutputStream output)
{
Map<String, Tag> map = new HashMap<>();
short width = schematic.getWidth();
short height = schematic.getHeight();
short length = schematic.getLength();
map.put("Width", new ShortTag(width));
map.put("Height", new ShortTag(height));
map.put("Length", new ShortTag(length));
if(schematic.hasWorldEditOffset())
{
Vector weOffset = schematic.getWorldEditOffset();
map.put("WEOffsetX", new IntTag(weOffset.getBlockX()));
map.put("WEOffsetY", new IntTag(weOffset.getBlockX()));
map.put("WEOffsetZ", new IntTag(weOffset.getBlockX()));
}
map.put("Materials", new StringTag("Alpha"));
short[] sBlocks = schematic.getBlocks();
Map<BlockVector, Map<String, Tag>> sTileEntities = schematic.getTileEntities();
byte[] blocks = new byte[sBlocks.length];
byte[] addBlocks = null;
byte[] blockData = schematic.getBlockData();
List<Tag> tileEntities = new ArrayList<Tag>();
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
for(int z = 0; z < length; z++)
{
int index = y * width * length + z * width + x;
BlockVector bv = new BlockVector(x, y, z);
//Save 4096 IDs in an AddBlocks section
if(sBlocks[index] > 255)
{
if (addBlocks == null) { // Lazily create section
addBlocks = new byte[(blocks.length >> 1) + 1];
}
addBlocks[index >> 1] = (byte) (((index & 1) == 0) ?
addBlocks[index >> 1] & 0xF0 | (sBlocks[index] >> 8) & 0xF
: addBlocks[index >> 1] & 0xF | ((sBlocks[index] >> 8) & 0xF) << 4);
}
blocks[index] = (byte) sBlocks[index];
if(sTileEntities.get(bv) != null)
{
Map<String, Tag> values = new HashMap<>(sTileEntities.get(bv));
values.put("x", new IntTag(x));
values.put("y", new IntTag(y));
values.put("z", new IntTag(z));
CompoundTag tileEntityTag = new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}
}
}
map.put("Blocks", new ByteArrayTag(blocks));
map.put("Data", new ByteArrayTag(blockData));
map.put("TileEntities", new ListTag(CompoundTag.class, tileEntities));
if (addBlocks != null) {
map.put("AddBlocks", new ByteArrayTag(addBlocks));
}
// ====================================================================
// Entities
// ====================================================================
List<Tag> entities = schematic.getEntities();
map.put("Entities", new ListTag(CompoundTag.class, entities));
// ====================================================================
// Output
// ====================================================================
CompoundTag schematicTag = new CompoundTag(map);
try (NBTOutputStream outputStream = new NBTOutputStream(new GZIPOutputStream(output)))
{
outputStream.writeNamedTag("Schematic", schematicTag);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static Schematic createSchematic(Location locA, Location locB)
{
return createSchematic(locA, locB, null);
}
public static Schematic createSchematic(Location locA, Location locB, Vector worldEditOffset)
{
World world = locA.getWorld();
Vector min = Vector.getMinimum(locA.toVector(), locB.toVector());
Vector max = Vector.getMaximum(locB.toVector(), locA.toVector());
short width = (short) (max.getBlockX()-min.getBlockX());
short height = (short) (max.getBlockY()-min.getBlockY());
short length = (short) (max.getBlockZ()-min.getBlockZ());
short[] blocks = new short[width*height*length];
byte[] blocksData = new byte[blocks.length];
WorldServer nmsWorld = ((CraftWorld)world).getHandle();
Map<BlockVector, Map<String, Tag>> tileEntities = new HashMap<>();
for(int x = min.getBlockX(); x < max.getBlockX(); x++)
{
for(int y = min.getBlockY(); y < max.getBlockY(); y++)
{
for(int z = min.getBlockZ(); z < max.getBlockZ(); z++)
{
int localX = x-min.getBlockX();
int localY = y-min.getBlockY();
int localZ = z-min.getBlockZ();
Block b = world.getBlockAt(x, y, z);
int index = localY * width * length + localZ * width + localX;
blocks[index] = (short) b.getTypeId();
blocksData[index] = b.getData();
BlockPosition bp = new BlockPosition(x, y, z);
TileEntity tileEntity = nmsWorld.getTileEntity(bp);
if(tileEntity == null) continue;
NBTTagCompound nmsTag = new NBTTagCompound();
tileEntity.b(nmsTag);
nmsTag.set("x", new NBTTagInt(localX));
nmsTag.set("y", new NBTTagInt(localY));
nmsTag.set("z", new NBTTagInt(localZ));
CompoundTag tag = NBTUtils.fromNative(nmsTag);
tileEntities.put(new BlockVector(localX, localY, localZ), tag.getValue());
}
}
}
List<Tag> entities = new ArrayList<>();
for(Entity e : world.getEntities())
{
if(e instanceof Player) continue;
if(e.getLocation().toVector().isInAABB(min, max))
{
net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity)e).getHandle();
NBTTagCompound nmsTag = new NBTTagCompound();
nmsEntity.c(nmsTag);
Vector diff = e.getLocation().subtract(min).toVector();
setPosition(nmsTag, diff);
nmsTag.remove("UUID");
nmsTag.remove("UUIDMost");
nmsTag.remove("UUIDLeast");
CompoundTag tag = NBTUtils.fromNative(nmsTag);
entities.add(tag);
}
}
return new Schematic(width, height, length, blocks, blocksData, worldEditOffset, tileEntities, entities);
}
@ -77,6 +365,11 @@ public class UtilSchematic
Tag tag = items.get(key);
return expected.cast(tag);
}
public static void setPosition(NBTTagCompound nbtTag, Vector pos)
{
nbtTag.set("Pos", NBTUtils.doubleArrayToList(pos.getX(), pos.getY(), pos.getZ()));
}
public static void main(String[] args) throws IOException
{

View File

@ -1,8 +1,9 @@
package mineplex.core.common.util;
import org.bukkit.ChatColor;
import mineplex.core.common.Rank;
import mineplex.core.common.currency.Currency;
import org.bukkit.ChatColor;
public class F
{
@ -27,6 +28,11 @@ public class F
return C.mGame + elem + C.mBody;
}
public static String color(String msg, String color)
{
return color + msg + C.mBody;
}
public static String ta(String message)
{
return C.cGreen + message + C.cWhite;
@ -197,7 +203,7 @@ public class F
return out;
}
public static String currency(Currency type, int amount)
{
return type.getString(amount) + ChatColor.RESET + C.mBody;
@ -223,4 +229,9 @@ public class F
return C.cClansNether + word + C.mBody;
}
public static String greenElem(String text)
{
return C.cGreen + text + ChatColor.RESET + C.mBody;
}
}

View File

@ -19,6 +19,7 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.Block;
import net.minecraft.server.v1_8_R3.BlockPosition;
@ -287,6 +288,16 @@ public class MapUtil
return true;
}
}
public static BlockPosition getBlockPos(Location loc)
{
return getBlockPos(loc.toVector());
}
public static BlockPosition getBlockPos(Vector v)
{
return getBlockPos(v.getBlockX(), v.getBlockY(), v.getBlockZ());
}
public static BlockPosition getBlockPos(int x, int y, int z)
{

View File

@ -606,10 +606,10 @@ public class UtilBlock
}
public static ArrayList<Block> getInBoundingBox(Location a, Location b, boolean ignoreAir) {
return getInBoundingBox(a, b, ignoreAir, false, true, true);
return getInBoundingBox(a, b, ignoreAir, false, false, false);
}
public static ArrayList<Block> getInBoundingBox(Location a, Location b, boolean ignoreAir, boolean hollow, boolean walls, boolean ceilfloor)
public static ArrayList<Block> getInBoundingBox(Location a, Location b, boolean ignoreAir, boolean hollow, boolean wallsOnly, boolean ceilfloorOnly)
{
ArrayList<Block> blocks = new ArrayList<Block>();
@ -626,26 +626,25 @@ public class UtilBlock
for (int y = ymin; y <= ymax; y++)
for (int z = zmin; z <= zmax; z++)
{
if(hollow)
if(hollow)
{
if(!(x == xmin || x == xmax || y == ymin || y == ymax || z == zmin || z == zmax)) continue;
}
if(!walls)
if(wallsOnly)
{
if(
(x == xmin || x == xmax) ||
(z == zmin || z == zmax)
(x != xmin && x != xmax) &&
(z != zmin && z != zmax)
)
{
continue;
}
}
if(!ceilfloor)
if(ceilfloorOnly)
{
if(y == ymin || y == ymax)
if(y != ymin && y != ymax)
{
continue;
}

View File

@ -0,0 +1,21 @@
package mineplex.core.antispam;
import mineplex.core.common.api.ApiResponse;
/**
* @author Shaun Bennett
*/
public class AntiSpamApiResponse extends ApiResponse
{
private boolean isShadowMuted;
public AntiSpamApiResponse()
{
}
public boolean isShadowMuted()
{
return isShadowMuted;
}
}

View File

@ -2,6 +2,7 @@ package mineplex.core.antispam;
import mineplex.core.MiniPlugin;
import mineplex.core.antispam.repository.AntiSpamRepository;
import mineplex.core.chat.IChatMessageFormatter;
import mineplex.core.status.ServerStatusManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -18,6 +19,8 @@ public class AntiSpamManager extends MiniPlugin
private final String _region;
private final AntiSpamRepository _repository;
private IChatMessageFormatter _messageFormatter;
public AntiSpamManager()
{
super("AntiSpam");
@ -38,6 +41,11 @@ public class AntiSpamManager extends MiniPlugin
}
}
public void setMessageFormatter(IChatMessageFormatter messageFormatter)
{
_messageFormatter = messageFormatter;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChat(AsyncPlayerChatEvent event)
{
@ -48,7 +56,19 @@ public class AntiSpamManager extends MiniPlugin
String message = event.getMessage();
ChatPayload payload = new ChatPayload(player.getName(), player.getUniqueId().toString(), _region, _serverName, message, System.currentTimeMillis());
// Run our API call async to the chat message (prevents blocking chat message)
runAsync(() -> _repository.logMessage(_pluginName, payload));
AntiSpamApiResponse response = _repository.sendMessage(_pluginName, payload);
if (response != null) // can be null if the request times out
{
if (response.isShadowMuted())
{
event.setCancelled(true);
if (_messageFormatter != null)
{
String formattedMessage = String.format(_messageFormatter.getChatFormat(player, message).getFormat(), player.getName(), message);
event.getPlayer().sendMessage(formattedMessage);
}
}
}
}
}
}

View File

@ -1,6 +1,7 @@
package mineplex.core.antispam.repository;
import com.google.gson.Gson;
import mineplex.core.antispam.AntiSpamApiResponse;
import mineplex.core.antispam.ChatPayload;
import mineplex.core.common.api.ApiEndpoint;
import mineplex.core.common.api.ApiHost;
@ -19,8 +20,8 @@ public class AntiSpamRepository extends ApiEndpoint
super(ApiHost.ANTISPAM, "/chat");
}
public ApiResponse logMessage(String source, ChatPayload payload)
public AntiSpamApiResponse sendMessage(String source, ChatPayload payload)
{
return getWebCall().post("/" + source, ApiResponse.class, payload);
return getWebCall().post("/" + source, AntiSpamApiResponse.class, payload);
}
}

View File

@ -1,11 +1,5 @@
package mineplex.core.bonuses;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import mineplex.core.MiniClientPlugin;
import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager;
@ -17,11 +11,9 @@ import mineplex.core.bonuses.commands.GuiCommand;
import mineplex.core.bonuses.commands.PowerPlayCommand;
import mineplex.core.bonuses.commands.TicketCommand;
import mineplex.core.bonuses.event.CarlSpinnerEvent;
import mineplex.core.bonuses.event.PowerPlayClubClaimEvent;
import mineplex.core.bonuses.gui.BonusGui;
import mineplex.core.bonuses.gui.SpinGui;
import mineplex.core.bonuses.gui.buttons.PowerPlayClubButton;
import mineplex.core.bonuses.powerplay.ClaimRegister;
import mineplex.core.bonuses.redis.VoteHandler;
import mineplex.core.bonuses.redis.VotifierCommand;
import mineplex.core.common.Rank;
@ -40,7 +32,7 @@ import mineplex.core.npc.Npc;
import mineplex.core.npc.NpcManager;
import mineplex.core.pet.PetManager;
import mineplex.core.poll.PollManager;
import mineplex.core.powerplayclub.PowerPlayClubManager;
import mineplex.core.powerplayclub.PowerPlayClubRepository;
import mineplex.core.recharge.Recharge;
import mineplex.core.reward.RewardManager;
import mineplex.core.stats.StatsManager;
@ -72,6 +64,12 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
public class BonusManager extends MiniClientPlugin<BonusClientData> implements ILoginProcessor
{
@ -128,13 +126,12 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
private StatsManager _statsManager;
private FacebookManager _facebookManager;
private YoutubeManager _youtubeManager;
private PowerPlayClubManager _powerPlayClubManager;
private PowerPlayClubRepository _powerPlayClubRepository;
private ThankManager _thankManager;
public boolean _enabled;
private Npc _carlNpc;
private AnimationCarl _animation;
private int _visualTick;
private ClaimRegister _claimRegister;
// Streak
// private StreakRecord _dailyStreak;
@ -157,7 +154,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
_repository = new BonusRepository(plugin, this, donationManager);
_clientManager = clientManager;
_donationManager = donationManager;
_powerPlayClubManager = donationManager.getPowerPlayClubManager();
_powerPlayClubRepository = new PowerPlayClubRepository(plugin, clientManager);
System.out.print("VOTIFIER: ");
System.out.print("DONATION MANAGER - > " + _donationManager.toString());
@ -170,8 +167,6 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
_coinQueue = new LinkedList<GiveDonorData>();
_gemQueue = new LinkedList<GiveDonorData>();
_claimRegister = new ClaimRegister();
updateOffSet();
}
@ -198,7 +193,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
_facebookManager = facebookManager;
_youtubeManager = youtubeManager;
_powerPlayClubManager = donationManager.getPowerPlayClubManager();
_powerPlayClubRepository = new PowerPlayClubRepository(plugin, _clientManager);
_voteList = new ArrayList<String>();
_voteList.add("http://vote1.mineplex.com");
@ -209,8 +204,6 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
_coinQueue = new LinkedList<GiveDonorData>();
_gemQueue = new LinkedList<GiveDonorData>();
_claimRegister = new ClaimRegister();
if (npcManager != null)
{
@ -932,7 +925,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
if (getPollManager().getNextPoll(_pollManager.Get(player), _clientManager.Get(player).GetRank()) != null) availableRewards++;
if (!_facebookManager.hasRedeemed(player)) availableRewards++;
if (_thankManager.Get(player).getThankToClaim() > 0) availableRewards++;
if (PowerPlayClubButton.isAvailable(player, _powerPlayClubManager)) availableRewards++;
if (PowerPlayClubButton.isAvailable(player, _powerPlayClubRepository)) availableRewards++;
Hologram hologram;
@ -1115,7 +1108,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
{
if (Recharge.Instance.use(player, "Carl Inform", 240000, false, false))
{
if(_pollManager.hasPoll(player) || canVote(player) || (canRank(player) && _clientManager.hasRank(player, Rank.ULTRA) && isPastAugust()) || canDaily(player) || PowerPlayClubButton.isAvailable(player, _powerPlayClubManager))
if(_pollManager.hasPoll(player) || canVote(player) || (canRank(player) && _clientManager.hasRank(player, Rank.ULTRA) && isPastAugust()) || canDaily(player) || PowerPlayClubButton.isAvailable(player, _powerPlayClubRepository))
{
if(_showCarl.containsKey(player.getName()))
{
@ -1124,40 +1117,9 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
}
}
}
if (Recharge.Instance.use(player, "Power Play Inform", 400000, false, false))
{
if (PowerPlayClubButton.isAvailable(player, _powerPlayClubManager) && PowerPlayClubButton.getMonthsLeft(player, true, _powerPlayClubManager) == 1)
{
if (_showCarl.containsKey(player.getName()))
{
if (_plugin.getConfig().getString("serverstatus.group").equalsIgnoreCase("Lobby") || _plugin.getConfig().getString("serverstatus.group").equalsIgnoreCase("Testing"))
{
UtilPlayer.message(player, F.main("Power Play Club", "This is your last month of Power Play Club! Resubscribe at" + C.cAqua + " www.mineplex.com/shop" + C.Reset + " before you lose your subscription!"));
}
}
}
}
}
}
@EventHandler
public void removeClaims(UpdateEvent event)
{
if (event.getType() != UpdateType.SEC_05)
return;
_claimRegister.removeAll();
}
@EventHandler
public void addClaims(PowerPlayClubClaimEvent event)
{
if (!event.isSuccessful())
return;
_claimRegister.registerEvent(event);
}
@EventHandler
public void processQueue(UpdateEvent event)
{
@ -1259,9 +1221,9 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
return _donationManager;
}
public PowerPlayClubManager getPowerPlayClubManager()
public PowerPlayClubRepository getPowerPlayClubRepository()
{
return _powerPlayClubManager;
return _powerPlayClubRepository;
}
public InventoryManager getInventoryManager()
@ -1269,9 +1231,4 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
return _inventoryManager;
}
public ClaimRegister getClaimRegister()
{
return _claimRegister;
}
}

View File

@ -1,25 +1,19 @@
package mineplex.core.bonuses.commands;
import java.util.UUID;
import mineplex.core.bonuses.BonusManager;
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.UtilText;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.time.LocalDate;
public class PowerPlayCommand extends CommandBase<BonusManager>
{
/**
* Examples:
* /powerplay LCastr0 5 -> Adds 5 months to player's power play club months
* /powerplay LCastr0 5 false -> same as above
* /powerplay LCastr0 5 true -> Sets the last claimed month as June
*/
private BonusManager _bonusManager;
public PowerPlayCommand(BonusManager manager)
@ -31,53 +25,21 @@ public class PowerPlayCommand extends CommandBase<BonusManager>
@Override
public void Execute(Player caller, String[] args)
{
if (args.length < 2)
if (args.length < 1)
{
UtilPlayer.message(caller, F.main("Power Play Club", "Missing Args: " + F.elem("/powerplay <player> <month(s)> [setLastClaimed:true/false]")));
UtilPlayer.message(caller, F.main("Power Play Club", "Missing Args: " + F.elem("/powerplay <player>")));
return;
}
final String targetName = args[0];
final String months = args[1];
boolean setLastClaimed = false;
if (args.length >= 3)
{
setLastClaimed = Boolean.valueOf(args[2]);
Player player = Bukkit.getPlayer(args[0]);
if (player == null) {
caller.sendMessage(ChatColor.RED + "Couldn't find player");
return;
}
Player target = UtilPlayer.searchExact(targetName);
_bonusManager.getPowerPlayClubRepository().Get(player).setSubscribed(true);
_bonusManager.getPowerPlayClubRepository().addSubscription(_bonusManager.getClientManager().Get(player).getAccountId(), LocalDate.now(), "month");
rewardPowerPlay(caller, target, target.getName(), months, setLastClaimed);
caller.sendMessage(ChatColor.GREEN + "Gave a month's subscription to " + player.getName());
}
private void rewardPowerPlay(Player caller, Player target, String targetName, String months, boolean setLastClaimed)
{
try
{
final int iMonths = Integer.parseInt(months);
UUID targetUuid = target.getUniqueId();
String messageCaller = "You gave " + F.elem(iMonths + UtilText.plural(" Month", iMonths)) + " to " + F.name(targetName) + ".";
String messageTarget = F.name(caller.getName()) + " gave you " + F.elem(iMonths + UtilText.plural(" Month", iMonths)) + ".";
if (setLastClaimed)
{
_bonusManager.getPowerPlayClubManager().setLastClaimedMonth(targetUuid, iMonths);
messageCaller = "You have set the last claimed month from " + F.name(targetName) + " to " + iMonths + ".";
messageTarget = F.name(caller.getName()) + " have set your last claimed month to " + iMonths + ".";
}
else
{
_bonusManager.getPowerPlayClubManager().addPlayerMonths(target.getUniqueId(), iMonths);
}
UtilPlayer.message(caller, F.main("Power Play Club", messageCaller));
if (target != null && !target.equals(caller))
{
UtilPlayer.message(target, F.main("Power Play Club", messageTarget));
}
}
catch (Exception e)
{
UtilPlayer.message(caller, F.main("Power Play Club", "Invalid Month Amount"));
}
}
}

View File

@ -1,48 +0,0 @@
package mineplex.core.bonuses.event;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PowerPlayClubClaimEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private long _time;
private boolean _successful;
public PowerPlayClubClaimEvent(Player player, boolean successful)
{
_player = player;
_successful = successful;
_time = System.currentTimeMillis();
}
public Player getPlayer()
{
return _player;
}
public boolean isSuccessful()
{
return _successful;
}
public long getTime()
{
return _time;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,33 +1,28 @@
package mineplex.core.bonuses.gui.buttons;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.bonuses.event.PowerPlayClubClaimEvent;
import mineplex.core.bonuses.powerplay.PowerPlayAnimation;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.gui.GuiItem;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.powerplayclub.PowerPlayClubManager;
import mineplex.core.powerplayclub.PowerPlayClubRepository;
import mineplex.core.powerplayclub.PowerPlayClubRewards;
import mineplex.core.shop.item.ShopItem;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
public class PowerPlayClubButton implements GuiItem
{
private ItemStack _item;
private Player _player;
private PowerPlayClubManager _powerPlayClubManager;
private PowerPlayClubRepository _powerPlayClubRepository;
private InventoryManager _inventoryManager;
private BonusManager _bonusManager;
@ -35,7 +30,7 @@ public class PowerPlayClubButton implements GuiItem
{
_player = player;
_bonusManager = manager;
_powerPlayClubManager = manager.getPowerPlayClubManager();
_powerPlayClubRepository = manager.getPowerPlayClubRepository();
_inventoryManager = manager.getInventoryManager();
}
@ -54,18 +49,16 @@ public class PowerPlayClubButton implements GuiItem
@Override
public void click(ClickType clickType)
{
if (isAvailable() && !_bonusManager.getClaimRegister().alreadyClaimed(_player.getUniqueId()))
if (isAvailable() && !_bonusManager.getPowerPlayClubRepository().alreadyClaimed(_player))
{
_player.closeInventory();
_player.playSound(_player.getLocation(), Sound.NOTE_PLING, 1, 1.6f);
getMonthlyRewards().giveAllItems(_player, _inventoryManager);
updateLastClaimedMonth();
Bukkit.getPluginManager().callEvent(new PowerPlayClubClaimEvent(_player, true));
PowerPlayClubRewards.giveAllItems(_player, _inventoryManager, _powerPlayClubRepository);
}
else
{
_player.playSound(_player.getLocation(), Sound.ITEM_BREAK, 1, 10);
if (getMonthsLeft(true) > 0)
if (_powerPlayClubRepository.alreadyClaimed(_player))
{
UtilPlayer.message(_player, F.main("Power Play Club", "Already claimed!"));
}
@ -73,7 +66,6 @@ public class PowerPlayClubButton implements GuiItem
{
UtilPlayer.message(_player, F.main("Power Play Club", "You have no months left! Buy more months at " + C.cAqua + "www.mineplex.com/shop" + C.Reset + "!"));
}
Bukkit.getPluginManager().callEvent(new PowerPlayClubClaimEvent(_player, false));
}
}
@ -106,16 +98,16 @@ public class PowerPlayClubButton implements GuiItem
lore.add(C.cYellow + "Rewards");
lore.add(" " + C.cWhite + "2 Game Amplifiers");
lore.add(" " + C.cWhite + "1 Omega Chest");
for (PowerPlayClubManager.PowerPlayClubItem prize : getMonthlyRewards().getItems())
for (PowerPlayClubRewards.PowerPlayClubItem prize : PowerPlayClubRewards.septemberItems())
{
lore.add(" " + C.cWhite + prize.getAmount() + " " + prize.getPrize());
}
lore.add(" ");
lore.add(C.cYellow + "Months left: " + C.cWhite + getMonthsLeft(true));
//lore.add(" ");
//lore.add(C.cYellow + "Months left: " + C.cWhite + getMonthsLeft(true)); //TODO: figure this out
if (!isAvailable())
{
lore.add(" ");
if (getMonthsLeft(true) > 0)
if (_powerPlayClubRepository.alreadyClaimed(_player))
{
lore.add(C.cRed + "Already claimed!");
}
@ -131,71 +123,12 @@ public class PowerPlayClubButton implements GuiItem
private boolean isAvailable()
{
int monthsLeft = getMonthsLeft(true);
int lastClaimed = _powerPlayClubManager.getLastClaimedMonth(_player.getUniqueId(), true);
int month = Calendar.getInstance().get(Calendar.MONTH);
int actualYear = Calendar.getInstance().get(Calendar.YEAR);
int lastClaimedYear = _powerPlayClubManager.getLastClaimedYear(_player.getUniqueId(), true);
if (monthsLeft > 0)
{
if (lastClaimed == -1)
return true;
if (lastClaimedYear < actualYear)
return true;
return lastClaimed != month;
}
return false;
return _powerPlayClubRepository.canClaim(_player);
}
private PowerPlayClubManager.PowerPlayClubRewards getMonthlyRewards()
public static boolean isAvailable(Player player, PowerPlayClubRepository repo)
{
String month = Calendar.getInstance().getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH);
return PowerPlayClubManager.PowerPlayClubRewards.valueOf(month.toUpperCase());
}
private void updateLastClaimedMonth()
{
// Send carl animation
List<ItemStack> animationItems = new ArrayList<>();
for (PowerPlayClubManager.PowerPlayClubItem prize : getMonthlyRewards().getItems())
{
animationItems.add(prize.getDisplay());
}
PowerPlayAnimation powerPlayAnimation = new PowerPlayAnimation(_player, animationItems);
_bonusManager.addPendingExplosion(_player, powerPlayAnimation);
int month = Calendar.getInstance().get(Calendar.MONTH);
int year = Calendar.getInstance().get(Calendar.YEAR);
_powerPlayClubManager.setLastClaimedMonth(_player.getUniqueId(), month);
_powerPlayClubManager.decreasePlayerMonth(_player.getUniqueId());
_powerPlayClubManager.setLastClaimedYear(_player.getUniqueId(), year);
}
private int getMonthsLeft(boolean update)
{
return _powerPlayClubManager.getPlayerMonths(_player.getUniqueId(), update);
}
public static int getMonthsLeft(Player player, boolean update, PowerPlayClubManager manager)
{
return manager.getPlayerMonths(player.getUniqueId(), update);
}
public static boolean isAvailable(Player player, PowerPlayClubManager manager)
{
int monthsLeft = getMonthsLeft(player, true, manager);
int lastClaimed = manager.getLastClaimedMonth(player.getUniqueId(), true);
int month = Calendar.getInstance().get(Calendar.MONTH);
int actualYear = Calendar.getInstance().get(Calendar.YEAR);
int lastClaimedYear = manager.getLastClaimedYear(player.getUniqueId(), true);
if (monthsLeft > 0)
{
if (lastClaimed == -1)
return true;
if (lastClaimedYear < actualYear)
return true;
return lastClaimed != month;
}
return false;
return repo.canClaim(player);
}
}

View File

@ -1,46 +0,0 @@
package mineplex.core.bonuses.powerplay;
import java.util.*;
import mineplex.core.bonuses.event.PowerPlayClubClaimEvent;
public class ClaimRegister
{
/**
* Fixes the problem where the database isn't sync'd with the server so the player can still claim it if they try
* to click really quickly after it was already claimed.
* This stores the player information for 5 seconds, so if they try to claim again they won't be able to.
*/
private Map<UUID, PowerPlayClubClaimEvent> _events = new HashMap<>();
public void registerEvent(PowerPlayClubClaimEvent event)
{
_events.put(event.getPlayer().getUniqueId(), event);
}
public void removeAll()
{
List<UUID> toRemove = new ArrayList<>();
long currentTime = System.currentTimeMillis();
for (Map.Entry<UUID, PowerPlayClubClaimEvent> eventEntry : _events.entrySet())
{
PowerPlayClubClaimEvent event = eventEntry.getValue();
if (currentTime - event.getTime() >= 5000)
{
toRemove.add(eventEntry.getKey());
}
}
for (UUID uuid : toRemove)
{
_events.remove(uuid);
}
}
public boolean alreadyClaimed(UUID uuid)
{
return _events.containsKey(uuid);
}
}

View File

@ -122,7 +122,7 @@ public class Fountain implements GoalCounterListener
}
_hologram.setText(text.toArray(new String[text.size()]));
_schematicLoader.update(fillPercent);
//_schematicLoader.update(fillPercent);
}
else
{

View File

@ -6,13 +6,13 @@ import mineplex.core.brawl.fountain.command.FountainCommand;
import mineplex.core.common.util.C;
import mineplex.core.donation.DonationManager;
import mineplex.core.hologram.HologramManager;
import mineplex.core.locations.LocationConstants;
import mineplex.core.stats.StatsManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.Region;
import mineplex.serverdata.servers.ConnectionData;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
@ -48,7 +48,7 @@ public class FountainManager extends MiniPlugin
int goal = 70000000;//!new File("eu.dat").exists() ? 200000000 : 20000000;
_gemFountain = new Fountain(new ConnectionData("10.3.203.80", 6379, ConnectionData.ConnectionType.MASTER, "USRedis"),
new ConnectionData("10.3.203.80", 6377, ConnectionData.ConnectionType.SLAVE, "USRedis"), Region.ALL,
new Location(world, -25.5, 73, 19.5), new Location(world, -35.5, 69, 1.5),
LocationConstants.FOUNTAIN_LOCATION, LocationConstants.FOUNTAIN_SCHEMATIC,
C.cGreen + "Gem Fountain", "GemFountain_01", goal, this, clientManager, donationManager, _hologramManager, _statsManager);
}

View File

@ -3,6 +3,7 @@ package mineplex.core.chat;
import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.antispam.AntiSpamManager;
import mineplex.core.chat.command.BroadcastCommand;
import mineplex.core.chat.command.ChatSlowCommand;
import mineplex.core.chat.command.SilenceCommand;

View File

@ -0,0 +1,39 @@
package mineplex.core.chat;
/**
* The format for a chat message being sent by a player
*
* @author Shaun Bennett
*/
public class ChatFormat
{
private String _format;
private boolean _json;
public ChatFormat(String format, boolean json)
{
_format = format;
_json = json;
}
/**
* Get the string representing the chat format. This will be represented as a JSON string if {@link #isJson()},
* or should be in the standard Spigot chat format otherwise.
*
* @return A string representing how to format the chat message
*/
public String getFormat()
{
return _format;
}
/**
* Is this chat format a JSON string (should be sent to player as a json message)
*
* @return boolean representing if this chat format is in the json format
*/
public boolean isJson()
{
return _json;
}
}

View File

@ -0,0 +1,21 @@
package mineplex.core.chat;
import org.bukkit.entity.Player;
/**
* This is an interface that provides a method to format chat message.
* Needed for AntiSpam's shadow mute feature.
*
* @author Shaun Bennett
*/
public interface IChatMessageFormatter
{
/**
* Returns the proper format for the chat message to be sent
*
* @param player Player sending the message
* @param message The message the player is trying to send
* @return the format of the chat message,
*/
public ChatFormat getChatFormat(Player player, String message);
}

View File

@ -1,9 +1,5 @@
package mineplex.core.donation;
import java.util.LinkedList;
import java.util.Queue;
import java.util.UUID;
import com.google.gson.Gson;
import mineplex.cache.player.PlayerCache;
import mineplex.core.MiniClientPlugin;
@ -16,7 +12,6 @@ import mineplex.core.donation.command.GemCommand;
import mineplex.core.donation.command.ShardCommand;
import mineplex.core.donation.repository.DonationRepository;
import mineplex.core.donation.repository.token.DonorTokenWrapper;
import mineplex.core.powerplayclub.PowerPlayClubManager;
import mineplex.core.server.util.TransactionResponse;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
@ -25,6 +20,10 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.LinkedList;
import java.util.Queue;
import java.util.UUID;
public class DonationManager extends MiniClientPlugin<Donor>
{
private final int MAX_GIVE_ATTEMPTS = 10;
@ -36,7 +35,6 @@ public class DonationManager extends MiniClientPlugin<Donor>
private Queue<GiveDonorData> _coinAttemptQueue;
private PowerPlayClubManager _powerPlayClubManager;
private final CoreClientManager _clientManager;
public DonationManager(JavaPlugin plugin, CoreClientManager clientManager, String webAddress)
@ -47,7 +45,6 @@ public class DonationManager extends MiniClientPlugin<Donor>
_coinAttemptQueue = new LinkedList<>();
_powerPlayClubManager = new PowerPlayClubManager();
_clientManager = clientManager;
}
@ -381,9 +378,4 @@ public class DonationManager extends MiniClientPlugin<Donor>
{
return new Donor();
}
public PowerPlayClubManager getPowerPlayClubManager()
{
return _powerPlayClubManager;
}
}

View File

@ -61,6 +61,7 @@ public enum GameDisplay
ZombieSurvival("Zombie Survival", Material.SKULL_ITEM, (byte)2, GameCategory.SURVIVAL, 49),
Build("Master Builders", Material.WOOD, (byte)0, GameCategory.CLASSICS, 50),
BuildMavericks("Mavericks Master Builders", Material.WOOD, (byte)3, GameCategory.CLASSICS, 63),
Cards("Craft Against Humanity", Material.MAP, (byte)0, GameCategory.CLASSICS, 51),
Skywars("Skywars", Material.FEATHER, (byte) 0, GameCategory.SURVIVAL, 52),
SkywarsTeams("Skywars Teams", "Skywars", Material.FEATHER, (byte)0, GameCategory.TEAM_VARIANT, 53),
@ -80,6 +81,8 @@ public enum GameDisplay
SpeedBuilders("Speed Builders", Material.QUARTZ_BLOCK, (byte) 0, GameCategory.CLASSICS, 60),
Valentines("Valentines Vendetta", Material.LEATHER, (byte)0, GameCategory.EXTRA, 61),
Basketball("Hoops", Material.SLIME_BALL, (byte)0, GameCategory.EXTRA, 63),
Event("Mineplex Event", Material.CAKE, (byte)0, GameCategory.EVENT, 999),

View File

@ -0,0 +1,58 @@
package mineplex.core.locations;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
/**
* This class controls all "hard coded" locations that will be the same throughout the entire server
* regardless of whether or not it is on hub
*/
public class LocationConstants
{
private static final int CHEST_X = 31;
private static final int CHEST_Z = 23;
/**
* The number to be added to either the X or the Z for chest reset locations
*/
private static final int CHEST_ADD = 5;
public static final World WORLD = Bukkit.getWorld("world");
public static final Location HUB_SPAWN = new Location(WORLD, 0, 77, -32);
public static final Location[] CHEST_LOCATIONS = {
new Location(WORLD, 34, 72, -15),
new Location(WORLD, 23, 72, -31),
new Location(WORLD, -23, 72, -31),
new Location(WORLD, -34, 72, -15)
};
//new Location(world, -25.5, 73, 19.5), new Location(world, -35.5, 69, 1.5)
public static final Location FOUNTAIN_SCHEMATIC = new Location(WORLD, -35.5, 68, 1.5);
public static final Location FOUNTAIN_LOCATION = new Location(WORLD, -24.5, 72, 24.5);
public static Location getResetLocation(Location chestLocation)
{
int x = chestLocation.getBlockX();
int z = chestLocation.getBlockZ();
int absX = Math.abs(x);
int absZ = Math.abs(z);
if (absX == CHEST_X)
{
return chestLocation.clone().add(CHEST_ADD, 0, 0);
}
if (absZ == CHEST_Z)
{
return chestLocation.clone().add(0, 0, CHEST_ADD);
}
return chestLocation.clone().add(CHEST_ADD, 0, CHEST_ADD);
}
}

View File

@ -0,0 +1,188 @@
package mineplex.core.mavericks;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.util.Vector;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.block.schematic.SchematicData;
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.UtilParticle;
import mineplex.core.common.util.UtilParticle.ParticleType;
import mineplex.core.common.util.UtilParticle.ViewDist;
import mineplex.core.hologram.Hologram;
import mineplex.core.hologram.HologramManager;
/**
* Represents a display slot to display Mavericks Master Builders builds.
*/
public class DisplaySlot
{
private MavericksApprovedWrapper _data;
private Location _loc;
private ArrayList<Entity> _pastedEntities = new ArrayList<>();
private Map<Vector, ParticleType> _particles = null;
private List<Hologram> _holograms = new ArrayList<>();
/**
* @param loc The minimum corner of where the build will be pasted in.
*/
public DisplaySlot(Location loc, HologramManager hologramManager)
{
_loc = loc.clone();
for(int i = 0; i < 4; i++)
{
_holograms.add(new Hologram(hologramManager, _loc.clone(), "Built by ???", "Theme: ???"));
}
}
public MavericksApprovedWrapper getData()
{
return _data;
}
public void setData(MavericksApprovedWrapper data)
{
clearEntities();
for(Hologram h : _holograms)
h.stop();
Schematic schematic = data.getBuild().getSchematic();
Location a = _loc;
Location b = _loc.clone().add(schematic.getWidth(), schematic.getHeight(), schematic.getLength());
UtilBlock.startQuickRecording();
for(int x = a.getBlockX(); x < b.getX(); x++)
{
// Ignore the floor to keep the outer ring
for(int y = a.getBlockY() + 1; y < b.getY(); y++)
{
for(int z = a.getBlockZ(); z < b.getZ(); z++)
{
UtilBlock.setQuick(a.getWorld(), x, y, z, 0, (byte) 0);
}
}
}
SchematicData pasteData = schematic.paste(_loc, true, false);
for(Entity e : pasteData.getEntities())
{
if(e instanceof Item)
{
//Don't despawn
e.setTicksLived(32768);
//Prevent Pickup
((Item)e).setPickupDelay(32767);
}
else
{
UtilEnt.Vegetate(e, true);
UtilEnt.ghost(e, true, false);
}
_pastedEntities.add(e);
}
_particles = data.getBuild().getParticles();
boolean wasNull = _data == null;
_data = data;
//Only need to set locations first time after we get the data
if(wasNull)
{
setHologramLocations();
}
for(Hologram h : _holograms)
{
h.setText(
C.cGray + "Built by " + C.cYellow + C.Bold + _data.getBuild().getName(),
C.cGray + "Theme: " + C.cYellow + C.Bold + data.getBuild().getTheme());
h.start();
}
}
/**
* Send all the entities to nearby players. Should be called every 10 ticks.
*/
public void updateParticles()
{
if(_particles == null) return;
for(Entry<Vector, ParticleType> e : _particles.entrySet())
{
Location loc = _loc.clone().add(e.getKey());
ParticleType type = e.getValue();
int amount = 8;
if (type == ParticleType.HUGE_EXPLOSION ||
type == ParticleType.LARGE_EXPLODE ||
type == ParticleType.NOTE)
amount = 1;
UtilParticle.PlayParticleToAll(type, loc, 0.4f, 0.4f, 0.4f, 0, amount, ViewDist.LONG);
}
}
private void clearEntities()
{
for(Entity e : _pastedEntities)
{
e.remove();
}
_pastedEntities.clear();
}
/**
* @param e The entity you want to check.
* @return Returns true if this entity is spawned in by this display slot.
*/
public boolean isDisplaySlotEntity(Entity e)
{
return _pastedEntities.contains(e);
}
public boolean isInside(Location loc)
{
if(!_loc.getWorld().equals(loc.getWorld())) return false;
if(_data == null) return false;
Schematic s = _data.getBuild().getSchematic();
Location min = _loc.clone();
Location max = _loc.clone().add(s.getWidth(), s.getHeight(), s.getLength());
return UtilAlg.inBoundingBox(loc, min, max);
}
public void setHologramLocations()
{
if(_data == null) return;
Schematic s = _data.getBuild().getSchematic();
Location min = _loc.clone();
double height = 4;
_holograms.get(0).setLocation(min.clone().add(s.getWidth()/2.0, height, -1.5));
_holograms.get(1).setLocation(min.clone().add(s.getWidth()/2.0, height, s.getLength() + 1.5));
_holograms.get(2).setLocation(min.clone().add(-1.5, height, s.getLength()/2.0));
_holograms.get(3).setLocation(min.clone().add(s.getWidth() + 1.5, height, s.getLength()/2.0));
}
}

View File

@ -0,0 +1,176 @@
package mineplex.core.mavericks;
import java.sql.Connection;
import java.sql.PreparedStatement;
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 java.util.concurrent.CompletableFuture;
import mineplex.serverdata.database.DBPool;
/**
* Repository for Mavericks-MasterBuilders SQL game data
* -
* Table to back this repository may be created with:
*
*
CREATE TABLE mavericksMasterBuildersApproved (
buildId INT NOT NULL AUTO_INCREMENT,
ApproveDate INT NOT NULL,
ApprovedBy VARCHAR(36) NOT NULL DEFAULT '',
Display TINYINT(1) NOT NULL DEFAULT '1',
PRIMARY KEY (buildId),
CONSTRAINT account_id FOREIGN KEY (ApprovedBy) REFERENCES accounts (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT build_id FOREIGN KEY (BuildId) REFERENCES mavericksMasterBuildersBuilds (BuildId) ON DELETE NO ACTION ON UPDATE NO ACTION
)
*/
public class MavericksApprovedRepository
{
private static final String TABLE_APPROVED = "mavericksMasterBuildersApproved";
private static final String TABLE_BUILD = "mavericksMasterBuildersBuilds";
public CompletableFuture<Boolean> add(MavericksBuildWrapper data, UUID approvedBy)
{
return add(data, approvedBy, true);
}
public CompletableFuture<Boolean> add(MavericksBuildWrapper data, UUID approvedBy, boolean display)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
PreparedStatement stmt = conn.prepareStatement("REPLACE INTO " + TABLE_APPROVED + " (BuildId, ApprovedBy, Display) SELECT ?, accounts.id, ? FROM accounts WHERE uuid=?");
stmt.setLong(1, data.getBuildId());
stmt.setBoolean(2, display);
stmt.setString(3, approvedBy.toString());
return stmt.executeUpdate() > 0;
}
catch(SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public CompletableFuture<List<MavericksApprovedWrapper>> getToDisplay(boolean onlyDisplay, int limit, int offset)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
String filter = onlyDisplay ? " WHERE Display=1 " : " ";
PreparedStatement stmt = conn.prepareStatement(
"SELECT " +
TABLE_APPROVED + ".BuildId, ApprovedDate," +
"(SELECT uuid FROM accounts WHERE accounts.id=ApprovedBy)," +
"Display, FirstDisplayed," +
"BuildTheme," +
"(SELECT uuid FROM accounts WHERE accounts.id=accountId)," +
"(SELECT name FROM accounts WHERE accounts.id=accountId)," +
"Points, Place, Date, Schematic, Particles, Reviewed " +
"FROM " + TABLE_APPROVED + " " +
"INNER JOIN " + TABLE_BUILD + " " +
"ON " + TABLE_APPROVED + ".BuildId = " + TABLE_BUILD + ".BuildId" +
filter +
"LIMIT " + limit + " OFFSET " + offset);
ResultSet set = stmt.executeQuery();
List<MavericksApprovedWrapper> list = new ArrayList<>();
while (set.next())
{
long buildId = set.getLong(1);
long approvedDate = set.getLong(2);
UUID approvedBy = UUID.fromString(set.getString(3));
boolean display = set.getBoolean(4);
Timestamp stamp = set.getTimestamp(1);
Long firstDisplayed = null;
if(!set.wasNull() && stamp != null) stamp.getTime();
String theme = set.getString(6);
UUID uuid = UUID.fromString(set.getString(7));
String lastName = set.getString(8);
int votes = set.getInt(9);
int place = set.getInt(10);
long dateStamp = set.getLong(11);
byte[] schematic = set.getBytes(12);
byte[] particles = set.getBytes(13);
boolean reviewed = set.getBoolean(14);
MavericksBuildWrapper build = new MavericksBuildWrapper(buildId, uuid, lastName, theme, votes, place, dateStamp, schematic, particles, reviewed);
MavericksApprovedWrapper approved = new MavericksApprovedWrapper(build, approvedDate, approvedBy, display, firstDisplayed);
list.add(approved);
}
return list;
}
catch (SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public CompletableFuture<Boolean> setDisplay(boolean display, long... buildids)
{
if(buildids.length == 0) return null;
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
String where = "WHERE BuildId=?";
for(int i = 1; i < buildids.length; i++)
{
where += " OR BuildId=?";
}
PreparedStatement stmt = conn.prepareStatement("UPDATE " + TABLE_APPROVED + " SET Display=? " + where);
stmt.setBoolean(1, display);
for(int i = 0; i < buildids.length; i++)
{
stmt.setLong(2+i, buildids[i]);
}
return stmt.executeUpdate() > 0;
}
catch(SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public CompletableFuture<Boolean> setDisplayDate(long buildid)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
PreparedStatement stmt = conn.prepareStatement("UPDATE " + TABLE_APPROVED + " SET FirstDisplayed=? WHERE BuildId=?");
// stmt.setDate(1, new Date(System.currentTimeMillis()));
stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
stmt.setLong(2, buildid);
return stmt.executeUpdate() > 0;
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
}

View File

@ -0,0 +1,57 @@
package mineplex.core.mavericks;
import java.util.UUID;
/**
* A wrapper class to SQL data in the mavericksMasterBuildersApproved SQL table
*/
public class MavericksApprovedWrapper
{
private final MavericksBuildWrapper _build;
private final long _approvedDate;
private final UUID _approvedBy;
private final boolean _display;
private Long _firstDisplayed;
public MavericksApprovedWrapper(MavericksBuildWrapper build, long approvedDate, UUID approvedBy, boolean display, Long firstDisplayed)
{
_build = build;
_approvedDate = approvedDate;
_approvedBy = approvedBy;
_display = display;
_firstDisplayed = firstDisplayed;
}
public MavericksBuildWrapper getBuild()
{
return _build;
}
public long getApprovedDate()
{
return _approvedDate;
}
public UUID getApprovedBy()
{
return _approvedBy;
}
public Long getFirstDisplayed()
{
return _firstDisplayed;
}
public void setFirstDisplayed(Long firstDisplayed)
{
_firstDisplayed = firstDisplayed;
}
public boolean isDisplay()
{
return _display;
}
}

View File

@ -0,0 +1,133 @@
package mineplex.core.mavericks;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import mineplex.serverdata.database.DBPool;
/**
* Repository for Mavericks-MasterBuilders SQL game data
* -
* Table to back this repository may be created with
*
CREATE TABLE IF NOT EXISTS mavericksMasterBuildersBuilds (
accountId INT NOT NULL,
BuildTheme VARCHAR(255) NOT NULL,
Points DOUBLE NOT NULL,
Place INT NOT NULL,
Date BIGINT NOT NULL,
Schematic BLOB,
Reviewed TINYINT,
PRIMARY KEY (accountId,Date),
FOREIGN KEY (accountId) REFERENCES accounts(id) ON DELETE NO ACTION ON UPDATE NO ACTION
);
*/
public class MavericksBuildRepository
{
private static final String TABLE = "mavericksMasterBuildersBuilds";
public CompletableFuture<List<MavericksBuildWrapper>> getToReview(boolean onlyUnreviewed, int limit, int offset)
{
return getToReview(onlyUnreviewed, limit, offset, true);
}
public CompletableFuture<List<MavericksBuildWrapper>> getToReview(boolean onlyUnreviewed, int limit, int offset, boolean parseData)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
String filter = onlyUnreviewed ? "WHERE Reviewed=0 " : "";
PreparedStatement stmt = conn.prepareStatement("SELECT BuildId," +
"(SELECT uuid from accounts WHERE accounts.id=" + TABLE + ".accountId)," +
"(SELECT name from accounts WHERE accounts.id=" + TABLE + ".accountId)," +
"BuildTheme,Points,Place,Date,Schematic,Particles,Reviewed FROM " + TABLE + " " + filter +
" ORDER BY Points DESC LIMIT " + limit + " OFFSET " + offset);
ResultSet set = stmt.executeQuery();
List<MavericksBuildWrapper> list = new ArrayList<>();
while (set.next())
{
long buildId = set.getLong(1);
UUID uuid = UUID.fromString(set.getString(2));
String lastName = set.getString(3);
String theme = set.getString(4);
int votes = set.getInt(5);
int place = set.getInt(6);
long dateStamp = set.getLong(7);
byte[] schematic = set.getBytes(8);
byte[] particles = set.getBytes(9);
boolean reviewed = set.getBoolean(10);
MavericksBuildWrapper data = new MavericksBuildWrapper(buildId, uuid, lastName, theme, votes, place, dateStamp, schematic, particles, reviewed);
if(parseData)
{
data.getParticles();
data.getSchematic();
}
list.add(data);
}
return list;
}
catch (SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public CompletableFuture<Boolean> setReviewed(long buildId, boolean reviewed)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
PreparedStatement stmt = conn.prepareStatement("UPDATE " + TABLE + " SET Reviewed=? WHERE BuildId=?");
stmt.setBoolean(1, reviewed);
stmt.setLong(2, buildId);
return stmt.executeUpdate() > 0;
}
catch(SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public CompletableFuture<Boolean> add(MavericksBuildWrapper data)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection conn = DBPool.getAccount().getConnection())
{
PreparedStatement stmt = conn.prepareStatement("REPLACE INTO " + TABLE + " (accountId, BuildTheme, Points, Place, Date, Schematic, Particles) SELECT accounts.id, ?, ?, ?, ?, ?, ? FROM accounts WHERE uuid=?");
stmt.setString(1, data.getTheme());
stmt.setDouble(2, data.getPoints());
stmt.setInt(3, data.getPlace());
stmt.setLong(4, data.getDateStamp());
stmt.setBytes(5, data.getSchematicBytes());
stmt.setBytes(6, data.getParticlesRaw());
stmt.setString(7, data.getUUID().toString());
return stmt.executeUpdate() > 0;
}
catch(SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
}

View File

@ -0,0 +1,176 @@
package mineplex.core.mavericks;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.util.Vector;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.NBTUtils;
import com.java.sk89q.jnbt.Tag;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.block.schematic.UtilSchematic;
import mineplex.core.common.util.UtilParticle.ParticleType;
/**
* A simple wrapper class for Mavericks-MasterBuilders SQL data
*/
public class MavericksBuildWrapper
{
private final long _buildId;
private final UUID _uuid;
private final String _theme;
private final double _points;
private final int _place;
private final long _dateStamp;
private final byte[] _schematic;
private Schematic _schematicCache;
private final byte[] _particles;
private Map<Vector, ParticleType> _particlesCache;
private boolean _reviewed;
private final String _name;
public MavericksBuildWrapper(long buildId, UUID uuid, String name, String theme, double points, int place, long dateStamp,
byte[] schematic, byte[] particles, boolean reviewed)
{
this._buildId = buildId;
this._uuid = uuid;
this._name = name;
this._theme = theme;
this._points = points;
this._place = place;
this._dateStamp = dateStamp;
this._schematic = schematic;
this._particles = particles;
this._reviewed = reviewed;
}
public MavericksBuildWrapper(long buildId, UUID uuid, String theme, double points, int place, long dateStamp,
byte[] schematic, byte[] particles, boolean reviewed)
{
this(buildId, uuid, null, theme, points, place, dateStamp, schematic, particles, reviewed);
}
public long getBuildId()
{
return _buildId;
}
public UUID getUUID()
{
return _uuid;
}
public String getName()
{
return _name;
}
public boolean hasNameSet()
{
return _name != null;
}
public String getTheme()
{
return _theme;
}
public double getPoints()
{
return _points;
}
public int getPlace()
{
return _place;
}
public long getDateStamp()
{
return _dateStamp;
}
public byte[] getSchematicBytes()
{
return _schematic;
}
public boolean isReviewed()
{
return _reviewed;
}
public void setReviewed(boolean reviewed)
{
_reviewed = reviewed;
}
public Schematic getSchematic()
{
if(_schematicCache != null) return _schematicCache;
try
{
return _schematicCache = UtilSchematic.loadSchematic(_schematic);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public boolean hasParticles()
{
return _particles != null && _particles.length > 0;
}
public byte[] getParticlesRaw()
{
return _particles;
}
public Map<Vector, ParticleType> getParticles()
{
if(_particlesCache != null) return _particlesCache;
Map<Vector, ParticleType> map = new HashMap<>();
if(!hasParticles()) return map;
try
{
CompoundTag tag = (CompoundTag) NBTUtils.getFromBytesCompressed(_particles).getTag();
for(Entry<String, Tag> e : tag.getValue().entrySet())
{
CompoundTag parent = (CompoundTag) e.getValue();
Vector v = NBTUtils.getVector(parent);
ParticleType particle = ParticleType.valueOf(parent.getString("particle"));
while(map.containsKey(v)) v.add(new Vector(0.00000001, 0, 0));
map.put(v, particle);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return _particlesCache = map;
}
@Override
public String toString()
{
return "MavericksBuildWrapper[uuid='" + _uuid + "',theme='" + _theme + "',points=" + _points + ",place=" + _place
+ ",date=" + _dateStamp + ",Schematic=ByteArray[" + _schematic.length + "]]";
}
}

View File

@ -27,7 +27,25 @@ public class Npc
_npcManager = npcManager;
_databaseRecord = databaseRecord;
_location = new Location(Bukkit.getWorld(getDatabaseRecord().getWorld()), getDatabaseRecord().getX(), getDatabaseRecord().getY(), getDatabaseRecord().getZ());
Double yaw = getDatabaseRecord().getYaw();
Double pitch = getDatabaseRecord().getPitch();
if(yaw == null)
{
yaw = 0d;
}
if(pitch == null)
{
pitch = 0d;
}
_location = new Location(Bukkit.getWorld(getDatabaseRecord().getWorld()),
getDatabaseRecord().getX(),
getDatabaseRecord().getY(),
getDatabaseRecord().getZ(),
yaw.floatValue(),
pitch.floatValue());
if (getDatabaseRecord().getInfo() == null)
_info = null;

View File

@ -264,6 +264,8 @@ public class NpcManager extends MiniPlugin
npcsRecord.setX(player.getLocation().getX());
npcsRecord.setY(player.getLocation().getY());
npcsRecord.setZ(player.getLocation().getZ());
npcsRecord.setYaw((double)player.getEyeLocation().getYaw());
npcsRecord.setPitch((double)player.getEyeLocation().getPitch());
npcsRecord.setRadius(radius);
npcsRecord.setEntityType(entityType.name());
npcsRecord.setAdult(adult);
@ -422,8 +424,6 @@ public class NpcManager extends MiniPlugin
if (npc.getFailedAttempts() >= 10 || npc.getDatabaseRecord().getRadius() == 0)
{
Location location = npc.getLocation();
location.setPitch(entity.getLocation().getPitch());
location.setYaw(entity.getLocation().getYaw());
entity.teleport(location);
entity.setVelocity(new Vector(0, 0, 0));
npc.setFailedAttempts(0);
@ -461,8 +461,6 @@ public class NpcManager extends MiniPlugin
if (!entity.isDead() && entity.isValid())
{
Location location = npc.getLocation();
location.setPitch(entity.getLocation().getPitch());
location.setYaw(entity.getLocation().getYaw());
entity.teleport(location);
entity.setVelocity(new Vector(0, 0, 0));

View File

@ -244,7 +244,7 @@ public class PartyRedisManager
{
player1.leaveVehicle();
player1.eject();
_plugin.getPortal().sendPlayerToServer(player1, server, true);
_plugin.getPortal().sendPlayer(player1, server);
});
_plugin.removeParty(party);
}

View File

@ -37,7 +37,7 @@ public class PartyInvitesMenu extends PartyMenu
private final int INV_SIZE = 54;
private final int SLOTS_PER_PAGE = 27;
private final int STARTING_SLOT = 18;
private final int STARTING_SLOT = 19;
private final int BACK_BUTTON_SLOT = 0;
private final int DENY_ALL_BUTTON_SLOW = 4;
private final int FILTER_BUTTON_SLOT = 8;

View File

@ -9,7 +9,6 @@ import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTabTitle;
import mineplex.core.party.Lang;
import mineplex.core.party.Party;
import mineplex.core.party.event.PartySendToServerEvent;
import mineplex.core.portal.Commands.SendCommand;
@ -104,7 +103,6 @@ public class Portal extends MiniPlugin
Party party = event.getParty();
if(!party.getOwner().equalsIgnoreCase(player.getName()))
{
Lang.NOT_OWNER_SERVER.send(player);
return;
}
sendParty(party);
@ -215,7 +213,7 @@ public class Portal extends MiniPlugin
sendPlayerToServer(player, "Lobby");
}
private void sendPlayer(final Player player, String serverName)
public void sendPlayer(final Player player, String serverName)
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);

View File

@ -0,0 +1,26 @@
package mineplex.core.powerplayclub;
public class PPCPlayerData {
private boolean _subscribed;
private boolean _claimed;
public void setSubscribed(boolean subscribed)
{
_subscribed = subscribed;
}
public void setClaimed(boolean claimed)
{
_claimed = claimed;
}
public boolean hasClaimed()
{
return _claimed;
}
public boolean hasSubscribed()
{
return _subscribed;
}
}

View File

@ -1,301 +0,0 @@
package mineplex.core.powerplayclub;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import mineplex.core.common.util.*;
import mineplex.core.database.PlayerKeyValueRepository;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.inventory.data.Item;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
public class PowerPlayClubManager implements Listener
{
/**
* Manager for the Power Play Club system
* Sends and receives information from/to the database
*/
private PlayerKeyValueRepository<Integer> _repository;
private Map<UUID, PlayerMonths> _playerMonths = new HashMap<>();
public PowerPlayClubManager()
{
Bukkit.getPluginManager().registerEvents(this, UtilServer.getPlugin());
_repository = new PlayerKeyValueRepository<>("powerPlayClub", PreparedStatement::setInt, ResultSet::getInt);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
updatePlayer(event.getPlayer().getUniqueId());
}
public int getLastClaimedMonth(UUID uuid, boolean update)
{
if (update)
{
updatePlayer(uuid);
}
if (_playerMonths.containsKey(uuid))
{
return _playerMonths.get(uuid).getLastClaimed();
}
return -1;
}
public void setLastClaimedMonth(UUID uuid, int month)
{
_repository.put(uuid, "lastClaimed", month);
updatePlayer(uuid);
PlayerMonths playerMonths = _playerMonths.get(uuid);
playerMonths.setLastClaimed(month);
_playerMonths.put(uuid, playerMonths);
}
public int getLastClaimedYear(UUID uuid, boolean update)
{
if (update)
{
updatePlayer(uuid);
}
if (_playerMonths.containsKey(uuid))
{
return _playerMonths.get(uuid).getYear();
}
return Calendar.getInstance().get(Calendar.YEAR);
}
public void setLastClaimedYear(UUID uuid, int year)
{
_repository.put(uuid, "year", year);
updatePlayer(uuid);
PlayerMonths playerMonths = _playerMonths.get(uuid);
playerMonths.setYear(year);
_playerMonths.put(uuid, playerMonths);
}
public int getPlayerMonths(UUID uuid, boolean update)
{
if (update)
{
updatePlayer(uuid);
}
if (_playerMonths.containsKey(uuid))
{
return _playerMonths.get(uuid).getMonths();
}
return 0;
}
public void addPlayerMonths(UUID uuid, int months)
{
int currentMonths = getPlayerMonths(uuid, true);
_repository.put(uuid, "monthsLeft", currentMonths + months);
updatePlayer(uuid);
PlayerMonths playerMonths = _playerMonths.get(uuid);
playerMonths.setMonths(currentMonths + months);
_playerMonths.put(uuid, playerMonths);
}
public void decreasePlayerMonth(UUID uuid)
{
addPlayerMonths(uuid, -1);
}
/**
* Updates player's months and last claimed month
* @param uuid the player's UUID
*/
private void updatePlayer(UUID uuid)
{
_repository.getAll(uuid).thenCompose(BukkitFuture.accept(values ->
{
int year = Calendar.getInstance().get(Calendar.YEAR);
int lastClaimed = -1;
int months = 0;
if (values.containsKey("claimedYear"))
{
year = values.get("claimedYear");
}
if (values.containsKey("lastClaimed"))
{
lastClaimed = values.get("lastClaimed");
}
if (values.containsKey("monthsLeft"))
{
months = values.get("monthsLeft");
}
PlayerMonths playerMonths = new PlayerMonths(months, lastClaimed, year);
_playerMonths.put(uuid, playerMonths);
}));
}
/**
* Monthly rewards, based on each month, a different reward
*/
public enum PowerPlayClubRewards
{
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY(new PowerPlayClubItem("Squid Morph", 1, new ItemStack(Material.INK_SACK))),
AUGUST(new PowerPlayClubItem("Squid Morph", 1, new ItemStack(Material.INK_SACK))),
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER;
private PowerPlayClubItem[] _items;
PowerPlayClubRewards(PowerPlayClubItem... items)
{
_items = items;
}
public PowerPlayClubItem[] getItems()
{
return _items;
}
/**
* Gives the player the specific items for that month, plus
* 2x Game Boosters
* 1x Omega Chest
* @param player
* @param manager
*/
public void giveAllItems(Player player, InventoryManager manager)
{
for (PowerPlayClubItem item : _items)
{
Item fItem = manager.getItem(item.getPrize());
if (fItem == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, fItem.Name, 1);
UtilPlayer.message(player, F.main("Power Play Club", "You received " + item.getAmount() + "x " + F.elem(item.getPrize()) + "."));
}
}
Item gameAmplifier = manager.getItem("Game Booster");
if (gameAmplifier == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, gameAmplifier.Name, 2);
UtilPlayer.message(player, F.main("Power Play Club", "You received 2x " + F.elem("Game Boosters") + "."));
}
Item omegaChest = manager.getItem("Omega Chest");
if (omegaChest == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, omegaChest.Name, 1);
UtilPlayer.message(player, F.main("Power Play Club", "You received 1x " + F.elem("Omega Chest") + "."));
}
}
}
/**
* Class to help on monthly bonuses
*/
public static class PowerPlayClubItem
{
private final String _prize;
private final int _amount;
private final ItemStack _display;
public PowerPlayClubItem(String prize, int amount, ItemStack display)
{
_prize = prize;
_amount = amount;
_display = display;
}
public String getPrize()
{
return _prize;
}
public int getAmount()
{
return _amount;
}
public ItemStack getDisplay()
{
return _display;
}
}
/**
* Class that stores player's months and last claimed month
*/
protected class PlayerMonths
{
private int _months;
private int _lastClaimed;
private int _year;
public PlayerMonths(int months, int lastClaimed, int year)
{
_months = months;
_lastClaimed = lastClaimed;
_year = year;
}
public int getMonths()
{
return _months;
}
public int getLastClaimed()
{
return _lastClaimed;
}
public int getYear()
{
return _year;
}
public void setMonths(int months)
{
_months = months;
}
public void setLastClaimed(int lastClaimed)
{
_lastClaimed = lastClaimed;
}
public void setYear(int year)
{
_year = year;
}
}
}

View File

@ -0,0 +1,118 @@
package mineplex.core.powerplayclub;
import mineplex.core.MiniClientPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.account.ILoginProcessor;
import mineplex.serverdata.database.DBPool;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.*;
import java.time.LocalDate;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class PowerPlayClubRepository extends MiniClientPlugin<PPCPlayerData> {
private final CoreClientManager _clientManager;
public PowerPlayClubRepository(JavaPlugin plugin, CoreClientManager clientManager) {
super("PowerPlayClubRepository", plugin);
_clientManager = clientManager;
clientManager.addStoredProcedureLoginProcessor(new ILoginProcessor() {
@Override
public String getName() {
return "PPC Claim Grabber";
}
@Override
public void processLoginResultSet(String playerName, UUID uuid, int accountId, ResultSet resultSet) throws SQLException {
PowerPlayClubRepository.this.Get(uuid).setClaimed(resultSet.next());
}
@Override
public String getQuery(int accountId, String uuid, String name) {
return "SELECT * FROM powerPlayClaims WHERE accountId = " + accountId + ";";
}
});
clientManager.addStoredProcedureLoginProcessor(new ILoginProcessor() {
@Override
public String getName() {
return "PPC Subscription Grabber";
}
@Override
public void processLoginResultSet(String playerName, UUID uuid, int accountId, ResultSet resultSet) throws SQLException {
PowerPlayClubRepository.this.Get(uuid).setSubscribed(resultSet.next());
}
@Override
public String getQuery(int accountId, String uuid, String name) {
return "SELECT * FROM powerPlaySubs WHERE accountId = " + accountId + ";";
}
});
}
public CompletableFuture<Void> addSubscription(int accountId, LocalDate date, String duration)
{
return CompletableFuture.supplyAsync(() ->
{
try (Connection connection = DBPool.getAccount().getConnection())
{
PreparedStatement statement = connection.prepareStatement("INSERT INTO powerPlaySubs (accountId, startDate, duration) VALUES (?, ?, ?)");
statement.setInt(1, accountId);
statement.setDate(2, Date.valueOf(date));
statement.setString(3, duration);
statement.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
return null;
});
}
public CompletableFuture<Boolean> attemptClaim(Player player)
{
int accountId = _clientManager.Get(player).getAccountId();
return CompletableFuture.supplyAsync(() ->
{
try (Connection connection = DBPool.getAccount().getConnection())
{
LocalDate date = LocalDate.now();
PreparedStatement statement = connection.prepareStatement("INSERT IGNORE INTO powerPlayClaims (accountId, claimMonth, claimYear) VALUES (?, ?, ?)");
statement.setInt(1, accountId);
statement.setInt(2, date.getMonthValue());
statement.setInt(3, date.getYear());
return statement.executeUpdate() == 1;
} catch (SQLException e)
{
e.printStackTrace();
}
return false;
});
}
public boolean alreadyClaimed(Player player)
{
return Get(player).hasClaimed();
}
public boolean canClaim(Player player)
{
return Get(player).hasSubscribed() && !Get(player).hasClaimed();
}
@Override
protected PPCPlayerData addPlayer(UUID uuid) {
return new PPCPlayerData();
}
}

View File

@ -0,0 +1,147 @@
package mineplex.core.powerplayclub;
import mineplex.core.common.util.BukkitFuture;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.inventory.data.Item;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.time.Month;
import java.time.Year;
import java.util.*;
public class PowerPlayClubRewards
{
private static final Map<RewardMonth, List<PowerPlayClubItem>> rewards = new HashMap<>();
static
{
setRewards(2016, Month.SEPTEMBER, new PowerPlayClubItem("Squid Morph", 1, new ItemStack(Material.INK_SACK)));
}
public static List<PowerPlayClubItem> septemberItems() // TODO: figure this out
{
return rewards.values().iterator().next();
}
private static void setRewards(int year, Month month, PowerPlayClubItem... items)
{
rewards.put(new RewardMonth(Year.of(year), month), Arrays.asList(items));
}
private static class RewardMonth
{
private final Year year;
private final Month month;
static RewardMonth of(Year year, Month month)
{
return new RewardMonth(year, month);
}
RewardMonth(Year year, Month month)
{
this.year = year;
this.month = month;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) return false;
RewardMonth that = (RewardMonth) obj;
return Objects.equals(this.year, that.year) && Objects.equals(this.month, that.month);
}
@Override
public int hashCode() {
return Objects.hash(year, month);
}
}
public static class PowerPlayClubItem
{
private final String _prize;
private final int _amount;
private final ItemStack _display;
public PowerPlayClubItem(String prize, int amount, ItemStack display)
{
_prize = prize;
_amount = amount;
_display = display;
}
public String getPrize()
{
return _prize;
}
public int getAmount()
{
return _amount;
}
public ItemStack getDisplay()
{
return _display;
}
}
public static void giveAllItems(Player player, InventoryManager manager, PowerPlayClubRepository repo)
{
UtilPlayer.message(player, F.main("Power Play Club", "Verifying subscription.."));
repo.attemptClaim(player).thenCompose(BukkitFuture.accept(success ->
{
if (!success)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
return;
}
repo.Get(player).setClaimed(true);
for (PowerPlayClubItem item : septemberItems()) // TODO: figure this out
{
Item fItem = manager.getItem(item.getPrize());
if (fItem == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, fItem.Name, 1);
UtilPlayer.message(player, F.main("Power Play Club", "You received " + item.getAmount() + "x " + F.elem(item.getPrize()) + "."));
}
}
Item gameAmplifier = manager.getItem("Game Booster");
if (gameAmplifier == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, gameAmplifier.Name, 2);
UtilPlayer.message(player, F.main("Power Play Club", "You received 2x " + F.elem("Game Boosters") + "."));
}
Item omegaChest = manager.getItem("Omega Chest");
if (omegaChest == null)
{
UtilPlayer.message(player, F.main("Power Play Club", "An unexpected error happened!"));
}
else
{
manager.addItemToInventory(player, omegaChest.Name, 1);
UtilPlayer.message(player, F.main("Power Play Club", "You received 1x " + F.elem("Omega Chest") + "."));
}
}));
}
}

View File

@ -38,9 +38,11 @@ public enum Preference
CLAN_TIPS(true, PreferenceCategory.MISC, Material.IRON_SWORD, "Show Clan Tips"),
HUB_MUSIC(true, PreferenceCategory.MISC, Material.NOTE_BLOCK, "Hub Music"),
//AUTO_JOIN_NEXT_GAME(true, PreferenceCategory.GAME_PLAY, Material.DIAMOND_SWORD, "Auto Join Next Game"),
//COUNTDOWN_ON_CLICK(true, PreferenceCategory.GAME_PLAY, Material.EMERALD, "Countdown to Join"),
AUTO_JOIN_NEXT_GAME(true, PreferenceCategory.GAME_PLAY, Material.DIAMOND_SWORD, "Auto Join Next Game", "Feel like playing again?", "Enable this, and when you're out", "a 15 second timer will start", "when it ends, it'll send you", "to another game!"),
DISABLE_WARNING(true, PreferenceCategory.GAME_PLAY, Material.BARRIER, "Disable Automatic Warning", "Know what you're doing?", "Disable this to not receive", "a message warning you about Auto-Join"),
COUNTDOWN_ON_CLICK(false, PreferenceCategory.GAME_PLAY, Material.WATCH, "Countdown to Join", "See that fancy text when you're out?", "If you click it, and this is enabled", "a 15 second time will countdown", "until you are sent to a new game"),
;
private static final Map<Integer, Preference> PREFERENCE_MAP = Maps.newHashMap();
private static final Map<PreferenceCategory, List<Preference>> PREFERENCES_BY_CATEGORY = Maps.newHashMap();

View File

@ -13,7 +13,7 @@ public enum PreferenceCategory
USER("User", Material.PAPER),
EXCLUSIVE("Exclusive", Material.DIAMOND),
//GAME_PLAY("Game Mechanic", Material.REDSTONE_COMPARATOR),
GAME_PLAY("Game Mechanic", Material.REDSTONE_COMPARATOR),
MISC("Miscellaneous", Material.COMPASS),
FRIEND("Friend", Material.CHEST),
;

View File

@ -21,15 +21,6 @@ public class PreferenceMainMenu extends Menu<PreferencesManager>
private final int INV_SIZE_MAX = 54;
private final int INV_SIZE_MIN = 45;
private final int[] SLOTS_MAX = {
20, 22, 24, 30, 32
};
private final int[] SLOTS_MIN = {
19, 21, 23, 25
};
public PreferenceMainMenu(PreferencesManager plugin)
{
super("My Preferences", plugin);
@ -50,7 +41,7 @@ public class PreferenceMainMenu extends Menu<PreferencesManager>
list.remove(PreferenceCategory.EXCLUSIVE);
}
int[] slots = UtilUI.getIndicesFor(list.size(), 1, 4, 1);
int[] slots = UtilUI.getIndicesFor(list.size(), 2, 4, 0);
int size = list.size();

View File

@ -1,5 +1,6 @@
package mineplex.core.preferences.ui.buttons;
import com.google.common.collect.Lists;
import mineplex.core.common.util.C;
import mineplex.core.itemstack.ItemBuilder;
import mineplex.core.menu.Button;
@ -12,6 +13,8 @@ import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import java.util.List;
/**
*
*/
@ -32,15 +35,28 @@ public class PreferenceButton extends Button<PreferencesManager>
Material icon = preference.getIcon();
boolean head = icon == Material.SKULL_ITEM;
List<String> lore = Lists.newArrayList();
if(preference.getLore() != null)
{
lore.add(" ");
for(String s : preference.getLore())
{
lore.add(C.cGray + s);
}
}
_disabled = new ItemBuilder(preference.getIcon())
.setTitle(C.cRed + preference.getName())
.setLore(C.cRed + "Disabled", " " , C.cWhite + "Click to Enable")
.addLore(C.cRed + "Disabled", " " , C.cWhite + "Click to Enable")
.addLores(lore)
.setData(head ? (short) 3 : 0)
.build();
_enabled = new ItemBuilder(preference.getIcon())
.setTitle(C.cGreen + preference.getName())
.setLore(C.cGreen + "Enabled", " " , C.cWhite + "Click to Disable")
.addLore(C.cGreen + "Enabled", " " , C.cWhite + "Click to Disable")
.addLores(lore)
.setData(head ? (short) 3 : 0)
.build();

View File

@ -20,7 +20,7 @@ public class PlayerKitDataManager
public PlayerKit get(UUID uuid)
{
return _dataMapAccountUUID.getOrDefault(uuid, new PlayerKit(uuid));
return _dataMapAccountUUID.get(uuid);
}
public void add(PlayerKit playerKit)

View File

@ -11,6 +11,7 @@ import mineplex.core.donation.DonationManager;
import mineplex.core.gadget.GadgetManager;
import mineplex.core.hologram.HologramManager;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.locations.LocationConstants;
import mineplex.core.pet.PetManager;
import mineplex.core.reward.Reward;
import mineplex.core.reward.RewardManager;
@ -18,9 +19,7 @@ import mineplex.core.reward.RewardPool;
import mineplex.core.reward.RewardType;
import mineplex.core.stats.StatsManager;
import mineplex.core.status.ServerStatusManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
@ -50,35 +49,14 @@ public class TreasureManager extends MiniPlugin
_statsManager = statsManager;
_rewardManager = rewardManager;
World world = Bukkit.getWorlds().get(0);
_treasureLocations = Lists.newArrayList();
_treasureLocations = new ArrayList<>();
for(Location location : LocationConstants.CHEST_LOCATIONS)
{
Block chestBlock = world.getBlockAt(-31, 73, -11);
Block[] blocks = setup(chestBlock);
Location resetLocation = new Location(world, -26.5, 72, -11.5);
_treasureLocations.add(new TreasureLocation(this, _inventoryManager, clientManager, donationManager, chestBlock, blocks, resetLocation, _hologramManager, gadgetManager, statusManager));
}
Location resetLocation = LocationConstants.getResetLocation(location);
Block[] blocks = setup(location.getBlock());
{
Block chestBlock = world.getBlockAt(-22, 73, -34);
Block[] blocks = setup(chestBlock);
Location resetLocation = new Location(world, -22.5, 72, -29.5);
_treasureLocations.add(new TreasureLocation(this, _inventoryManager, clientManager, donationManager, chestBlock, blocks, resetLocation, _hologramManager, gadgetManager, statusManager));
}
{
Block chestBlock = world.getBlockAt(22, 75, -34);
Block[] blocks = setup(chestBlock);
Location resetLocation = new Location(world, 19.5, 74, -30.5);
_treasureLocations.add(new TreasureLocation(this, _inventoryManager, clientManager, donationManager, chestBlock, blocks, resetLocation, _hologramManager, gadgetManager, statusManager));
}
{
Block chestBlock = world.getBlockAt(31, 74, -11);
Block[] blocks = setup(chestBlock);
Location resetLocation = new Location(world, 27.5, 73, -15.5);
_treasureLocations.add(new TreasureLocation(this, _inventoryManager, clientManager, donationManager, chestBlock, blocks, resetLocation, _hologramManager, gadgetManager, statusManager));
_treasureLocations.add(new TreasureLocation(this, _inventoryManager, clientManager, donationManager, location.getBlock(), blocks, resetLocation, _hologramManager, gadgetManager, statusManager));
}
for (TreasureLocation treasureLocation : _treasureLocations)

View File

@ -65,6 +65,16 @@ public class Npcs extends org.jooq.impl.TableImpl<mineplex.database.tables.recor
* The column <code>Account.npcs.z</code>.
*/
public final org.jooq.TableField<mineplex.database.tables.records.NpcsRecord, java.lang.Double> z = createField("z", org.jooq.impl.SQLDataType.FLOAT.nullable(false), this, "");
/**
* The column <code>Account.npcs.yaw</code>.
*/
public final org.jooq.TableField<mineplex.database.tables.records.NpcsRecord, java.lang.Double> yaw = createField("yaw", org.jooq.impl.SQLDataType.FLOAT.nullable(false).defaulted(true), this, "");
/**
* The column <code>Account.npcs.pitch</code>.
*/
public final org.jooq.TableField<mineplex.database.tables.records.NpcsRecord, java.lang.Double> pitch = createField("pitch", org.jooq.impl.SQLDataType.FLOAT.nullable(false).defaulted(true), this, "");
/**
* The column <code>Account.npcs.radius</code>.

View File

@ -14,7 +14,7 @@ package mineplex.database.tables.records;
comments = "This class is generated by jOOQ"
)
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.database.tables.records.NpcsRecord> implements java.io.Serializable, java.lang.Cloneable, org.jooq.Record19<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> {
public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.database.tables.records.NpcsRecord> implements java.io.Serializable, java.lang.Cloneable, org.jooq.Record21<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> {
private static final long serialVersionUID = -112578515;
@ -115,173 +115,201 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
public java.lang.Double getZ() {
return (java.lang.Double) getValue(6);
}
/**
* Setter for <code>Account.npcs.yaw</code>.
*/
public void setYaw(java.lang.Double value) {
setValue(7, value);
}
/**
* Getter for <code>Account.npcs.yaw</code>.
*/
public java.lang.Double getYaw() {
return (java.lang.Double) getValue(7);
}
/**
* Setter for <code>Account.npcs.pitch</code>.
*/
public void setPitch(java.lang.Double value) {
setValue(8, value);
}
/**
* Getter for <code>Account.npcs.pitch</code>.
*/
public java.lang.Double getPitch() {
return (java.lang.Double) getValue(8);
}
/**
* Setter for <code>Account.npcs.radius</code>.
*/
public void setRadius(java.lang.Double value) {
setValue(7, value);
setValue(9, value);
}
/**
* Getter for <code>Account.npcs.radius</code>.
*/
public java.lang.Double getRadius() {
return (java.lang.Double) getValue(7);
return (java.lang.Double) getValue(9);
}
/**
* Setter for <code>Account.npcs.entityType</code>.
*/
public void setEntityType(java.lang.String value) {
setValue(8, value);
setValue(10, value);
}
/**
* Getter for <code>Account.npcs.entityType</code>.
*/
public java.lang.String getEntityType() {
return (java.lang.String) getValue(8);
return (java.lang.String) getValue(10);
}
/**
* Setter for <code>Account.npcs.entityMeta</code>.
*/
public void setEntityMeta(java.lang.String value) {
setValue(9, value);
setValue(11, value);
}
/**
* Getter for <code>Account.npcs.entityMeta</code>.
*/
public java.lang.String getEntityMeta() {
return (java.lang.String) getValue(9);
return (java.lang.String) getValue(11);
}
/**
* Setter for <code>Account.npcs.adult</code>.
*/
public void setAdult(java.lang.Boolean value) {
setValue(10, value);
setValue(12, value);
}
/**
* Getter for <code>Account.npcs.adult</code>.
*/
public java.lang.Boolean getAdult() {
return (java.lang.Boolean) getValue(10);
return (java.lang.Boolean) getValue(12);
}
/**
* Setter for <code>Account.npcs.helmet</code>.
*/
public void setHelmet(java.lang.String value) {
setValue(11, value);
setValue(13, value);
}
/**
* Getter for <code>Account.npcs.helmet</code>.
*/
public java.lang.String getHelmet() {
return (java.lang.String) getValue(11);
return (java.lang.String) getValue(13);
}
/**
* Setter for <code>Account.npcs.chestplate</code>.
*/
public void setChestplate(java.lang.String value) {
setValue(12, value);
setValue(14, value);
}
/**
* Getter for <code>Account.npcs.chestplate</code>.
*/
public java.lang.String getChestplate() {
return (java.lang.String) getValue(12);
return (java.lang.String) getValue(14);
}
/**
* Setter for <code>Account.npcs.leggings</code>.
*/
public void setLeggings(java.lang.String value) {
setValue(13, value);
setValue(15, value);
}
/**
* Getter for <code>Account.npcs.leggings</code>.
*/
public java.lang.String getLeggings() {
return (java.lang.String) getValue(13);
return (java.lang.String) getValue(15);
}
/**
* Setter for <code>Account.npcs.boots</code>.
*/
public void setBoots(java.lang.String value) {
setValue(14, value);
setValue(16, value);
}
/**
* Getter for <code>Account.npcs.boots</code>.
*/
public java.lang.String getBoots() {
return (java.lang.String) getValue(14);
return (java.lang.String) getValue(16);
}
/**
* Setter for <code>Account.npcs.inHand</code>.
*/
public void setInHand(java.lang.String value) {
setValue(15, value);
setValue(17, value);
}
/**
* Getter for <code>Account.npcs.inHand</code>.
*/
public java.lang.String getInHand() {
return (java.lang.String) getValue(15);
return (java.lang.String) getValue(17);
}
/**
* Setter for <code>Account.npcs.info</code>.
*/
public void setInfo(java.lang.String value) {
setValue(16, value);
setValue(18, value);
}
/**
* Getter for <code>Account.npcs.info</code>.
*/
public java.lang.String getInfo() {
return (java.lang.String) getValue(16);
return (java.lang.String) getValue(18);
}
/**
* Setter for <code>Account.npcs.infoRadius</code>.
*/
public void setInfoRadius(java.lang.Double value) {
setValue(17, value);
setValue(19, value);
}
/**
* Getter for <code>Account.npcs.infoRadius</code>.
*/
public java.lang.Double getInfoRadius() {
return (java.lang.Double) getValue(17);
return (java.lang.Double) getValue(19);
}
/**
* Setter for <code>Account.npcs.infoDelay</code>.
*/
public void setInfoDelay(java.lang.Integer value) {
setValue(18, value);
setValue(20, value);
}
/**
* Getter for <code>Account.npcs.infoDelay</code>.
*/
public java.lang.Integer getInfoDelay() {
return (java.lang.Integer) getValue(18);
return (java.lang.Integer) getValue(20);
}
// -------------------------------------------------------------------------
@ -304,16 +332,16 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Row19<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> fieldsRow() {
return (org.jooq.Row19) super.fieldsRow();
public org.jooq.Row21<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> fieldsRow() {
return (org.jooq.Row21) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row19<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> valuesRow() {
return (org.jooq.Row19) super.valuesRow();
public org.jooq.Row21<java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.String, java.lang.String, java.lang.Boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Double, java.lang.Integer> valuesRow() {
return (org.jooq.Row21) super.valuesRow();
}
/**
@ -371,12 +399,28 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
public org.jooq.Field<java.lang.Double> field7() {
return mineplex.database.tables.Npcs.npcs.z;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Double> field8() {
return mineplex.database.tables.Npcs.npcs.yaw;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Double> field9() {
return mineplex.database.tables.Npcs.npcs.pitch;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Double> field10() {
return mineplex.database.tables.Npcs.npcs.radius;
}
@ -384,7 +428,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field9() {
public org.jooq.Field<java.lang.String> field11() {
return mineplex.database.tables.Npcs.npcs.entityType;
}
@ -392,7 +436,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field10() {
public org.jooq.Field<java.lang.String> field12() {
return mineplex.database.tables.Npcs.npcs.entityMeta;
}
@ -400,7 +444,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Boolean> field11() {
public org.jooq.Field<java.lang.Boolean> field13() {
return mineplex.database.tables.Npcs.npcs.adult;
}
@ -408,7 +452,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field12() {
public org.jooq.Field<java.lang.String> field14() {
return mineplex.database.tables.Npcs.npcs.helmet;
}
@ -416,7 +460,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field13() {
public org.jooq.Field<java.lang.String> field15() {
return mineplex.database.tables.Npcs.npcs.chestplate;
}
@ -424,7 +468,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field14() {
public org.jooq.Field<java.lang.String> field16() {
return mineplex.database.tables.Npcs.npcs.leggings;
}
@ -432,7 +476,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field15() {
public org.jooq.Field<java.lang.String> field17() {
return mineplex.database.tables.Npcs.npcs.boots;
}
@ -440,7 +484,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field16() {
public org.jooq.Field<java.lang.String> field18() {
return mineplex.database.tables.Npcs.npcs.inHand;
}
@ -448,7 +492,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field17() {
public org.jooq.Field<java.lang.String> field19() {
return mineplex.database.tables.Npcs.npcs.info;
}
@ -456,7 +500,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Double> field18() {
public org.jooq.Field<java.lang.Double> field20() {
return mineplex.database.tables.Npcs.npcs.infoRadius;
}
@ -464,7 +508,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Integer> field19() {
public org.jooq.Field<java.lang.Integer> field21() {
return mineplex.database.tables.Npcs.npcs.infoDelay;
}
@ -523,12 +567,28 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
public java.lang.Double value7() {
return getZ();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Double value8() {
return getYaw();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Double value9() {
return getPitch();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Double value10() {
return getRadius();
}
@ -536,7 +596,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value9() {
public java.lang.String value11() {
return getEntityType();
}
@ -544,7 +604,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value10() {
public java.lang.String value12() {
return getEntityMeta();
}
@ -552,7 +612,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.Boolean value11() {
public java.lang.Boolean value13() {
return getAdult();
}
@ -560,7 +620,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value12() {
public java.lang.String value14() {
return getHelmet();
}
@ -568,7 +628,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value13() {
public java.lang.String value15() {
return getChestplate();
}
@ -576,7 +636,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value14() {
public java.lang.String value16() {
return getLeggings();
}
@ -584,7 +644,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value15() {
public java.lang.String value17() {
return getBoots();
}
@ -592,7 +652,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value16() {
public java.lang.String value18() {
return getInHand();
}
@ -600,7 +660,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.String value17() {
public java.lang.String value19() {
return getInfo();
}
@ -608,7 +668,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.Double value18() {
public java.lang.Double value20() {
return getInfoRadius();
}
@ -616,7 +676,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public java.lang.Integer value19() {
public java.lang.Integer value21() {
return getInfoDelay();
}
@ -682,12 +742,30 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
setZ(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public NpcsRecord value8(java.lang.Double value) {
setYaw(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public NpcsRecord value9(java.lang.Double value) {
setPitch(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public NpcsRecord value10(java.lang.Double value) {
setRadius(value);
return this;
}
@ -696,7 +774,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value9(java.lang.String value) {
public NpcsRecord value11(java.lang.String value) {
setEntityType(value);
return this;
}
@ -705,7 +783,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value10(java.lang.String value) {
public NpcsRecord value12(java.lang.String value) {
setEntityMeta(value);
return this;
}
@ -714,7 +792,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value11(java.lang.Boolean value) {
public NpcsRecord value13(java.lang.Boolean value) {
setAdult(value);
return this;
}
@ -723,7 +801,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value12(java.lang.String value) {
public NpcsRecord value14(java.lang.String value) {
setHelmet(value);
return this;
}
@ -732,7 +810,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value13(java.lang.String value) {
public NpcsRecord value15(java.lang.String value) {
setChestplate(value);
return this;
}
@ -741,7 +819,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value14(java.lang.String value) {
public NpcsRecord value16(java.lang.String value) {
setLeggings(value);
return this;
}
@ -750,7 +828,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value15(java.lang.String value) {
public NpcsRecord value17(java.lang.String value) {
setBoots(value);
return this;
}
@ -759,7 +837,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value16(java.lang.String value) {
public NpcsRecord value18(java.lang.String value) {
setInHand(value);
return this;
}
@ -768,7 +846,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value17(java.lang.String value) {
public NpcsRecord value19(java.lang.String value) {
setInfo(value);
return this;
}
@ -777,7 +855,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value18(java.lang.Double value) {
public NpcsRecord value20(java.lang.Double value) {
setInfoRadius(value);
return this;
}
@ -786,7 +864,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord value19(java.lang.Integer value) {
public NpcsRecord value21(java.lang.Integer value) {
setInfoDelay(value);
return this;
}
@ -795,7 +873,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
* {@inheritDoc}
*/
@Override
public NpcsRecord values(java.lang.Integer value1, java.lang.String value2, java.lang.String value3, java.lang.String value4, java.lang.Double value5, java.lang.Double value6, java.lang.Double value7, java.lang.Double value8, java.lang.String value9, java.lang.String value10, java.lang.Boolean value11, java.lang.String value12, java.lang.String value13, java.lang.String value14, java.lang.String value15, java.lang.String value16, java.lang.String value17, java.lang.Double value18, java.lang.Integer value19) {
public NpcsRecord values(java.lang.Integer value1, java.lang.String value2, java.lang.String value3, java.lang.String value4, java.lang.Double value5, java.lang.Double value6, java.lang.Double value7, java.lang.Double value8, java.lang.Double value9, java.lang.Double value10, java.lang.String value11, java.lang.String value12, java.lang.Boolean value13, java.lang.String value14, java.lang.String value15, java.lang.String value16, java.lang.String value17, java.lang.String value18, java.lang.String value19, java.lang.Double value20, java.lang.Integer value21) {
return this;
}
@ -813,7 +891,7 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
/**
* Create a detached, initialised NpcsRecord
*/
public NpcsRecord(java.lang.Integer id, java.lang.String server, java.lang.String name, java.lang.String world, java.lang.Double x, java.lang.Double y, java.lang.Double z, java.lang.Double radius, java.lang.String entityType, java.lang.String entityMeta, java.lang.Boolean adult, java.lang.String helmet, java.lang.String chestplate, java.lang.String leggings, java.lang.String boots, java.lang.String inHand, java.lang.String info, java.lang.Double infoRadius, java.lang.Integer infoDelay) {
public NpcsRecord(java.lang.Integer id, java.lang.String server, java.lang.String name, java.lang.String world, java.lang.Double x, java.lang.Double y, java.lang.Double z, java.lang.Double yaw, java.lang.Double pitch, java.lang.Double radius, java.lang.String entityType, java.lang.String entityMeta, java.lang.Boolean adult, java.lang.String helmet, java.lang.String chestplate, java.lang.String leggings, java.lang.String boots, java.lang.String inHand, java.lang.String info, java.lang.Double infoRadius, java.lang.Integer infoDelay) {
super(mineplex.database.tables.Npcs.npcs);
setValue(0, id);
@ -823,17 +901,19 @@ public class NpcsRecord extends org.jooq.impl.UpdatableRecordImpl<mineplex.datab
setValue(4, x);
setValue(5, y);
setValue(6, z);
setValue(7, radius);
setValue(8, entityType);
setValue(9, entityMeta);
setValue(10, adult);
setValue(11, helmet);
setValue(12, chestplate);
setValue(13, leggings);
setValue(14, boots);
setValue(15, inHand);
setValue(16, info);
setValue(17, infoRadius);
setValue(18, infoDelay);
setValue(7, yaw);
setValue(8, pitch);
setValue(9, radius);
setValue(10, entityType);
setValue(11, entityMeta);
setValue(12, adult);
setValue(13, helmet);
setValue(14, chestplate);
setValue(15, leggings);
setValue(16, boots);
setValue(17, inHand);
setValue(18, info);
setValue(19, infoRadius);
setValue(20, infoDelay);
}
}

View File

@ -1,12 +1,5 @@
package mineplex.enjinTranslator;
import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager;
@ -14,10 +7,9 @@ import mineplex.core.common.Rank;
import mineplex.core.common.currency.GlobalCurrency;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UUIDFetcher;
import mineplex.core.donation.DonationManager;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.powerplayclub.PowerPlayClubManager;
import mineplex.core.powerplayclub.PowerPlayClubRepository;
import mineplex.core.server.util.TransactionResponse;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
@ -29,13 +21,21 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.plugin.java.JavaPlugin;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.AbstractMap;
import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
public class Enjin extends MiniPlugin implements CommandExecutor
{
private CoreClientManager _clientManager;
private DonationManager _donationManager;
private InventoryManager _inventoryManager;
private PurchaseManager _purchaseManager;
private PowerPlayClubManager _powerPlayClubManager;
private PowerPlayClubRepository _powerPlayClubRepository;
private NautHashMap<String, Entry<UUID, Long>> _cachedUUIDs = new NautHashMap<String, Entry<UUID, Long>>();
private static Object _commandLock = new Object();
@ -53,7 +53,7 @@ public class Enjin extends MiniPlugin implements CommandExecutor
_inventoryManager = inventoryManager;
_purchaseManager = new PurchaseManager(plugin);
_powerPlayClubManager = donationManager.getPowerPlayClubManager();
_powerPlayClubRepository = new PowerPlayClubRepository(plugin, clientManager);
plugin.getCommand("enjin_mineplex").setExecutor(this);
plugin.getCommand("pull").setExecutor(this);
@ -287,18 +287,24 @@ public class Enjin extends MiniPlugin implements CommandExecutor
protected boolean checkForPowerPlayClub(String[] args, final String name, final UUID playerUUID, final CoreClient client)
{
if (args.length != 3 || !args[0].equalsIgnoreCase("powerplayclub"))
if (args.length < 3 || !args[0].equalsIgnoreCase("powerplayclub"))
return false;
if (args[2].equalsIgnoreCase("month"))
if (args[2].equalsIgnoreCase("add"))
{
_powerPlayClubManager.addPlayerMonths(playerUUID, 1);
} else
String[] splitDate = args[3].split("/");
LocalDate date = LocalDate.of(Integer.parseInt(splitDate[2]), Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]));
String duration = args[4];
_powerPlayClubRepository.addSubscription(client.getAccountId(), date, duration);
} else if (args[2].equalsIgnoreCase("cancel"))
{
_powerPlayClubManager.addPlayerMonths(playerUUID, 12);
// TODO: cancel it in our logs? I don't think this is necessary.
}
return true;
return false;
}
protected boolean checkForClansPurchase(String[] args, final String name, final CoreClient client)

View File

@ -33,7 +33,7 @@ public class TutorialRegion
private void pasteSchematic()
{
_locationMap = _schematic.paste(getOrigin(), false);
_locationMap = _schematic.paste(getOrigin(), false).getDataLocationMap();
}
/**

View File

@ -14,6 +14,8 @@ import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.boosters.BoosterManager;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.chat.ChatFormat;
import mineplex.core.chat.IChatMessageFormatter;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
@ -120,7 +122,7 @@ import java.util.UUID;
/**
* Main manager for clans hub
*/
public class HubManager extends MiniPlugin
public class HubManager extends MiniPlugin implements IChatMessageFormatter
{
private BlockRestore _blockRestore;
private CoreClientManager _clientManager;
@ -176,16 +178,6 @@ public class HubManager extends MiniPlugin
_portal = portal;
_spawn = new Location(UtilWorld.getWorld("world"), 0.5, 179, 0.5, -90f, 0f);
runSyncLater(() ->
{
for (Entity e : _spawn.getWorld().getEntities())
{
if (npcManager.getNpcByEntity(e) != null)
{
e.teleport(new Location(e.getWorld(), e.getLocation().getX(), e.getLocation().getY(), e.getLocation().getZ(), 90f, 0f));
}
}
}, 120L);
((CraftWorld) _spawn.getWorld()).getHandle().spigotConfig.itemMerge = 0;
new WorldManager(this);
@ -538,6 +530,33 @@ public class HubManager extends MiniPlugin
}
}
@Override
public ChatFormat getChatFormat(Player player, String message)
{
Rank rank = GetClients().Get(player).getRealOrDisguisedRank();
//Level Prefix
String levelStr = _achievementManager.getMineplexLevel(player, rank);
//Rank Prefix
String rankStr = "";
if (rank != Rank.ALL)
rankStr = rank.getTag(true, true) + " ";
TextComponent rankComponent = new TextComponent(rankStr);
TextComponent playerNameText = new TextComponent(ChatColor.YELLOW + "%1$s");
TextComponent component = new TextComponent();
rankComponent.setHoverEvent(new HoverEvent(Action.SHOW_TEXT, new ComponentBuilder(rank.getColor() + rank.getTag(true, true) + ChatColor.WHITE + "\n" + rank.getDescription()).create()));
component.setText(levelStr);
component.addExtra(rankComponent);
component.addExtra(playerNameText);
component.addExtra(" " + ChatColor.WHITE + "%2$s");
return new ChatFormat(component.toLegacyText(), false);
}
@EventHandler
public void Damage(EntityDamageEvent event)
{

View File

@ -1,10 +1,4 @@
package mineplex.hub;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import mineplex.core.Managers;
import mineplex.core.MiniClientPlugin;
import mineplex.core.account.CoreClient;
@ -17,6 +11,8 @@ import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.bonuses.BonusManager;
import mineplex.core.boosters.BoosterManager;
import mineplex.core.botspam.BotSpamManager;
import mineplex.core.chat.ChatFormat;
import mineplex.core.chat.IChatMessageFormatter;
import mineplex.core.common.Rank;
import mineplex.core.common.currency.GlobalCurrency;
import mineplex.core.common.util.*;
@ -35,6 +31,7 @@ import mineplex.core.incognito.IncognitoManager;
import mineplex.core.incognito.events.IncognitoHidePlayerEvent;
import mineplex.core.interactions.NewInteractionsManager;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.locations.LocationConstants;
import mineplex.core.menu.MenuManager;
import mineplex.core.message.PrivateMessageEvent;
import mineplex.core.mount.MountManager;
@ -105,7 +102,13 @@ import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class HubManager extends MiniClientPlugin<HubClient>
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class HubManager extends MiniClientPlugin<HubClient> implements IChatMessageFormatter
{
// Snowman!
public HubType Type = HubType.Normal;
@ -141,6 +144,7 @@ public class HubManager extends MiniClientPlugin<HubClient>
private JumpManager _jumpManager;
// private HalloweenSpookinessManager _halloweenManager;
// private TrickOrTreatManager _trickOrTreatManager;
private MavericksManager _mavericksManager;
private Location _spawn;
@ -176,7 +180,7 @@ public class HubManager extends MiniClientPlugin<HubClient>
_portal = portal;
_spawn = new Location(UtilWorld.getWorld("world"), 0.5, 79, -23.5);
_spawn = LocationConstants.HUB_SPAWN.clone().add(0, 5, 0);
// Disable item merging
((CraftWorld) _spawn.getWorld()).getHandle().spigotConfig.itemMerge = 0;
@ -195,17 +199,21 @@ public class HubManager extends MiniClientPlugin<HubClient>
FacebookManager facebookManager = new FacebookManager(plugin, clientManager, donationManager, inventoryManager);
YoutubeManager youtubeManager = new YoutubeManager(plugin, clientManager, donationManager);
_bonusManager = new BonusManager(plugin, clientManager, serverStatusManager, donationManager, pollManager , npcManager, hologramManager, statsManager, _inventoryManager, petManager, facebookManager, youtubeManager, _gadgetManager, thankManager);
_treasureManager = new TreasureManager(_plugin, clientManager, serverStatusManager, donationManager, _inventoryManager, petManager, _gadgetManager, _blockRestore, hologramManager, statsManager, _bonusManager.getRewardManager());
CosmeticManager cosmeticManager = new CosmeticManager(_plugin, clientManager, donationManager, _inventoryManager, _gadgetManager, _mountManager, petManager, _treasureManager, boosterManager);
_mavericksManager = new MavericksManager(plugin, cosmeticManager, hologramManager, this);
new SoccerManager(this, _gadgetManager);
new KothManager(this, _gadgetManager);
new AntiSpamManager();
new MenuManager(_plugin);
new NewInteractionsManager();
AntiSpamManager antiSpam = new AntiSpamManager();
antiSpam.setMessageFormatter(this);
//new TrickOrTreatManager(_plugin, this, taskManager, donationManager, clientManager);
@ -712,6 +720,33 @@ public class HubManager extends MiniClientPlugin<HubClient>
}
}
@Override
public ChatFormat getChatFormat(Player player, String message)
{
Rank rank = GetClients().Get(player).getRealOrDisguisedRank();
//Level Prefix
String levelStr = _achievementManager.getMineplexLevel(player, rank);
//Rank Prefix
String rankStr = "";
if (rank != Rank.ALL)
rankStr = rank.getTag(true, true) + " ";
TextComponent rankComponent = new TextComponent(rankStr);
TextComponent playerNameText = new TextComponent(ChatColor.YELLOW + "%1$s");
TextComponent component = new TextComponent();
rankComponent.setHoverEvent(new HoverEvent(Action.SHOW_TEXT, new ComponentBuilder(rank.getColor() + rank.getTag(true, true) + ChatColor.WHITE + "\n" + rank.getDescription()).create()));
component.setText(levelStr);
component.addExtra(rankComponent);
component.addExtra(playerNameText);
component.addExtra(" " + ChatColor.WHITE + "%2$s");
return new ChatFormat(component.toLegacyText(), false);
}
@EventHandler
public void Damage(EntityDamageEvent event)
{
@ -855,6 +890,11 @@ public class HubManager extends MiniClientPlugin<HubClient>
{
return _punishManager;
}
public MavericksManager getMavericksManager()
{
return _mavericksManager;
}
// public HalloweenSpookinessManager getHalloweenManager()
// {

View File

@ -107,6 +107,11 @@ public class KothManager extends MiniPlugin
public boolean inPlayerArena(Entity entity)
{
if (!entity.getWorld().equals(_cornerPlayerA.getWorld()))
{
return false;
}
return UtilAlg.inBoundingBox(entity.getLocation(), _cornerPlayerA, _cornerPlayerB);
}

View File

@ -0,0 +1,351 @@
package mineplex.hub.modules;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.BukkitFuture;
import mineplex.core.cosmetic.CosmeticManager;
import mineplex.core.hologram.HologramManager;
import mineplex.core.mavericks.DisplaySlot;
import mineplex.core.mavericks.MavericksApprovedRepository;
import mineplex.core.mavericks.MavericksApprovedWrapper;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.hub.HubManager;
import mineplex.hub.modules.mavericks.MavericksPortalManager;
import mineplex.hub.modules.mavericks.MavericksWorldManager;
import mineplex.hub.modules.mavericks.basketball.BasketballManager;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.spigotmc.event.entity.EntityMountEvent;
/**
* A manager to handle all mavericks related content in the hub. Holds the mavericks portal manager in addition to handle
* the rotation of the "best of" builds from Mavericks Master Builders.
*/
public class MavericksManager extends MiniPlugin
{
// private static final long ROTATION_TIME = 1000*60*60*6;
private static final long ROTATION_TIME = 1000*30;
private MavericksPortalManager _portalManager;
private MavericksWorldManager _worldManager;
private MavericksApprovedRepository _repoApproved;
private List<DisplaySlot> _displaySlots = new ArrayList<>();
public MavericksManager(JavaPlugin plugin, CosmeticManager cosmeticManager, HologramManager hologramManager, HubManager hub)
{
super("Mavericks", plugin);
_worldManager = new MavericksWorldManager(plugin);
_portalManager = new MavericksPortalManager(plugin, hub, _worldManager, cosmeticManager);
_repoApproved = new MavericksApprovedRepository();
new BasketballManager(plugin, _worldManager, hub);
_displaySlots.add(new DisplaySlot(new Location(_worldManager.getWorld(), -41, 24, 237), hologramManager));
_displaySlots.add(new DisplaySlot(new Location(_worldManager.getWorld(), 19, 24, 237), hologramManager));
}
/**
* Main task to handle the rotation. Pulls data from the SQL DB and displays it in-game.
*/
@EventHandler
public void onUpdate(UpdateEvent event)
{
if(event.getType() != UpdateType.SLOW) return;
Function<? super List<MavericksApprovedWrapper>, ? extends CompletionStage<Void>> updateTask = BukkitFuture.accept((list) ->
{
List<DisplaySlot> openSlots = new ArrayList<>();
List<MavericksApprovedWrapper> undisplayedData = new ArrayList<>();
undisplayedData.addAll(list);
slots:
for(DisplaySlot slot : _displaySlots)
{
if(slot.getData() != null)
{
for(MavericksApprovedWrapper build : list)
{
if(slot.getData().getBuild().getBuildId() == build.getBuild().getBuildId())
{
undisplayedData.remove(build);
continue slots;
}
}
}
openSlots.add(slot);
}
for(int i = 0; i < Math.min(openSlots.size(), undisplayedData.size()); i++)
{
MavericksApprovedWrapper approved = undisplayedData.get(i);
if(approved.getFirstDisplayed() == null)
{
_repoApproved.setDisplayDate(approved.getBuild().getBuildId());
}
openSlots.get(i).setData(approved);
}
});
List<DisplaySlot> outdated = new ArrayList<>();
for(DisplaySlot slot : _displaySlots)
{
if(slot.getData() == null) continue;
if(slot.getData().getFirstDisplayed() == null)
{
_repoApproved.setDisplayDate(slot.getData().getBuild().getBuildId());
slot.getData().setFirstDisplayed(System.currentTimeMillis());
}
else if(slot.getData().getFirstDisplayed() + ROTATION_TIME < System.currentTimeMillis())
{
outdated.add(slot);
}
}
if(outdated.size() > 0)
{
_repoApproved.getToDisplay(true, outdated.size(), _displaySlots.size()).thenCompose(BukkitFuture.accept((list2) ->
{
if(list2.isEmpty()) return;
long[] ids = new long[list2.size()];
for(int i = 0; i < list2.size(); i++)
{
ids[i] = outdated.get(i).getData().getBuild().getBuildId();
}
_repoApproved.setDisplay(false, ids).thenCompose(BukkitFuture.accept((success) ->
{
_repoApproved.getToDisplay(true, _displaySlots.size(), 0).thenCompose(updateTask);
}));
}));
}
else
{
_repoApproved.getToDisplay(true, _displaySlots.size(), 0).thenCompose(updateTask);
}
}
@EventHandler
public void updateParticles(UpdateEvent event)
{
if(event.getType() == UpdateType.FAST)
{
for(DisplaySlot d : _displaySlots)
{
d.updateParticles();
}
}
}
@EventHandler
public void onUnload(ChunkUnloadEvent event)
{
for(Entity e : event.getChunk().getEntities())
{
if(isStatueEntity(e))
{
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onGrow(BlockGrowEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onStructureGrow(StructureGrowEvent event)
{
for(BlockState b : event.getBlocks())
{
if(isInsideDisplaySlot(b.getBlock()))
{
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onForm(BlockFormEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onBlockFromTo(BlockFromToEvent event)
{
if(isInsideDisplaySlot(event.getBlock()) || isInsideDisplaySlot(event.getToBlock()))
event.setCancelled(true);
}
@EventHandler
public void onSpread(BlockSpreadEvent event)
{
if(isInsideDisplaySlot(event.getBlock()) || isInsideDisplaySlot(event.getSource()))
event.setCancelled(true);
}
@EventHandler
public void onEntityBlockFormEvent(EntityBlockFormEvent event)
{
if(isInsideDisplaySlot(event.getBlock()) || isStatueEntity(event.getEntity()))
event.setCancelled(true);
}
@EventHandler
public void onBurn(BlockBurnEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onFade(BlockFadeEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onRedstone(BlockRedstoneEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setNewCurrent(event.getOldCurrent());
}
@EventHandler
public void onDecay(LeavesDecayEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onPhysics(BlockPhysicsEvent event)
{
if(isInsideDisplaySlot(event.getBlock()))
event.setCancelled(true);
}
@EventHandler
public void onBlockIgnite(BlockIgniteEvent event)
{
if(isInsideDisplaySlot(event.getBlock()) || isInsideDisplaySlot(event.getIgnitingBlock()))
event.setCancelled(true);
}
@EventHandler
public void onInteract(PlayerInteractEvent event)
{
if(event.getClickedBlock() == null) return;
if(isInsideDisplaySlot(event.getClickedBlock()))
event.setCancelled(true);
}
@EventHandler
public void ignite(EntityCombustEvent event)
{
if(isStatueEntity(event.getEntity()))
event.setCancelled(true);
}
@EventHandler
public void onInteractEntity(PlayerInteractEntityEvent event)
{
if(isStatueEntity(event.getRightClicked()))
event.setCancelled(true);
}
@EventHandler
public void onInteractEntity(PlayerInteractAtEntityEvent event)
{
if(isStatueEntity(event.getRightClicked()))
event.setCancelled(true);
}
@EventHandler
public void onVehicleCollide(VehicleEntityCollisionEvent event)
{
if(isStatueEntity(event.getVehicle()))
event.setCancelled(true);
}
@EventHandler
public void onMount(EntityMountEvent event)
{
if(isStatueEntity(event.getMount()))
event.setCancelled(true);
}
public boolean isInsideDisplaySlot(Block block)
{
return isInsideDisplaySlot(block.getLocation().add(0.5, 0.5, 0.5));
}
public boolean isInsideDisplaySlot(Location loc)
{
for(DisplaySlot d : _displaySlots)
{
if(d.isInside(loc)) return true;
}
return false;
}
/**
* Check if an entity is spawned in and managed by the mavericks "best of" builds.
* @param e The entity you want to check.
* @return Returns true if the entity is spawned and managed by this mavericks manager.
*/
public boolean isStatueEntity(Entity e)
{
for(DisplaySlot d : _displaySlots)
{
if(d.isDisplaySlotEntity(e)) return true;
}
return false;
}
public MavericksPortalManager getPortalManager()
{
return _portalManager;
}
}

View File

@ -103,14 +103,14 @@ public class SoccerManager extends MiniPlugin
_cornerGoalPlayerA = new Location(hubManager.GetSpawn().getWorld(), -17.5, 67, -71.5);
_cornerGoalPlayerB = new Location(hubManager.GetSpawn().getWorld(), 29.5, 100, -80.5);
_cornerFieldA = new Location(hubManager.GetSpawn().getWorld(), -12.75, 67, -66.75);
_cornerFieldA = new Location(hubManager.GetSpawn().getWorld(), -12.75, 67, -65.75);
_cornerFieldB = new Location(hubManager.GetSpawn().getWorld(), 24.25, 100, -86.25);
_cornerRedGoalA = new Location(hubManager.GetSpawn().getWorld(), 27.75, 67.5, -73.25);
_cornerRedGoalB = new Location(hubManager.GetSpawn().getWorld(), 25.25, 72.5, -79.25);
_cornerRedGoalA = new Location(hubManager.GetSpawn().getWorld(), 27.75, 66.5, -73.25);
_cornerRedGoalB = new Location(hubManager.GetSpawn().getWorld(), 25.25, 74.5, -79.25);
_cornerBlueGoalA = new Location(hubManager.GetSpawn().getWorld(), -15.75, 67.5, -79.75);
_cornerBlueGoalB = new Location(hubManager.GetSpawn().getWorld(), -13.25, 72.5, -73.75);
_cornerBlueGoalA = new Location(hubManager.GetSpawn().getWorld(), -15.75, 66.5, -79.75);
_cornerBlueGoalB = new Location(hubManager.GetSpawn().getWorld(), -13.25, 74.5, -73.75);
//Store Gadgets
for (Gadget gadget : gadgetManager.getGadgets(GadgetType.COSTUME))
@ -351,6 +351,8 @@ public class SoccerManager extends MiniPlugin
public boolean inPlayerArena(Entity entity)
{
if(!entity.getWorld().equals(_cornerFieldA.getWorld())) return false;
return UtilAlg.inBoundingBox(entity.getLocation(), _cornerFieldPlayerA, _cornerFieldPlayerB) ||
UtilAlg.inBoundingBox(entity.getLocation(), _cornerGoalPlayerA, _cornerGoalPlayerB);
}

View File

@ -83,6 +83,9 @@ public class StackerManager extends MiniPlugin implements IThrown
if (stackee instanceof EnderDragon)
return;
if (Manager.getMavericksManager().isStatueEntity(stackee))
return;
if (stackee instanceof Player && ((Player)stackee).getGameMode() != GameMode.SURVIVAL)
return;

View File

@ -2,7 +2,6 @@ package mineplex.hub.modules;
import mineplex.core.MiniPlugin;
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;
@ -10,10 +9,8 @@ import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilWorld;
import mineplex.core.gadget.event.GadgetCollideEntityEvent;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.npc.NpcManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.hub.Hub;
import mineplex.hub.HubManager;
import mineplex.hub.HubType;
import mineplex.minecraft.game.core.damage.CustomDamageEvent;
@ -85,7 +82,6 @@ public class WorldManager extends MiniPlugin
}
world.setStorm(false);
world.setThundering(false);
fixEntities();
}
@EventHandler
@ -245,9 +241,9 @@ public class WorldManager extends MiniPlugin
return;
}
for (Player player : UtilServer.getPlayers())
for (Player player : Manager.GetSpawn().getWorld().getPlayers())
{
if (UtilMath.offset(player.getLocation(), Manager.GetSpawn()) > 210)
if (UtilMath.offset(player.getLocation(), Manager.GetSpawn()) > 350)
{
player.eject();
player.leaveVehicle();
@ -440,15 +436,4 @@ public class WorldManager extends MiniPlugin
event.setCancelled(true);
}
}
public void fixEntities()
{
NpcManager npcManager = ((Hub) Manager.getPlugin()).getNpcManager();
runSyncLater(() -> Manager.GetSpawn().getWorld().getEntities().stream().filter(e -> npcManager.getNpcByEntity(e) != null).forEach(e ->
{
float yaw = UtilAlg.GetYaw(UtilAlg.getTrajectory(e.getLocation(), Manager.GetSpawn()));
e.teleport(new Location(e.getWorld(), e.getLocation().getX(), e.getLocation().getY(), e.getLocation().getZ(), yaw, 0f));
}), 120L);
}
}

View File

@ -0,0 +1,154 @@
package mineplex.hub.modules.mavericks;
import mineplex.core.gadget.types.GadgetType;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityPortalEnterEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.F;
import mineplex.core.cosmetic.CosmeticManager;
import mineplex.core.gadget.event.GadgetEnableEvent;
import mineplex.core.npc.event.NpcDamageByEntityEvent;
import mineplex.core.npc.event.NpcInteractEntityEvent;
import mineplex.core.recharge.Recharge;
import mineplex.hub.HubManager;
/**
* A small teleportation manager to manage the portal from the hub to the mavericks world and back.
*/
public class MavericksPortalManager extends MiniPlugin
{
private Box _portalMavericksHub;
private Location _destHub;
private Location _destMavericks;
private CosmeticManager _cosmeticManager;
public MavericksPortalManager(JavaPlugin plugin, HubManager hubManager, MavericksWorldManager worldManager, CosmeticManager cosmeticManager)
{
super("Mavericks Teleporter", plugin);
_cosmeticManager = cosmeticManager;
_destMavericks = worldManager.getSpawn();
_portalMavericksHub = new Box(worldManager.getWorld().getName(), new Vector(3, 20, 316), new Vector(-1, 25, 317));
_destHub = hubManager.GetSpawn();
}
@EventHandler
public void onEnable(GadgetEnableEvent event)
{
if (event.getPlayer().getWorld().equals(_destMavericks.getWorld()) && event.getGadget().getGadgetType() != GadgetType.COSTUME)
{
event.setCancelled(true);
}
}
@EventHandler
public void onUseNPC(NpcInteractEntityEvent event)
{
if (ChatColor.stripColor(event.getNpc().getName()).contains("Mavericks Lobby"))
{
useMavsNpc(event.getPlayer());
}
}
@EventHandler
public void onUseNPC(NpcDamageByEntityEvent event)
{
if (!(event.getDamager() instanceof Player))
{
return;
}
Player player = (Player) event.getDamager();
if (ChatColor.stripColor(event.getNpc().getName()).contains("Mavericks Lobby") && Recharge.Instance.use(player, "Go to Mavs Lobby", 1000, false, false))
{
useMavsNpc(player);
}
}
@EventHandler
public void onEnter(EntityPortalEnterEvent event)
{
if (!(event.getEntity() instanceof Player))
{
return;
}
Player p = (Player) event.getEntity();
Box box = isInside(p);
if (box == null)
{
return;
}
_cosmeticManager.getPetManager().disableAll(p);
_cosmeticManager.getMountManager().DisableAll(p);
_cosmeticManager.getGadgetManager().disableAll(p);
if (box == _portalMavericksHub)
{
p.teleport(_destHub);
p.sendMessage(F.main("Teleporter", "Teleported to " + F.item("Hub") + " area."));
}
p.playSound(p.getLocation(), Sound.ENDERMAN_TELEPORT, 1, 1);
}
private void useMavsNpc(Player player)
{
_cosmeticManager.getPetManager().disableAll(player);
_cosmeticManager.getMountManager().DisableAll(player);
_cosmeticManager.getGadgetManager().disableAll(player);
player.teleport(_destMavericks);
player.sendMessage(F.main("Teleporter", "Teleported to " + F.item("Mavericks") + " area."));
player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1, 1);
}
private Box isInside(Player player)
{
if (_portalMavericksHub.isInside(player.getLocation()))
{
return _portalMavericksHub;
}
return null;
}
/**
* A small AABB box util class.
*/
private static class Box
{
private Vector _min;
private Vector _max;
private String _world;
public Box(String world, Vector a, Vector b)
{
_world = world;
_min = Vector.getMinimum(a, b);
_max = Vector.getMaximum(a, b);
}
public boolean isInside(Vector v)
{
return v.isInAABB(_min, _max);
}
public boolean isInside(Location loc)
{
return loc.getWorld().getName().equals(_world) && isInside(loc.toVector());
}
}
}

View File

@ -0,0 +1,93 @@
package mineplex.hub.modules.mavericks;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.worldgen.WorldGenCleanRoom;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
/**
* A small world manager for the mavericks world.
*/
public class MavericksWorldManager extends MiniPlugin
{
private World _world;
private Location _spawn;
public MavericksWorldManager(JavaPlugin plugin)
{
super("Mavericks World", plugin);
WorldCreator wc = new WorldCreator("Mav_Lobby");
wc.generator(new WorldGenCleanRoom());
_world = wc.createWorld();
_world.setGameRuleValue("doDaylightCycle", "false");
_world.setTime(6000);
_world.setPVP(true);
_spawn = new Location(_world, 1.5, 22, 287.5, -180, 0);
}
public Location getSpawn()
{
return _spawn.clone();
}
public World getWorld()
{
return _world;
}
public boolean isInWorld(Entity e)
{
return _world.equals(e.getWorld());
}
@EventHandler
public void onSpawn(CreatureSpawnEvent event)
{
if(isInWorld(event.getEntity()))
{
if(event.getSpawnReason() == SpawnReason.CUSTOM) return;
event.setCancelled(true);
}
}
@EventHandler
public void onWeather(WeatherChangeEvent event)
{
if(!event.getWorld().equals(_world)) return;
if(!event.toWeatherState()) return;
event.setCancelled(true);
}
@EventHandler
public void borderCheck(UpdateEvent event)
{
if(event.getType() != UpdateType.FAST)
{
for(Player p : _world.getPlayers())
{
if (UtilMath.offset(p.getLocation(), _world.getSpawnLocation()) > 400)
{
p.eject();
p.leaveVehicle();
p.teleport(getSpawn());
}
}
}
}
}

View File

@ -0,0 +1,647 @@
package mineplex.hub.modules.mavericks.basketball;
import java.util.HashMap;
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.UtilAlg;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilInv;
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.UtilTextBottom;
import mineplex.core.common.util.UtilTextMiddle;
import mineplex.core.common.util.UtilTime;
import mineplex.core.itemstack.ItemBuilder;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.hub.HubManager;
import net.minecraft.server.v1_8_R3.BlockPosition;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
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.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import com.google.common.collect.Lists;
/**
* Instance class for running a basketball game in the hub
*/
public class BasketballGame implements Listener
{
private HubManager _hub;
private World _world;
private List<Player> _players = Lists.newArrayList();
private Entity _ball;
private Player _dribbling;
private ThrowData _throwData;
private static final double THREE_POINTER_DISTANCE = 27;
private boolean _frozen = false;
private long _lastDribbleAnim = 0;
private long _lastDribbleMove = 0;
private long _start;
private HashMap<BasketballTeam, Block> _hoops = new HashMap<>();
private double _maxX = 0;
private double _minX = 0;
private double _maxZ = 0;
private double _minZ = 0;
private double _velocity = -7;
private int _redScore;
private int _blueScore;
public BasketballGame(JavaPlugin plugin, HubManager hub, World world)
{
_hub = hub;
_world = world;
setupMap();
Bukkit.getPluginManager().registerEvents(this, plugin);
beginGame();
_start = System.currentTimeMillis();
}
private Entity spawnBall(Location loc)
{
_velocity = -7;
Entity e = loc.getWorld().spawnEntity(loc, EntityType.SLIME);
UtilEnt.Vegetate(e, true);
UtilEnt.ghost(e, true, false);
((Slime)e).setSize(1);
return e;
}
private BasketballTeam getTeam(Player player)
{
if (player.getInventory().getHelmet() == null || !(player.getInventory().getHelmet().getItemMeta() instanceof LeatherArmorMeta))
{
return null;
}
Color color = ((LeatherArmorMeta)player.getInventory().getHelmet().getItemMeta()).getColor();
return BasketballTeam.getFromColor(color);
}
private boolean checkCatching()
{
if (_ball != null)
{
for (Player player : _players)
{
if (UtilMath.offset(player, _ball) <= 1.5)
{
if (Recharge.Instance.usable(player, "Catch Ball", false))
{
catchBall(player);
return true;
}
}
}
}
return false;
}
private int getWorth(Location start, Location hoop)
{
if (UtilMath.offset2d(start, hoop) >= THREE_POINTER_DISTANCE)
{
return 3;
}
return 2;
}
private void reboundBall()
{
if (_ball == null)
{
return;
}
Vector vec = _ball.getVelocity();
//Rebound Y
if (UtilEnt.isGrounded(_ball))
{
if (vec.getY() < 0)
{
vec.setY(_ball.getVelocity().getY() * _velocity);
_velocity = Math.max(0, _velocity - .5);
}
}
if (!UtilEnt.isGrounded(_ball))
{
vec.setY(vec.getY() - 0.08);
}
//Rebound X
if ((vec.getX() > 0 && _ball.getLocation().getX() >= _maxX) || (vec.getX() < 0 && _ball.getLocation().getX() <= _minX))
{
vec.setX(vec.getX() * -1);
vec = vec.multiply(0.9);
}
//Rebound Z
if ((vec.getZ() > 0 && _ball.getLocation().getZ() >= _maxZ) || (vec.getZ() < 0 && _ball.getLocation().getZ() <= _minZ))
{
vec.setZ(vec.getZ() * -1);
vec = vec.multiply(0.9);
}
_ball.setVelocity(vec);
}
private void spawnNeutralBall()
{
Location loc = DataLoc.CENTER_COURT.getLocation(_world);
_ball = spawnBall(loc);
}
private void throwBall(Player origin, boolean right)
{
Entity e = spawnBall(origin.getEyeLocation());
double power = 1.7;
if (right)
{
power = 3.1;
}
e.setVelocity(origin.getEyeLocation().getDirection().normalize().multiply(power));
Recharge.Instance.use(origin, "Catch Ball", 3000, false, false, false);
_ball = e;
if (_dribbling != null)
{
UtilInv.removeAll(_dribbling, Material.SLIME_BALL, (byte)0);
_dribbling = null;
}
_throwData = new ThrowData(origin, getTeam(origin));
}
private void catchBall(Player player)
{
_lastDribbleMove = System.currentTimeMillis();
_dribbling = player;
for (int i = 0; i < 8; i++)
{
_dribbling.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
_ball.remove();
_ball = null;
_throwData = null;
}
private void setupMap()
{
Block redHoop = DataLoc.RED_HOOP.getLocation(_world).getBlock();
redHoop.setType(Material.WEB);
Block blueHoop = DataLoc.BLUE_HOOP.getLocation(_world).getBlock();
blueHoop.setType(Material.WEB);
_hoops.put(BasketballTeam.RED, redHoop);
_hoops.put(BasketballTeam.BLUE, blueHoop);
_maxX = DataLoc.CORNER_MAX.getLocation(_world).getX();
_minX = DataLoc.CORNER_MIN.getLocation(_world).getX();
_maxZ = DataLoc.CORNER_MAX.getLocation(_world).getZ();
_minZ = DataLoc.CORNER_MIN.getLocation(_world).getZ();
}
private void beginGame()
{
spawnNeutralBall();
_ball.setVelocity(_ball.getVelocity().add(new Vector(0, 1.5, 0)));
}
private void stealBall(Player to, Player from)
{
Recharge.Instance.use(to, "ThrowBall", 1500, false, false, false);
_lastDribbleMove = System.currentTimeMillis();
_dribbling = to;
for (int i = 0; i < 8; i++)
{
to.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
UtilInv.removeAll(from, Material.SLIME_BALL, (byte)0);
for (Player player : _players)
{
UtilPlayer.message(player, F.main("Game", getTeam(to).getChatColor() + to.getName() + C.cGray + " has stolen the ball from " + getTeam(from).getChatColor() + from.getName() + C.cGray + "!"));
}
}
private void score(BasketballTeam team, Location hoop)
{
int points = getWorth(_throwData.getThrowOrigin(), hoop);
if (team == BasketballTeam.RED)
{
_redScore += points;
}
else if (team == BasketballTeam.BLUE)
{
_blueScore += points;
}
UtilTextMiddle.display(team.getName() + " has scored!", BasketballTeam.RED.getChatColor() + "" + _redScore + C.cWhite + " - " + BasketballTeam.BLUE.getChatColor() + _blueScore, 0, 20 * 2, 0, _players.toArray(new Player[] {}));
_ball.remove();
_ball = null;
_throwData = null;
BasketballTeam other = getOtherTeam(team);
List<Player> teamD = Lists.newArrayList();
List<Player> teamO = Lists.newArrayList();
for (Player player : _players)
{
if (getTeam(player) == team)
{
teamO.add(player);
}
else
{
teamD.add(player);
}
}
for (int i = 0; i < teamO.size(); i++)
{
Player player = teamO.get(i);
int locId = Math.min(i, team.getSpawns(_world).length);
player.teleport(team.getSpawns(_world)[locId]);
}
if (!teamD.isEmpty())
{
//Select player to get ball
Player carrier = teamD.get(new Random().nextInt(teamD.size()));
for (int i = 0; i < teamD.size(); i++)
{
Player player = teamD.get(i);
if (carrier.getEntityId() != player.getEntityId())
{
Location loc = null;
int locId = i;
if (other == BasketballTeam.BLUE)
{
locId = Math.min(DataLoc.BLUE_SCORE_SPAWN.getLocations(_world).length - 1, locId);
loc = DataLoc.BLUE_SCORE_SPAWN.getLocations(_world)[locId];
}
else if (other == BasketballTeam.RED)
{
locId = Math.min(DataLoc.RED_SCORE_SPAWN.getLocations(_world).length - 1, locId);
loc = DataLoc.RED_SCORE_SPAWN.getLocations(_world)[locId];
}
if (loc != null)
{
player.teleport(loc);
}
}
}
Location teleport = DataLoc.BLUE_HOOP.getLocation(_world);
if (other == BasketballTeam.RED)
teleport = DataLoc.RED_UNDER_HOOP.getLocation(_world);
teleport.setPitch(UtilAlg.GetPitch(UtilAlg.getTrajectory(teleport, DataLoc.CENTER_COURT.getLocation(_world))));
teleport.setYaw(UtilAlg.GetYaw(UtilAlg.getTrajectory(teleport, DataLoc.CENTER_COURT.getLocation(_world))));
carrier.teleport(teleport);
_lastDribbleMove = System.currentTimeMillis();
_dribbling = carrier;
for (int i = 0; i < 8; i++)
{
_dribbling.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
}
else
{
spawnNeutralBall();
}
}
private void checkScoring()
{
if (_ball == null)
{
return;
}
for (BasketballTeam team : _hoops.keySet())
{
Location check = _hoops.get(team).getLocation().add(.5, 0, .5);
if (UtilMath.offset(check, _ball.getLocation()) <= .9)
{
score(getOtherTeam(team), check);
return;
}
}
}
private void dribble()
{
if (_dribbling == null)
{
_lastDribbleAnim = System.currentTimeMillis();
return;
}
UtilTextBottom.display(C.cRed + "You have the ball!", _dribbling);
UtilParticle.PlayParticleToAll(ParticleType.HAPPY_VILLAGER, _dribbling.getEyeLocation(), new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat(), 0, 1, ViewDist.MAX);
if (System.currentTimeMillis() - _lastDribbleAnim > 333)
{
_lastDribbleAnim = System.currentTimeMillis();
Item item = _dribbling.getWorld().dropItem(_dribbling.getLocation(), new ItemStack(Material.SLIME_BALL));
item.setPickupDelay(Integer.MAX_VALUE);
Bukkit.getScheduler().runTaskLater(_hub.getPlugin(), () -> {
item.remove();
}, 7);
}
}
/**
* Checks how long this game has been running
* @return The amount of time this game has been running
*/
public long getGameAge()
{
return System.currentTimeMillis() - _start;
}
/**
* Checks whether a location is out of bounds of the main arena
* @param loc The location to check
* @param ball Whether to base calculations on the location being the location of the ball
* @return Whether the location is out of bounds
*/
public boolean isOutOfBounds(Location loc, boolean ball)
{
if (ball)
{
if ((loc.getX() - 1) > _maxX || (loc.getX() + 1) < _minX)
{
return true;
}
if ((loc.getZ() - 1) > _maxZ || (loc.getZ() + 1) < _minZ)
{
return true;
}
return false;
}
if (loc.getX() >= _maxX || loc.getX() <= _minX)
{
return true;
}
if (loc.getZ() >= _maxZ || loc.getZ() <= _minZ)
{
return true;
}
return false;
}
/**
* Fetches the entity representing the ball in this game
* @return The entity representing the ball, or null if a player is dribbling
*/
public Entity getBall()
{
return _ball;
}
/**
* Quickly searches for the opposite team of the one given
* @param team The team to check
* @return The opposite team
*/
public BasketballTeam getOtherTeam(BasketballTeam team)
{
if (team == BasketballTeam.RED)
{
return BasketballTeam.BLUE;
}
if (team == BasketballTeam.BLUE)
{
return BasketballTeam.RED;
}
return null;
}
/**
* Fetches the list of players in this game
* @return The list containing all players in this game
*/
public List<Player> getPlayers()
{
return _players;
}
/**
* Forces the game to end, unregistering all listeners and cleaning up created entities
*/
public void end()
{
HandlerList.unregisterAll(this);
if (_ball != null)
{
_ball.remove();
}
if (_dribbling != null)
{
UtilInv.removeAll(_dribbling, Material.SLIME_BALL, (byte)0);
}
}
@EventHandler
public void onSwipe(EntityDamageByEntityEvent event)
{
if (_frozen)
return;
if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof Player))
{
return;
}
if (!_players.contains((Player)event.getEntity()) || !_players.contains((Player)event.getDamager()))
{
return;
}
Player player = (Player)event.getDamager();
Player target = (Player)event.getEntity();
if (_dribbling != null && getTeam(player) != getTeam(target) && target.getEntityId() == _dribbling.getEntityId())
{
if (Recharge.Instance.usable(player, "Steal Ball", true))
{
Recharge.Instance.use(player, "Steal Ball", 1000 * 5, true, false, false);
if (new Random().nextDouble() <= .15)
{
stealBall(player, target);
}
else
{
player.sendMessage(F.main("Game", "Your steal attempt failed!"));
}
}
}
}
@EventHandler
public void onThrow(PlayerInteractEvent event)
{
if (_frozen)
return;
if (_dribbling != null && event.getPlayer().getEntityId() == _dribbling.getEntityId() && Recharge.Instance.usable(_dribbling, "ThrowBall", false))
{
throwBall(event.getPlayer(), event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK);
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (event.getType() == UpdateType.FASTEST)
{
for (Player player : _players)
{
CraftPlayer cp = (CraftPlayer)player;
for (int x = (int)Math.floor(cp.getHandle().getBoundingBox().a + 0.001); x <= (int)Math.floor(cp.getHandle().getBoundingBox().d - 0.001); x++)
{
for (int y = (int)Math.floor(cp.getHandle().getBoundingBox().b + 0.001); y <= (int)Math.floor(cp.getHandle().getBoundingBox().e - 0.001); y++)
{
for (int z = (int)Math.floor(cp.getHandle().getBoundingBox().c + 0.001); z <= (int)Math.floor(cp.getHandle().getBoundingBox().f - 0.001); z++)
{
CraftWorld world = (CraftWorld)_world;
if (net.minecraft.server.v1_8_R3.Block.getId(world.getHandle().getType(new BlockPosition(x, y, z)).getBlock()) == Material.WEB.getId())
{
player.teleport(new Location(player.getWorld(), x, y - 2, z));
}
}
}
}
}
if (_dribbling != null && (!_dribbling.isOnline() || !_players.contains(_dribbling)))
{
if (_dribbling != null)
{
UtilInv.removeAll(_dribbling, Material.SLIME_BALL, (byte)0);
}
_dribbling = null;
spawnNeutralBall();
}
if (_ball != null)
{
if (isOutOfBounds(_ball.getLocation(), true))
{
if (_ball.hasMetadata("Respawn"))
{
if (UtilTime.elapsed(_ball.getMetadata("Respawn").get(0).asLong(), 2000))
{
_ball.removeMetadata("Respawn", _hub.getPlugin());
_ball.setVelocity(UtilAlg.getTrajectory(_ball.getLocation(), DataLoc.CENTER_COURT.getLocation(_world)));
}
}
else
{
_ball.setMetadata("Respawn", new FixedMetadataValue(_hub.getPlugin(), System.currentTimeMillis()));
}
}
else
{
if (_ball.hasMetadata("Respawn"))
{
_ball.removeMetadata("Respawn", _hub.getPlugin());
}
}
}
reboundBall();
if (!checkCatching())
{
checkScoring();
}
dribble();
if (_dribbling != null)
{
if (UtilTime.elapsed(_lastDribbleMove, 15000))
{
throwBall(_dribbling, false);
}
}
}
}
@EventHandler
public void onMove(PlayerMoveEvent event)
{
if (!_players.contains(event.getPlayer()))
{
return;
}
if (UtilMath.offset2d(event.getFrom(), event.getTo()) <= 0)
{
return;
}
if (_frozen)
{
event.setTo(event.getFrom());
return;
}
if (_dribbling != null && event.getPlayer().getEntityId() == _dribbling.getEntityId())
{
_lastDribbleMove = System.currentTimeMillis();
}
}
}

View File

@ -0,0 +1,324 @@
package mineplex.hub.modules.mavericks.basketball;
import java.util.ArrayList;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
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.UtilServer;
import mineplex.core.event.StackerEvent;
import mineplex.core.gadget.event.GadgetEnableEvent;
import mineplex.core.gadget.event.GadgetSelectLocationEvent;
import mineplex.core.gadget.gadgets.outfit.OutfitTeam;
import mineplex.core.gadget.types.Gadget;
import mineplex.core.gadget.types.GadgetType;
import mineplex.core.mount.event.MountActivateEvent;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.hub.HubManager;
import mineplex.hub.modules.mavericks.MavericksWorldManager;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.WitherSkull;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerVelocityEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.collect.Lists;
/**
* Manager class for creating and maintaining basketball games in the hub
*/
public class BasketballManager extends MiniPlugin
{
private HubManager _hubManager;
private MavericksWorldManager _world;
private ArrayList<OutfitTeam> _teamArmor = Lists.newArrayList();
private BasketballGame _game;
public BasketballManager(JavaPlugin plugin, MavericksWorldManager world, HubManager hub)
{
super("Basketball Manager", plugin);
_world = world;
_hubManager = hub;
for (Gadget outfit : hub.GetGadget().getGadgets(GadgetType.COSTUME))
{
if (outfit instanceof OutfitTeam)
{
_teamArmor.add((OutfitTeam)outfit);
}
}
}
@Override
public void disable()
{
if (_game != null)
{
_game.end();
_game = null;
}
}
private void setBasketballMode(Player player, boolean enabled, Color color)
{
if (_game == null)
{
return;
}
if (enabled)
{
_game.getPlayers().add(player);
if (color == null)
UtilPlayer.message(player, F.main("Basketball", "You have entered " + F.elem("Basketball Mode") + "."));
else if (color == Color.RED)
UtilPlayer.message(player, F.main("Basketball", "You have joined " + F.elem(C.cRed + "Red Basketball Team") + "."));
else if (color == Color.AQUA)
UtilPlayer.message(player, F.main("Basketball", "You have joined " + F.elem(C.cAqua + "Blue Basketball Team") + "."));
ArrayList<String> outfit = new ArrayList<String>();
outfit.add("Team Helmet");
outfit.add("Team Shirt");
outfit.add("Team Pants");
outfit.add("Team Boots");
_hubManager.GetGadget().disableAll(player, outfit);
_hubManager.GetMount().DisableAll(player);
_hubManager.getPetManager().disableAll(player);
}
else
{
_game.getPlayers().remove(player);
UtilPlayer.message(player, F.main("Parkour", "You have exited " + F.elem("Basketball Mode") + "."));
}
}
/**
* Fetches the color of a player's team based on their outfit
* @param player The player to check
* @return The color of the player's team, or null if they are not wearing a team outfit
*/
public Color getTeamColor(Player player)
{
//All pieces are always same color!
for (OutfitTeam outfit : _teamArmor)
{
if (outfit.isActive(player))
return outfit.getTeamColor(player);
}
return null;
}
/**
* Checks whether an entity is in the bounds considered the basketball court
* @param entity The entity to check
* @return Whether the entity is in the bounds considered the basketball court
*/
public boolean inPlayerArena(Entity entity)
{
if(!entity.getWorld().equals(_world.getWorld()))
{
return false;
}
Location loc = entity.getLocation();
return (loc.getX() > DataLoc.CORNER_MIN.getLocation(_world.getWorld()).getX() && loc.getX() < DataLoc.CORNER_MAX.getLocation(_world.getWorld()).getX()) && (loc.getZ() > DataLoc.CORNER_MIN.getLocation(_world.getWorld()).getZ() && loc.getZ() < DataLoc.CORNER_MAX.getLocation(_world.getWorld()).getZ());
}
@EventHandler
public void clean(UpdateEvent event)
{
if (event.getType() != UpdateType.FASTER)
return;
for (Entity ent : _world.getWorld().getEntities())
{
if (ent instanceof Player)
continue;
if (_game != null && _game.getBall() != null && _game.getBall().equals(ent))
continue;
if (inPlayerArena(ent))
{
if (ent instanceof Bat || ent instanceof WitherSkull || ent instanceof TNTPrimed || ent instanceof Firework)
{
ent.remove();
continue;
}
Location bounce = UtilAlg.getMidpoint(DataLoc.CORNER_MAX.getLocation(_world.getWorld()), DataLoc.CORNER_MIN.getLocation(_world.getWorld()));
bounce.setY(Math.min(DataLoc.CORNER_MAX.getLocation(_world.getWorld()).getY(), DataLoc.CORNER_MIN.getLocation(_world.getWorld()).getY()));
Entity bottom = ent;
if (bottom.getVehicle() != null)
bottom = bottom.getVehicle();
UtilAction.velocity(bottom, UtilAlg.getTrajectory(bounce, ent.getLocation()), 1, false, 0, 0.4, 1, true);
}
}
if (_game != null && _game.getGameAge() > 5000 && _game.getPlayers().size() < 1)
{
_game.end();
_game = null;
}
}
@EventHandler
public void joinLeaveGame(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (Player player : UtilServer.getPlayers())
{
if (_game != null && _game.getPlayers().contains(player))
{
if (!inPlayerArena(player))
{
setBasketballMode(player, false, null);
continue;
}
//Took armor off
Color color = getTeamColor(player);
if (color == null || (color != Color.RED && color != Color.AQUA))
{
setBasketballMode(player, false, null);
}
}
else
{
if (inPlayerArena(player))
{
Color color = getTeamColor(player);
if (color != null && (color == BasketballTeam.RED.getColor() || color == BasketballTeam.BLUE.getColor()) && _game == null)
{
_game = new BasketballGame(getPlugin(), _hubManager, _world.getWorld());
}
//Join
if (color != null && (color == Color.RED || color == Color.AQUA) && _game != null && _game.getPlayers().size() < 10)
{
setBasketballMode(player, true, color);
}
//Eject
else
{
Location bounce = UtilAlg.getMidpoint(DataLoc.CORNER_MAX.getLocation(_world.getWorld()), DataLoc.CORNER_MIN.getLocation(_world.getWorld()));
bounce.setY(Math.min(DataLoc.CORNER_MAX.getLocation(_world.getWorld()).getY(), DataLoc.CORNER_MIN.getLocation(_world.getWorld()).getY()));
Entity bottom = player;
if (bottom.getVehicle() != null)
bottom = bottom.getVehicle();
UtilAction.velocity(bottom, UtilAlg.getTrajectory2d(bounce, player.getLocation()), 1, false, 0, 0.8, 1, true);
if (Recharge.Instance.use(player, "Basketball Eject", 5000, false, false))
{
if (_game == null || (_game != null && _game.getPlayers().size() < 10))
{
UtilPlayer.message(player, F.main("Slimeball", "You must be wearing Red/Blue Team Outfit."));
UtilPlayer.message(player, F.main("Slimeball", "Type " + F.elem("/team red") + " or " + F.elem("/team blue") + "!"));
}
else
{
UtilPlayer.message(player, F.main("Slimeball", "The game is currently full!"));
}
}
}
}
}
}
}
@EventHandler
public void disableGadgets(GadgetEnableEvent event)
{
if (_game != null && _game.getPlayers().contains(event.getPlayer()))
{
event.setCancelled(true);
}
}
@EventHandler
public void disableMounts(MountActivateEvent event)
{
if (_game != null && _game.getPlayers().contains(event.getPlayer()))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerGrabSlime(PlayerInteractEntityEvent event)
{
if (_game != null && _game.getPlayers().contains(event.getPlayer()))
{
event.setCancelled(true);
}
if (_game != null && _game.getBall() != null && event.getRightClicked().equals(_game.getBall()))
{
event.setCancelled(true);
}
}
@EventHandler
public void disableStacker(StackerEvent event)
{
if (_game != null && _game.getPlayers().contains(event.getEntity()))
{
event.setCancelled(true);
}
}
@EventHandler
public void disableGuardianLazer(GadgetSelectLocationEvent event)
{
if (_game != null && !_game.isOutOfBounds(event.getLocation(), false))
{
event.setCancelled(true);
}
}
@EventHandler
public void disableVelocity(PlayerVelocityEvent event)
{
// Disable velocity but allow double jumping.
if (_game != null && _game.getPlayers().contains(event.getPlayer()) && !_hubManager.getJumpManager().hasDoubleJumped(event.getPlayer()))
{
event.setCancelled(true);
}
}
@EventHandler
public void playerQuit(PlayerQuitEvent event)
{
if (_game != null)
{
_game.getPlayers().remove(event.getPlayer());
}
}
}

View File

@ -0,0 +1,84 @@
package mineplex.hub.modules.mavericks.basketball;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.World;
/**
* Enum containing all teams for hub basketball
*/
public enum BasketballTeam
{
RED(Color.RED, ChatColor.RED, "Red", DataLoc.RED_SPAWNS),
BLUE(Color.AQUA, ChatColor.AQUA, "Blue", DataLoc.BLUE_SPAWNS)
;
private Color _color;
private ChatColor _cColor;
private String _name;
private DataLoc _spawns;
private BasketballTeam(Color color, ChatColor cColor, String name, DataLoc spawns)
{
_color = color;
_cColor = cColor;
_name = name;
_spawns = spawns;
}
/**
* Fetches the color of this team's uniform
* @return The color of this team's uniform
*/
public Color getColor()
{
return _color;
}
/**
* Fetches the color of this team in chat
* @return The color of this team in chat
*/
public ChatColor getChatColor()
{
return _cColor;
}
/**
* Fetches the display name of this team
* @return The display name of this team
*/
public String getName()
{
return _cColor + _name + " Team";
}
/**
* Fetches all possible spawns for this team
* @param world The world to create the locations in
* @return All possible spawns for this team
*/
public Location[] getSpawns(World world)
{
return _spawns.getLocations(world);
}
/**
* Fetches the team matching a color
* @param color The color to match a team to
* @return The team matching the color, or null if one is not found
*/
public static BasketballTeam getFromColor(Color color)
{
for (BasketballTeam team : BasketballTeam.values())
{
if (team.getColor().asRGB() == color.asRGB())
{
return team;
}
}
return null;
}
}

View File

@ -0,0 +1,68 @@
package mineplex.hub.modules.mavericks.basketball;
import org.bukkit.Location;
import org.bukkit.World;
/**
* Enum for easy references to data location keys
*/
public enum DataLoc
{
RED_HOOP(0, 15, 45),
BLUE_HOOP(0, 15, -47),
CENTER_COURT(0, 8, -1),
CORNER_MIN(-24.8, 8, -47.8),
CORNER_MAX(24.8, 8, 45.8),
RED_SCORE_SPAWN(new Double[] {7D, 7D, -7D, -7D}, new Double[] {8D, 8D, 8D, 8D}, new Double[] {43D, 28D, 43D, 28D}),
RED_UNDER_HOOP(0, 8, 43),
BLUE_SCORE_SPAWN(new Double[] {-7D, -7D, 7D, 7D}, new Double[] {8D, 8D, 8D, 8D}, new Double[] {-45D, -30D, -45D, -30D}),
BLUE_UNDER_HOOP(0, 8, -45),
RED_SPAWNS(new Double[] {-8D, -5D, 0D, 5D, 8D}, new Double[] {8D, 8D, 8D, 8D, 8D}, new Double[] {2D, 6D, 8D, 6D, 2D}),
BLUE_SPAWNS(new Double[] {-8D, -5D, 0D, 5D, 8D}, new Double[] {8D, 8D, 8D, 8D, 8D}, new Double[] {-4D, -8D, -10D, -8D, -4D})
;
private Double[] _x, _y, _z;
private DataLoc(Double[] x, Double[] y, Double[] z)
{
_x = x;
_y = y;
_z = z;
}
private DataLoc(double x, double y, double z)
{
this(new Double[] {x}, new Double[] {y}, new Double[] {z});
}
/**
* Fetches the Locations bound to this DataLoc
* @param world The world to input this DataLoc's coordinates into
* @return The Locations for this DataLoc
*/
public Location[] getLocations(World world)
{
Location[] array = new Location[_x.length];
for (int i = 0; i < _x.length; i++)
{
array[i] = new Location(world, _x[i], _y[i], _z[i]);
}
return array;
}
/**
* Fetches the first Location bound to this DataLoc
* @param world The world to input this DataLoc's coordinates into
* @return The first Location for this DataLoc
*/
public Location getLocation(World world)
{
if (getLocations(world).length < 1)
{
return null;
}
return getLocations(world)[0];
}
}

View File

@ -0,0 +1,37 @@
package mineplex.hub.modules.mavericks.basketball;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* Data class to store information about the last throw of a ball
*/
public class ThrowData
{
private BasketballTeam _team;
private Location _location;
public ThrowData(Player thrower, BasketballTeam team)
{
_team = team;
_location = thrower.getEyeLocation();
}
/**
* Request the player who threw the ball
* @return The player who threw the ball
*/
public BasketballTeam getThrower()
{
return _team;
}
/**
* Requests the location where the ball was thrown from
* @return The origin location of the throw
*/
public Location getThrowOrigin()
{
return _location;
}
}

View File

@ -146,6 +146,12 @@ public class ServerManager extends MiniPlugin implements BrawlShopProvider
}
Player player = (Player)event.getEntity();
if(!player.getWorld().getName().equalsIgnoreCase("world"))
{
return;
}
player.teleport(_hubManager.GetSpawn());
runSyncLater(() -> {_quickShop.attemptShopOpen(player);}, 3L);
@ -618,7 +624,7 @@ public class ServerManager extends MiniPlugin implements BrawlShopProvider
}
Region region = getPlugin().getConfig().getBoolean("serverstatus.us") ? Region.US : Region.EU;
try
{
for (ServerGroup serverGroup : mineplex.serverdata.servers.ServerManager.getServerRepository(region).getServerGroups(null))

View File

@ -12,6 +12,7 @@ public enum GameType
Barbarians("A Barbarians Life"),
Bridge("The Bridges"),
Build("Master Builders"),
BuildMavericks("Mavericks Master Builders"),
CastleSiege("Castle Siege"),
ChampionsTDM("Champions TDM", "Champions"),
ChampionsDominate("Champions Domination", "Champions"),

View File

@ -3,7 +3,6 @@ package mineplex.staffServer;
import com.mojang.authlib.GameProfile;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.antihack.AntiHack;
import mineplex.core.chat.Chat;
import mineplex.core.command.CommandCenter;
import mineplex.core.common.Rank;
@ -71,8 +70,7 @@ public class StaffServer extends JavaPlugin
require(PacketHandler.class);
require(DisguiseManager.class);
require(AntiHack.class);
new CustomerSupport(this, clientManager, donationManager, new SalesPackageManager(this, clientManager, donationManager, new InventoryManager(this, clientManager), new StatsManager(this, clientManager)));
//new Password(this, serverStatusManager.getCurrentServerName());
@ -87,7 +85,6 @@ public class StaffServer extends JavaPlugin
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("377bdea3-badc-448d-81c1-65db43b17ea4"), "Strutt20"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("cf1b629c-cc55-4eb4-be9e-3ca86dfc7b9d"), "mannalou"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("04a484d0-93e0-4777-a70c-808046917e3a"), "EstherCS"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("adaa7613-6683-400f-baf8-7272c04b2cb4"), "Timmy48081_"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("231fb752-9556-489b-8428-f47c7598e061"), "Nuclear_Poptart"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("efaf9a17-2304-4f42-8433-421523c308dc"), "B2_mp"));
@ -95,7 +92,7 @@ public class StaffServer extends JavaPlugin
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("6edf17d5-6bb2-4ed9-92e9-bed8e96fff68"), "BlueBeetleHD"));
((CraftServer)getServer()).getHandle().addWhitelist(new GameProfile(UUID.fromString("a47a4d04-9f51-44ba-9d35-8de6053e9289"), "AlexTheCoder"));
((CraftServer)getServer()).getHandle().addOp(new GameProfile(UUID.fromString("cf1b629c-cc55-4eb4-be9e-3ca86dfc7b9d"), "mannalou"));
((CraftServer)getServer()).getHandle().addOp(new GameProfile(UUID.fromString("377bdea3-badc-448d-81c1-65db43b17ea4"), "Strutt20"));
((CraftServer)getServer()).getHandle().addOp(new GameProfile(UUID.fromString("efaf9a17-2304-4f42-8433-421523c308dc"), "B2_mp"));
((CraftServer)getServer()).getHandle().addOp(new GameProfile(UUID.fromString("6edf17d5-6bb2-4ed9-92e9-bed8e96fff68"), "BlueBeetleHD"));

View File

@ -79,13 +79,17 @@ import mineplex.minecraft.game.core.IRelation;
import mineplex.minecraft.game.core.condition.ConditionManager;
import mineplex.minecraft.game.core.damage.DamageManager;
import mineplex.minecraft.game.core.fire.Fire;
import mineplex.serverdata.Region;
import nautilus.game.arcade.addons.SoupAddon;
import nautilus.game.arcade.addons.TeamArmorAddon;
import nautilus.game.arcade.addons.compass.CompassAddon;
import nautilus.game.arcade.booster.GameBoosterManager;
import nautilus.game.arcade.command.CancelNextGameCommand;
import nautilus.game.arcade.command.GameCmdModeCommand;
import nautilus.game.arcade.command.GameCommand;
import nautilus.game.arcade.command.GoToNextGameCommand;
import nautilus.game.arcade.command.KitUnlockCommand;
import nautilus.game.arcade.command.OpenGameMechPrefsCommand;
import nautilus.game.arcade.command.RequiredRankCommand;
import nautilus.game.arcade.command.WriteCommand;
import nautilus.game.arcade.events.GameStateChangeEvent;
@ -113,6 +117,7 @@ import nautilus.game.arcade.managers.GameTournamentManager;
import nautilus.game.arcade.managers.GameWorldManager;
import nautilus.game.arcade.managers.IdleManager;
import nautilus.game.arcade.managers.MiscManager;
import nautilus.game.arcade.managers.NextBestGameManager;
import nautilus.game.arcade.managers.ProgressingKitManager;
import nautilus.game.arcade.managers.ServerUptimeManager;
import nautilus.game.arcade.managers.chat.GameChatManager;
@ -214,6 +219,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
private GameSpectatorManager _spectatorManager;
private ServerUptimeManager _serverUptimeManager;
private ScoreboardManager _scoreboardManager;
private NextBestGameManager _nextBestGameManager;
private IncognitoManager _incognitoManager;
@ -383,7 +389,15 @@ public class ArcadeManager extends MiniPlugin implements IRelation
_gameCommandMode = checkGameCommandMode();
this._scoreboardManager = new ScoreboardManager(_plugin)
Region region = new File("eu.dat").exists() ? Region.EU : Region.US;
_nextBestGameManager = new NextBestGameManager(serverConfig.ServerGroup, region, _partyManager);
addCommand(new GoToNextGameCommand(this));
addCommand(new OpenGameMechPrefsCommand(this));
addCommand(new CancelNextGameCommand(this));
_scoreboardManager = new ScoreboardManager(_plugin)
{
@Override
public void handlePlayerJoin(String playerName)
@ -562,7 +576,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
}
};
new MenuManager(_plugin);
Managers.put(this._scoreboardManager, ScoreboardManager.class);
Managers.put(_scoreboardManager, ScoreboardManager.class);
}
@Override
@ -1008,6 +1022,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
public void SetGame(Game game)
{
_game = game;
_nextBestGameManager.setGame(game);
}
public int GetPlayerMin()
@ -1276,7 +1291,7 @@ public class ArcadeManager extends MiniPlugin implements IRelation
name = name.substring(name.length() - 4, name.length());
if (file.getName().equals(".zip"))
if (!name.equals(".zip"))
continue;
maps.add(file.getName().substring(0, file.getName().length() - 4));
@ -1994,6 +2009,12 @@ public class ArcadeManager extends MiniPlugin implements IRelation
public ScoreboardManager getScoreboardManager()
{
return this._scoreboardManager;
return _scoreboardManager;
}
public NextBestGameManager getNextBestGameManager()
{
return _nextBestGameManager;
}
}

View File

@ -1,7 +1,5 @@
package nautilus.game.arcade;
import org.bukkit.Material;
import mineplex.core.common.MinecraftVersion;
import mineplex.core.common.Pair;
import mineplex.core.game.GameCategory;
@ -9,15 +7,17 @@ import mineplex.core.game.GameDisplay;
import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.games.baconbrawl.BaconBrawl;
import nautilus.game.arcade.game.games.barbarians.Barbarians;
import nautilus.game.arcade.game.games.basketball.Basketball;
import nautilus.game.arcade.game.games.bossbattles.BossBattles;
import nautilus.game.arcade.game.games.bouncyballs.BouncyBalls;
import nautilus.game.arcade.game.games.bridge.Bridge;
import nautilus.game.arcade.game.games.bridge.modes.LuckyBridges;
import nautilus.game.arcade.game.games.bridge.modes.OverpoweredBridge;
import nautilus.game.arcade.game.games.bridge.modes.SpeedBridges ;
import nautilus.game.arcade.game.games.bridge.modes.SpeedBridges;
import nautilus.game.arcade.game.games.build.Build;
import nautilus.game.arcade.game.games.build.modes.DukesOfDecoration;
import nautilus.game.arcade.game.games.build.modes.TeamBuild;
import nautilus.game.arcade.game.games.buildmavericks.BuildMavericks;
import nautilus.game.arcade.game.games.cards.Cards;
import nautilus.game.arcade.game.games.castlesiege.CastleSiege;
import nautilus.game.arcade.game.games.champions.ChampionsCTF;
@ -60,7 +60,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.quiver.modes.BunnyHop ;
import nautilus.game.arcade.game.games.quiver.modes.BunnyHop;
import nautilus.game.arcade.game.games.rings.ElytraRings;
import nautilus.game.arcade.game.games.runner.Runner;
import nautilus.game.arcade.game.games.runner.modes.FasterThanLight;
@ -99,18 +99,21 @@ import nautilus.game.arcade.game.games.typewars.TypeWars;
import nautilus.game.arcade.game.games.uhc.UHC;
import nautilus.game.arcade.game.games.uhc.modes.Assassins;
import nautilus.game.arcade.game.games.uhc.modes.BloodDiamonds;
import nautilus.game.arcade.game.games.uhc.modes.CutClean ;
import nautilus.game.arcade.game.games.uhc.modes.CutClean;
import nautilus.game.arcade.game.games.uhc.modes.GodBattles;
import nautilus.game.arcade.game.games.valentines.Valentines;
import nautilus.game.arcade.game.games.wither.WitherGame;
import nautilus.game.arcade.game.games.wizards.Wizards;
import nautilus.game.arcade.game.games.zombiesurvival.ZombieSurvival;
import org.bukkit.Material;
public enum GameType
{
//Mini
BaconBrawl(BaconBrawl.class, GameDisplay.BaconBrawl),
Barbarians(Barbarians.class, GameDisplay.Barbarians),
Basketball(Basketball.class, GameDisplay.Basketball),
BossBattles(BossBattles.class, GameDisplay.BossBattles),
Bridge(Bridge.class, GameDisplay.Bridge),
CastleSiege(CastleSiege.class, GameDisplay.CastleSiege),
@ -183,6 +186,7 @@ public enum GameType
}, true),
ZombieSurvival(ZombieSurvival.class, GameDisplay.ZombieSurvival),
Build(Build.class, GameDisplay.Build),
BuildMavericks(BuildMavericks.class, GameDisplay.BuildMavericks),
Cards(Cards.class, GameDisplay.Cards),
Skywars(SoloSkywars.class, GameDisplay.Skywars),
SkywarsTeams(TeamSkywars.class, GameDisplay.SkywarsTeams, new GameType[]{GameType.Skywars}, false),

View File

@ -0,0 +1,24 @@
package nautilus.game.arcade.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import nautilus.game.arcade.ArcadeManager;
import org.bukkit.entity.Player;
/**
*
*/
public class CancelNextGameCommand extends CommandBase<ArcadeManager>
{
public CancelNextGameCommand(ArcadeManager plugin)
{
super(plugin, Rank.ALL, "cancelsendingtonextbestgame");
}
@Override
public void Execute(Player caller, String[] args)
{
Plugin.getNextBestGameManager().cancel(caller, Plugin.getPartyManager().getParty(caller));
}
}

View File

@ -0,0 +1,24 @@
package nautilus.game.arcade.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import nautilus.game.arcade.ArcadeManager;
import org.bukkit.entity.Player;
/**
*
*/
public class GoToNextGameCommand extends CommandBase<ArcadeManager>
{
public GoToNextGameCommand(ArcadeManager plugin)
{
super(plugin, Rank.ALL, "gotonextbestgame");
}
@Override
public void Execute(Player caller, String[] args)
{
Plugin.getNextBestGameManager().onCommand(caller);
}
}

View File

@ -0,0 +1,26 @@
package nautilus.game.arcade.command;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.preferences.PreferenceCategory;
import mineplex.core.preferences.ui.menus.PreferenceMenu;
import nautilus.game.arcade.ArcadeManager;
import org.bukkit.entity.Player;
/**
*
*/
public class OpenGameMechPrefsCommand extends CommandBase<ArcadeManager>
{
public OpenGameMechPrefsCommand(ArcadeManager plugin)
{
super(plugin, Rank.ALL, "opengamemechanicpreferences");
}
@Override
public void Execute(Player caller, String[] args)
{
new PreferenceMenu(PreferenceCategory.GAME_PLAY, Plugin.getPreferences()).open(caller);
}
}

View File

@ -0,0 +1,730 @@
package nautilus.game.arcade.game.games.basketball;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilInv;
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.UtilTextBottom;
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.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.games.basketball.data.ScoringManager;
import nautilus.game.arcade.game.games.basketball.data.ThrowData;
import nautilus.game.arcade.game.games.basketball.kit.BasketballPlayerKit;
import nautilus.game.arcade.kit.Kit;
import net.minecraft.server.v1_8_R3.BlockPosition;
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.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.Vector;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
/**
* Main game class for Basketball
*/
public class Basketball extends TeamGame
{
private Entity _ball;
private Player _dribbling;
private ThrowData _throwData;
private static final double THREE_POINTER_DISTANCE = 27;
private boolean _frozen = false;
private long _lastDribbleAnim = 0;
private long _lastDribbleMove = 0;
private HashMap<GameTeam, Block> _hoops = new HashMap<>();
private ScoringManager _score;
private double _maxX = 0;
private double _minX = 0;
private double _maxZ = 0;
private double _minZ = 0;
private double _velocity = -7;
public Basketball(ArcadeManager manager)
{
super(manager, GameType.Basketball, new Kit[] {new BasketballPlayerKit(manager)}, new String[]
{
"Dribble the ball to the other side of the court",
"Shoot into the hoop to score 2 or 3 points",
"Team with most points at the end wins!",
"Left Click to pass or do a layup",
"Right Click to make a distance shot",
"Left Click an opposing player to try and steal the ball"
}
);
this.TeamArmor = true;
this.TeamArmorHotbar = true;
this.HealthSet = 20;
this.HungerSet = 20;
this.Damage = false;
this.CreatureAllow = false;
this.AllowParticles = false;
this.GameTimeout = -1;
_score = new ScoringManager(this);
}
private boolean isOutOfBounds(Location loc, boolean ball)
{
if (ball)
{
if ((loc.getX() - 1) > _maxX || (loc.getX() + 1) < _minX)
{
return true;
}
if ((loc.getZ() - 1) > _maxZ || (loc.getZ() + 1) < _minZ)
{
return true;
}
return false;
}
if (loc.getX() >= _maxX || loc.getX() <= _minX)
{
return true;
}
if (loc.getZ() >= _maxZ || loc.getZ() <= _minZ)
{
return true;
}
return false;
}
private Entity spawnBall(Location loc)
{
this.CreatureAllowOverride = true;
_velocity = -7;
Entity e = Manager.GetCreature().SpawnEntity(loc, EntityType.SLIME);
UtilEnt.Vegetate(e, true);
UtilEnt.ghost(e, true, false);
((Slime)e).setSize(1);
this.CreatureAllowOverride = false;
return e;
}
private void announceDebug(Object debugMessage)
{
for (Player player : Bukkit.getOnlinePlayers())
{
if (player.getItemInHand() != null && player.getItemInHand().getType() == Material.BOOK)
{
player.sendMessage(debugMessage + "");
}
}
}
private void reboundBall()
{
if (_ball == null)
{
return;
}
if (_throwData != null)
{
for (Player player : GetTeam(_throwData.getThrower()).GetPlayers(true))
{
if (UtilMath.offset(_ball, player) <= 2.5)
{
if (Recharge.Instance.usable(player, "Catch Ball", false))
{
catchBall(player);
return;
}
}
}
}
Vector vec = _ball.getVelocity();
announceDebug(vec.toString());
//Rebound Y
if (UtilEnt.isGrounded(_ball))
{
announceDebug("First");
if (vec.getY() < 0)
{
announceDebug("Second");
vec.setY(_ball.getVelocity().getY() * _velocity);
_velocity = Math.max(0, _velocity - .5);
}
}
if (!UtilEnt.isGrounded(_ball))
{
vec.setY(vec.getY() - 0.08);
}
//Rebound X
if ((vec.getX() > 0 && _ball.getLocation().getX() >= _maxX) || (vec.getX() < 0 && _ball.getLocation().getX() <= _minX))
{
vec.setX(vec.getX() * -1);
vec = vec.multiply(0.9);
}
//Rebound Z
if ((vec.getZ() > 0 && _ball.getLocation().getZ() >= _maxZ) || (vec.getZ() < 0 && _ball.getLocation().getZ() <= _minZ))
{
vec.setZ(vec.getZ() * -1);
vec = vec.multiply(0.9);
}
announceDebug(vec);
_ball.setVelocity(vec);
}
private void spawnNeutralBall()
{
Location loc = WorldData.GetCustomLocs(DataLoc.CENTER_COURT.getKey()).get(0);
_ball = spawnBall(loc);
}
private void throwBall(Player origin, boolean right)
{
Entity e = spawnBall(origin.getEyeLocation());
double power = 1.7;
if (right)
{
power = 3.1;
}
e.setVelocity(origin.getEyeLocation().getDirection().normalize().multiply(power));
Recharge.Instance.use(origin, "Catch Ball", 3000, false, false, false);
_ball = e;
if (_dribbling != null)
{
UtilInv.removeAll(_dribbling, Material.SLIME_BALL, (byte)0);
_dribbling = null;
}
_throwData = new ThrowData(origin);
}
private void catchBall(Player player)
{
_lastDribbleMove = System.currentTimeMillis();
_dribbling = player;
for (int i = 0; i < 8; i++)
{
_dribbling.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
_ball.remove();
_ball = null;
_throwData = null;
}
@Override
public void ParseData()
{
Block redHoop = WorldData.GetCustomLocs(DataLoc.RED_HOOP.getKey()).get(0).getBlock();
redHoop.setType(Material.WEB);
Block blueHoop = WorldData.GetCustomLocs(DataLoc.BLUE_HOOP.getKey()).get(0).getBlock();
blueHoop.setType(Material.WEB);
_hoops.put(GetTeam(ChatColor.RED), redHoop);
_hoops.put(GetTeam(ChatColor.AQUA), blueHoop);
_maxX = WorldData.GetCustomLocs(DataLoc.CORNER_MAX.getKey()).get(0).getX();
_minX = WorldData.GetCustomLocs(DataLoc.CORNER_MIN.getKey()).get(0).getX();
_maxZ = WorldData.GetCustomLocs(DataLoc.CORNER_MAX.getKey()).get(0).getZ();
_minZ = WorldData.GetCustomLocs(DataLoc.CORNER_MIN.getKey()).get(0).getZ();
}
@Override
public void ScoreboardUpdate(UpdateEvent event)
{
}
public void stealBall(Player to, Player from)
{
Recharge.Instance.use(to, "ThrowBall", 1500, false, false, false);
_lastDribbleMove = System.currentTimeMillis();
_dribbling = to;
for (int i = 0; i < 8; i++)
{
to.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
UtilInv.removeAll(from, Material.SLIME_BALL, (byte)0);
Bukkit.broadcastMessage(F.main("Game", GetTeam(to).GetColor() + to.getName() + C.cGray + " has stolen the ball from " + GetTeam(from).GetColor() + from.getName() + C.cGray + "!"));
}
private boolean checkCatching()
{
if (_ball != null)
{
for (Player player : GetPlayers(true))
{
if (UtilMath.offset(player, _ball) <= 1.5)
{
if (Recharge.Instance.usable(player, "Catch Ball", false))
{
catchBall(player);
return true;
}
}
}
}
return false;
}
private void score(GameTeam team, Location hoop)
{
UtilTextMiddle.display("", team.GetColor() + team.getDisplayName() + " has scored!", 0, 20 * 2, 0);
int points = getWorth(_throwData.getThrowOrigin(), hoop);
if(_throwData.getThrower() != null)
{
String player = team.GetColor() + _throwData.getThrower().getName() + C.mBody + "";
String broad = player + " has scored a " + F.elem(points + " pointer!");
Location location = _throwData.getThrower().getLocation();
double dist = UtilMath.offset2d(_throwData.getThrowOrigin(), hoop);
if(dist <= 3)
{
broad = player + C.cGreen + " scored a layup!";
if(hoop.getY() < location.getY())
{
broad = player + C.cGreenB + " dunked on em!";
}
}
UtilServer.broadcast(broad);
}
_score.addPoint(team, points);
_ball.remove();
_ball = null;
_throwData = null;
GameTeam other = getOtherTeam(team);
List<Player> teamP = other.GetPlayers(true);
//Select player to get ball
Player carrier = teamP.get(new Random().nextInt(teamP.size()));
for (int i = 0; i < teamP.size(); i++)
{
Player player = teamP.get(i);
if (carrier.getEntityId() != player.getEntityId())
{
String key = DataLoc.BLUE_SCORE_SPAWN.getKey();
if (other.GetColor() == ChatColor.RED)
key = DataLoc.RED_SCORE_SPAWN.getKey();
player.teleport(WorldData.GetCustomLocs(key).get(i % WorldData.GetCustomLocs(key).size()));
player.playSound(player.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f);
}
}
for (Player player : team.GetPlayers(true))
{
player.teleport(team.GetSpawn());
player.playSound(player.getLocation(), Sound.LEVEL_UP, 1.0f, 1.0f);
}
Location teleport = WorldData.GetCustomLocs(DataLoc.BLUE_UNDER_HOOP.getKey()).get(0);
if (other.GetColor() == ChatColor.RED)
teleport = WorldData.GetCustomLocs(DataLoc.RED_UNDER_HOOP.getKey()).get(0);
teleport.setPitch(UtilAlg.GetPitch(UtilAlg.getTrajectory(teleport, WorldData.GetCustomLocs(DataLoc.CENTER_COURT.getKey()).get(0))));
teleport.setYaw(UtilAlg.GetYaw(UtilAlg.getTrajectory(teleport, WorldData.GetCustomLocs(DataLoc.CENTER_COURT.getKey()).get(0))));
carrier.teleport(teleport);
_lastDribbleMove = System.currentTimeMillis();
_dribbling = carrier;
for (int i = 0; i < 8; i++)
{
_dribbling.getInventory().setItem(i, new ItemBuilder(Material.SLIME_BALL).setTitle(C.cGold + "Basketball").build());
}
}
private void checkScoring()
{
if (_ball == null)
{
return;
}
for (GameTeam team : _hoops.keySet())
{
Location check = _hoops.get(team).getLocation().add(.5, 0, .5);
if (UtilMath.offset(check, _ball.getLocation()) <= .9)
{
score(getOtherTeam(team), check);
return;
}
}
}
private void dribble()
{
if (_dribbling == null)
{
_lastDribbleAnim = System.currentTimeMillis();
return;
}
UtilTextBottom.display(C.cRed + "You have the ball!", _dribbling);
UtilParticle.PlayParticleToAll(ParticleType.HAPPY_VILLAGER, _dribbling.getEyeLocation(), new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat(), 0, 1, ViewDist.MAX);
if (System.currentTimeMillis() - _lastDribbleAnim > 333)
{
_lastDribbleAnim = System.currentTimeMillis();
Item item = _dribbling.getWorld().dropItem(_dribbling.getLocation(), new ItemStack(Material.SLIME_BALL));
item.setPickupDelay(Integer.MAX_VALUE);
Bukkit.getScheduler().runTaskLater(Manager.getPlugin(), () -> {
item.remove();
}, 7);
}
}
private int getWorth(Location start, Location hoop)
{
if (UtilMath.offset2d(start, hoop) >= THREE_POINTER_DISTANCE)
{
return 3;
}
return 2;
}
private boolean endCheck()
{
//Check scores
for (int scoreId = 0; scoreId <= 1; scoreId++)
{
int score = _score.getScores()[scoreId];
if (score >= 50)
{
GameTeam team = null;
if (scoreId == 0)
{
team = GetTeam(ChatColor.RED);
}
else if (scoreId == 1)
{
team = GetTeam(ChatColor.AQUA);
}
end(team);
return true;
}
}
//Check time
if ((GetStateTime() + UtilTime.convert(10, TimeUnit.MINUTES, TimeUnit.MILLISECONDS)) - System.currentTimeMillis() <= 0)
{
int red = _score.getScores()[0];
int blue = _score.getScores()[1];
if (red > blue)
{
end(GetTeam(ChatColor.RED));
return true;
}
else if (blue > red)
{
end(GetTeam(ChatColor.AQUA));
return true;
}
}
return false;
}
private void end(GameTeam winner)
{
AnnounceEnd(winner);
for (GameTeam team : GetTeamList())
{
if (winner != null && team.equals(winner))
{
for (Player player : team.GetPlayers(false))
{
AddGems(player, 10, "Winning Team", false, false);
}
}
for (Player player : team.GetPlayers(false))
{
if (player.isOnline())
{
AddGems(player, 10, "Participation", false, false);
}
}
}
_score.displayScores(Scoreboard, true, winner.GetColor() + winner.GetName());
SetState(GameState.End);
}
/**
* Quickly searches for the opposite team of the one given
* @param team The team to check
* @return The opposite team
*/
public GameTeam getOtherTeam(GameTeam team)
{
if (team.GetColor() == ChatColor.RED)
{
return GetTeam(ChatColor.AQUA);
}
if (team.GetColor() == ChatColor.AQUA)
{
return GetTeam(ChatColor.RED);
}
return null;
}
@EventHandler
public void onSwipe(EntityDamageByEntityEvent event)
{
if (!IsLive())
return;
if (_frozen)
return;
if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof Player))
{
return;
}
if (!IsPlaying((Player)event.getEntity()) || !IsPlaying((Player)event.getDamager()))
{
return;
}
Player player = (Player)event.getDamager();
Player target = (Player)event.getEntity();
if (_dribbling != null && GetTeam(player).GetColor() != GetTeam(target).GetColor() && target.getEntityId() == _dribbling.getEntityId())
{
if (Recharge.Instance.usable(player, "Steal Ball", true))
{
Recharge.Instance.use(player, "Steal Ball", 1000 * 5, true, false, false);
if (new Random().nextDouble() <= .20)
{
stealBall(player, target);
}
else
{
player.sendMessage(F.main("Game", "Your steal attempt failed!"));
}
}
}
}
@EventHandler
public void onThrow(PlayerInteractEvent event)
{
if (!IsLive())
return;
if (_frozen)
return;
if (_dribbling != null && event.getPlayer().getEntityId() == _dribbling.getEntityId() && Recharge.Instance.usable(_dribbling, "ThrowBall", false))
{
throwBall(event.getPlayer(), event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK);
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (!IsLive())
return;
if (event.getType() == UpdateType.FASTEST)
{
if (endCheck())
{
return;
}
for (Player player : GetPlayers(true))
{
CraftPlayer cp = (CraftPlayer)player;
for (int x = (int)Math.floor(cp.getHandle().getBoundingBox().a + 0.001); x <= (int)Math.floor(cp.getHandle().getBoundingBox().d - 0.001); x++)
{
for (int y = (int)Math.floor(cp.getHandle().getBoundingBox().b + 0.001); y <= (int)Math.floor(cp.getHandle().getBoundingBox().e - 0.001); y++)
{
for (int z = (int)Math.floor(cp.getHandle().getBoundingBox().c + 0.001); z <= (int)Math.floor(cp.getHandle().getBoundingBox().f - 0.001); z++)
{
CraftWorld world = (CraftWorld)WorldData.World;
if (net.minecraft.server.v1_8_R3.Block.getId(world.getHandle().getType(new BlockPosition(x, y, z)).getBlock()) == Material.WEB.getId())
{
player.teleport(new Location(player.getWorld(), x, y - 2, z));
}
}
}
}
}
if (_dribbling != null && !_dribbling.isOnline())
{
_dribbling = null;
spawnNeutralBall();
}
if (_ball != null)
{
if (isOutOfBounds(_ball.getLocation(), true))
{
if (_ball.hasMetadata("Respawn"))
{
if (UtilTime.elapsed(_ball.getMetadata("Respawn").get(0).asLong(), 2000))
{
_ball.removeMetadata("Respawn", Manager.getPlugin());
_ball.setVelocity(UtilAlg.getTrajectory(_ball.getLocation(), WorldData.GetCustomLocs(DataLoc.CENTER_COURT.getKey()).get(0)));
}
}
else
{
_ball.setMetadata("Respawn", new FixedMetadataValue(Manager.getPlugin(), System.currentTimeMillis()));
}
}
else
{
if (_ball.hasMetadata("Respawn"))
{
_ball.removeMetadata("Respawn", Manager.getPlugin());
}
}
}
reboundBall();
if (!checkCatching())
{
checkScoring();
}
dribble();
if (_dribbling != null)
{
if (UtilTime.elapsed(_lastDribbleMove, 15000))
{
throwBall(_dribbling, false);
}
}
}
if (event.getType() == UpdateType.FASTER)
{
_score.displayScores(Scoreboard, false, "");
}
}
@EventHandler
public void onMove(PlayerMoveEvent event)
{
if (!IsLive())
return;
if (!IsPlaying(event.getPlayer()))
{
return;
}
if (UtilMath.offset2d(event.getFrom(), event.getTo()) <= 0)
{
return;
}
if (_frozen)
{
event.setTo(event.getFrom());
return;
}
if (isOutOfBounds(event.getTo(), false))
{
event.getPlayer().teleport(event.getFrom());
Vector bounce = UtilAlg.getTrajectory(event.getTo(), WorldData.GetCustomLocs(DataLoc.CENTER_COURT.getKey()).get(0));
event.getPlayer().setVelocity(bounce.normalize());
event.getPlayer().sendMessage(F.main("Game", "You aren't allowed to go out of bounds!"));
}
if (_dribbling != null && event.getPlayer().getEntityId() == _dribbling.getEntityId())
{
_lastDribbleMove = System.currentTimeMillis();
}
}
@EventHandler
public void onStart(GameStateChangeEvent event)
{
if (event.GetGame().equals(this) && event.GetState() == GameState.Live)
{
spawnNeutralBall();
_ball.setVelocity(_ball.getVelocity().add(new Vector(0, 1.5, 0)));
/*_frozen = true;
Bukkit.getScheduler().runTaskLater(Manager.getPlugin(), () ->
{
_frozen = false;
spawnNeutralBall();
}, 20 * 3);*/
}
}
@EventHandler
public void onDebug(PlayerCommandPreprocessEvent event)
{
if (event.getMessage().toLowerCase().contains("/setvelocity ") && event.getPlayer().isOp())
{
event.setCancelled(true);
_velocity = Double.parseDouble(event.getMessage().replace("/setvelocity ", "")) * -1;
}
}
}

View File

@ -0,0 +1,34 @@
package nautilus.game.arcade.game.games.basketball;
/**
* Enum for easy references to data location keys
*/
public enum DataLoc
{
RED_HOOP("RED_HOOP"),
BLUE_HOOP("BLUE_HOOP"),
CENTER_COURT("CENTER_COURT"),
CORNER_MIN("CORNER_MIN"),
CORNER_MAX("CORNER_MAX"),
RED_SCORE_SPAWN("RED_SCORE_SP"),
RED_UNDER_HOOP("RED_UNDER"),
BLUE_SCORE_SPAWN("BLUE_SCORE_SP"),
BLUE_UNDER_HOOP("BLUE_UNDER")
;
private String _key;
private DataLoc(String key)
{
_key = key.toString();
}
/**
* Fetches the Data Location key
* @return The Data Key for the point
*/
public String getKey()
{
return _key;
}
}

View File

@ -0,0 +1,100 @@
package nautilus.game.arcade.game.games.basketball.data;
import org.bukkit.ChatColor;
import mineplex.core.common.util.C;
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.basketball.Basketball;
import nautilus.game.arcade.scoreboard.GameScoreboard;
/**
* Manager to store gameplay scores and dynamically display them wherever needed
*/
public class ScoringManager
{
private Basketball _host;
private int _redScore = 0;
private int _blueScore = 0;
public ScoringManager(Basketball host)
{
_host = host;
}
/**
* Getter for the current scores of both teams
* @return The scores of each team, with the order of red then blue
*/
public Integer[] getScores()
{
return new Integer[] {_redScore, _blueScore};
}
/**
* Displays the scores and time remaining on the Game Scoreboard
* @param sb The GameScoreboard of the currently running Basketball game
*/
public void displayScores(GameScoreboard sb, boolean end, String winTeam)
{
sb.reset();
sb.write(C.cRedB + "Red Score");
sb.write(C.cWhite + getScores()[0]);
sb.writeNewLine();
sb.write(C.cAquaB + "Blue Score");
sb.write(C.cWhite + getScores()[1]);
sb.writeNewLine();
if (end)
{
sb.write(C.cWhiteB + "FINAL SCORE");
sb.writeNewLine();
sb.write(winTeam + " Wins!");
}
else
{
sb.write(C.cYellowB + "Time Remaining");
long timeLeft = (_host.GetStateTime() + UtilTime.convert(10, TimeUnit.MINUTES, TimeUnit.MILLISECONDS)) - System.currentTimeMillis();
if (!_host.IsLive() && !_host.InProgress())
{
timeLeft = 0;
}
else if (!_host.IsLive() && _host.InProgress())
{
timeLeft = UtilTime.convert(10, TimeUnit.MINUTES, TimeUnit.SECONDS);
}
if (timeLeft < 0)
{
sb.write(C.cYellow + "Overtime");
}
else
{
sb.write(UtilTime.MakeStr(timeLeft));
}
}
sb.draw();
}
/**
* Adds points to a team
* @param team The team to add points to
* @param points The amount of points to add
*/
public void addPoint(GameTeam team, int points)
{
if (team.GetColor() == ChatColor.RED)
{
_redScore += points;
}
if (team.GetColor() == ChatColor.AQUA)
{
_blueScore += points;
}
}
}

View File

@ -0,0 +1,37 @@
package nautilus.game.arcade.game.games.basketball.data;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* Data class to store information about the last throw of a ball
*/
public class ThrowData
{
private Player _player;
private Location _location;
public ThrowData(Player thrower)
{
_player = thrower;
_location = thrower.getEyeLocation();
}
/**
* Request the player who threw the ball
* @return The player who threw the ball
*/
public Player getThrower()
{
return _player;
}
/**
* Requests the location where the ball was thrown from
* @return The origin location of the throw
*/
public Location getThrowOrigin()
{
return _location;
}
}

View File

@ -0,0 +1,45 @@
package nautilus.game.arcade.game.games.basketball.kit;
import mineplex.core.common.util.C;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.kit.KitAvailability;
import nautilus.game.arcade.kit.Perk;
import nautilus.game.arcade.kit.ProgressingKit;
import nautilus.game.arcade.kit.perks.PerkDoubleJump;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Kit for Basketball Game
*/
public class BasketballPlayerKit extends ProgressingKit
{
private static final String[] DESCRIPTION =
{
"A true Basketball Champion!",
"Left Click to pass or do a layup",
"Right Click to make a distance shot",
"Left Click an opposing player to try and steal the ball"
};
private static final Perk[] PERKS =
{
new PerkDoubleJump("Hops", new String[] {C.cYellow + "Tap Jump Twice" + C.cGray + " to use " + C.cGreen + "Hops"}, 1.2, 1.2, true, 8000, true)
};
private static final ItemStack IN_HAND = new ItemStack(Material.SLIME_BALL);
public BasketballPlayerKit(ArcadeManager manager)
{
super(manager, "Basketball Player", "bballer", KitAvailability.Free, DESCRIPTION, PERKS, EntityType.ZOMBIE, IN_HAND);
}
@Override
public void GiveItems(Player player)
{
}
}

View File

@ -3,7 +3,9 @@ package nautilus.game.arcade.game.games.build;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
@ -72,7 +74,6 @@ import org.bukkit.inventory.ItemStack;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilAction;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEvent;
@ -98,7 +99,7 @@ import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.GameType;
import nautilus.game.arcade.events.GameStateChangeEvent;
import nautilus.game.arcade.events.PlayerPrepareTeleportEvent;
import nautilus.game.arcade.game.Game ;
import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.GameTeam;
import nautilus.game.arcade.game.games.build.gui.MobShop;
import nautilus.game.arcade.game.games.build.gui.OptionsShop;
@ -110,30 +111,32 @@ import nautilus.game.arcade.stats.BlockPlaceStatTracker;
public class Build extends Game
{
private NautHashMap<Player, BuildData> _data = new NautHashMap<Player, BuildData>();
protected Map<Player, BuildData> _data = new HashMap<>();
private NautHashMap<Player, NautHashMap<Player, Integer>> _votes = new NautHashMap<Player, NautHashMap<Player, Integer>>();
protected Map<Player, Map<Player, Integer>> _votes = new HashMap<>();
private ArrayList<Entry<Player,Double>> _scoreboardPlaces = new ArrayList<Entry<Player,Double>>();
protected ArrayList<Entry<Player,Double>> _scoreboardPlaces = new ArrayList<Entry<Player,Double>>();
private int _buildGameState = 0;
private long _buildStateTime = 0;
private long _buildTime = 300000;
private long _voteTime = 14000;
private long _viewTime = 18000;
protected int _buildGameState = 0;
protected long _buildStateTime = 0;
protected long _buildTime = 300000;
protected long _voteTime = 14000;
protected long _viewTime = 18000;
private BuildData _viewData = null;
private int _countdownTimerState = 0;
private String[] _words;
private String[] _holidayWords;
private boolean _useHolidayWords = false;
protected String[] _words;
protected String[] _holidayWords;
protected boolean _useHolidayWords = false;
private String _word = "?";
protected String _word = "?";
protected boolean _notifyFailure = true;
private OptionsShop _optionsShop;
private MobShop _mobShop;
private ItemStack _shopItem;
protected OptionsShop _optionsShop;
protected MobShop _mobShop;
protected ItemStack _shopItem;
private String[] _hintText = new String[]
{
@ -150,26 +153,16 @@ public class Build extends Game
private ChatColor _hintColor = ChatColor.YELLOW;
private ChatColor _firstHintColor = ChatColor.YELLOW;
private UUID _winnerUUID = null;
protected UUID _winnerUUID = null;
public Build(ArcadeManager manager)
{
this(manager, GameType.Build);
registerStatTrackers(
new BlockBreakStatTracker(this, false),
new BlockPlaceStatTracker(this, new Material[]{})
);
registerChatStats(
new ChatStatData("BlocksPlaced", "Blocks Placed", true),
new ChatStatData("BlocksBroken", "Blocks Broken", true)
);
}
public Build(ArcadeManager manager, GameType type)
protected Build(ArcadeManager manager, GameType gameType)
{
super(manager, type,
super(manager, gameType,
new Kit[]
{
@ -181,6 +174,16 @@ public class Build extends Game
"Be creative and build something",
"based on the build theme!"
});
registerStatTrackers(
new BlockBreakStatTracker(this, false),
new BlockPlaceStatTracker(this, new Material[]{})
);
registerChatStats(
new ChatStatData("BlocksPlaced", "Blocks Placed", true),
new ChatStatData("BlocksBroken", "Blocks Broken", true)
);
this.StrictAntiHack = true;
this.Damage = false;
@ -279,7 +282,7 @@ public class Build extends Game
{
Location spawn = UtilAlg.findClosest(player.getLocation(), this.GetTeamList().get(0).GetSpawns());
_data.put(player, new BuildData(player, spawn, WorldData.GetDataLocs("YELLOW")));
addBuildData(player, spawn);
player.setFlySpeed(0.1f);
}
@ -294,6 +297,11 @@ public class Build extends Game
this.WorldTimeSet = -1;
}
}
protected void addBuildData(Player player, Location spawn)
{
_data.put(player, new BuildData(player, spawn, WorldData.GetDataLocs("YELLOW")));
}
@EventHandler
public void stateChange(UpdateEvent event)
@ -413,7 +421,7 @@ public class Build extends Game
for (Player player : _votes.keySet())
{
NautHashMap<Player, Integer> votes = _votes.get(player);
Map<Player, Integer> votes = _votes.get(player);
if (votes.containsKey(_viewData.Player))
{
@ -433,7 +441,7 @@ public class Build extends Game
result = C.cWhite + "Inappropriate Build";
abusiveBulid();
}
else if (!hasDecentVote)
else if (!hasDecentVote && _notifyFailure)
{
for(Entity entity : _viewData.Entities)
{
@ -614,7 +622,7 @@ public class Build extends Game
getArcadeManager().GetPortal().sendPlayerToServer(_viewData.Player, "Lobby");
}
private void tallyScores()
protected void tallyScores()
{
//Reset, if being re-called
for (BuildData data : _data.values())
@ -632,7 +640,7 @@ public class Build extends Game
double votesCast = 0;
double voteTotal = 0;
NautHashMap<Player, Integer> votes = _votes.get(voter);
Map<Player, Integer> votes = _votes.get(voter);
for (int vote : votes.values())
{
@ -772,7 +780,7 @@ public class Build extends Game
if (data == null)
return;
if (event.getTo().getY() > Math.max(data.CornerA.getBlockY(), data.CornerB.getBlockY()) + 3 &&
if (event.getTo().getY() > data.getMaxHeight() + 3 &&
UtilMath.offset(data.Spawn, event.getFrom()) < UtilMath.offset(data.Spawn, event.getTo()))
{
//Inform
@ -845,7 +853,7 @@ public class Build extends Game
return;
if (!_votes.containsKey(event.getPlayer()))
_votes.put(event.getPlayer(), new NautHashMap<Player, Integer>());
_votes.put(event.getPlayer(), new HashMap<Player, Integer>());
switch (event.getPlayer().getItemInHand().getData().getData())
{
@ -891,7 +899,7 @@ public class Build extends Game
{
_data.remove(event.getPlayer());
for (NautHashMap<Player, Integer> votedFor : _votes.values())
for (Map<Player, Integer> votedFor : _votes.values())
votedFor.remove(event.getPlayer());
_votes.remove(event.getPlayer());
@ -1339,7 +1347,6 @@ public class Build extends Game
Scoreboard.write(C.cYellow + C.Bold + "Build Theme");
Scoreboard.write(_word);
Scoreboard.writeNewLine();
if (_buildGameState == 0)
@ -1647,7 +1654,7 @@ public class Build extends Game
return Arrays.asList(player);
}
public NautHashMap<Player, BuildData> getData()
public Map<Player, BuildData> getData()
{
return _data;
}

View File

@ -1,8 +1,11 @@
package nautilus.game.arcade.game.games.build;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Location;
import org.bukkit.Material;
@ -15,7 +18,16 @@ import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.DoubleTag;
import com.java.sk89q.jnbt.NBTUtils;
import com.java.sk89q.jnbt.StringTag;
import com.java.sk89q.jnbt.Tag;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.block.schematic.UtilSchematic;
import mineplex.core.common.util.F;
import mineplex.core.common.util.MapUtil;
import mineplex.core.common.util.NautHashMap;
@ -63,13 +75,18 @@ public class BuildData
public WeatherType Weather = WeatherType.SUNNY;
private double _totalPoints = 0;
private double _totalPoints = 0;
public BuildData(Player player, Location spawn, ArrayList<Location> buildBorders)
protected BuildData(Player player, Location spawn)
{
Player = player;
Team = null;
Spawn = spawn;
}
public BuildData(Player player, Location spawn, ArrayList<Location> buildBorders)
{
this(player, spawn);
CornerA = UtilAlg.findClosest(spawn, buildBorders);
buildBorders.remove(CornerA);
@ -200,25 +217,32 @@ public class BuildData
{
Blocks.add(block);
}
public boolean inBuildArea(Block block)
public boolean inBuildArea(Block block)
{
if (block.getX() < Math.min(CornerA.getBlockX(), CornerB.getBlockX()))
if(!block.getWorld().getName().equals(Spawn.getWorld().getName())) return false;
return inBuildArea(block.getLocation().add(0.5, 0, 0.5).toVector());
}
public boolean inBuildArea(Vector vec)
{
if (vec.getX() < Math.min(CornerA.getBlockX(), CornerB.getBlockX()))
return false;
if (block.getY() < Math.min(CornerA.getBlockY(), CornerB.getBlockY()))
if (vec.getY() < Math.min(CornerA.getBlockY(), CornerB.getBlockY()))
return false;
if (block.getZ() < Math.min(CornerA.getBlockZ(), CornerB.getBlockZ()))
if (vec.getZ() < Math.min(CornerA.getBlockZ(), CornerB.getBlockZ()))
return false;
if (block.getX() > Math.max(CornerA.getBlockX(), CornerB.getBlockX()))
if (vec.getX() > Math.max(CornerA.getBlockX(), CornerB.getBlockX()))
return false;
if (block.getY() > Math.max(CornerA.getBlockY(), CornerB.getBlockY()))
if (vec.getY() > Math.max(CornerA.getBlockY(), CornerB.getBlockY()))
return false;
if (block.getZ() > Math.max(CornerA.getBlockZ(), CornerB.getBlockZ()))
if (vec.getZ() > Math.max(CornerA.getBlockZ(), CornerB.getBlockZ()))
return false;
return true;
@ -300,13 +324,13 @@ public class BuildData
}
}
public void playWeather(boolean b)
public void playWeather(boolean all)
{
org.bukkit.WeatherType type = org.bukkit.WeatherType.CLEAR;
if (Weather == WeatherType.STORMING || Weather == WeatherType.RAINING)
type = org.bukkit.WeatherType.DOWNFALL;
if (b)
if (all)
{
for (Player player : UtilServer.getPlayers())
{
@ -378,20 +402,31 @@ public class BuildData
}
}
int x = Math.min(CornerA.getBlockX(), CornerB.getBlockX());
int y = Math.min(CornerA.getBlockY(), CornerB.getBlockY()) - 1;
for (int x= Math.min(CornerA.getBlockX(), CornerB.getBlockX()) ; x <= Math.max(CornerA.getBlockX(), CornerB.getBlockX()) ; x++)
for (int z= Math.min(CornerA.getBlockZ(), CornerB.getBlockZ()) ; z <= Math.max(CornerA.getBlockZ(), CornerB.getBlockZ()) ; z++)
int z = Math.min(CornerA.getBlockZ(), CornerB.getBlockZ());
if(ground.hasSchematic())
{
ground.getSchematic().paste(new Location(CornerA.getWorld(), x, y, z), true);
return;
}
for (; x <= Math.max(CornerA.getBlockX(), CornerB.getBlockX()) ; x++)
{
for (; z <= Math.max(CornerA.getBlockZ(), CornerB.getBlockZ()) ; z++)
{
MapUtil.QuickChangeBlockAt(player.getWorld(), x, y, z, mat, data);
}
}
}
public void addPoints(double d)
public void addPoints(double points)
{
if (IsAbusive)
return;
_totalPoints += d;
_totalPoints += points;
}
public double getPoints()
@ -413,4 +448,75 @@ public class BuildData
{
IsAbusive = true;
}
protected Location getMin()
{
return Vector.getMinimum(CornerA.toVector(), CornerB.toVector()).toBlockVector().toLocation(CornerA.getWorld()).subtract(0, 1, 0);
}
protected Location getMax()
{
return Vector.getMaximum(CornerA.toVector(), CornerB.toVector()).toBlockVector().toLocation(CornerA.getWorld());
}
public double getMaxHeight()
{
return Math.max(CornerA.getY(), CornerB.getY());
}
/**
* Converts all the blocks inside the build to a schematic
* @return
*/
public Schematic convertToSchematic()
{
Location min = getMin();
Location max = getMax();
return UtilSchematic.createSchematic(min, max);
}
/**
* @return Returns a map of the particles with their relative vector paths to the build.
*/
public Map<Vector, ParticleType> getParticles()
{
Vector min = getMin().toVector();
Map<Vector, ParticleType> map = new HashMap<>();
for(Entry<Location, ParticleType> e : Particles.entrySet())
{
Vector v = e.getKey().toVector().subtract(min);
map.put(v, e.getValue());
}
return map;
}
/**
* @return Returns the byte map from {@link #getParticles()} in byte form converted to NBT data and compressed with Gzip
*/
public byte[] getParticlesBytes()
{
Map<String, Tag> map = new HashMap<String, Tag>();
int i = 0;
for(Entry<Vector, ParticleType> e : getParticles().entrySet())
{
Map<String, Tag> entryMap = new HashMap<>();
entryMap.put("x", new DoubleTag(e.getKey().getX()));
entryMap.put("y", new DoubleTag(e.getKey().getY()));
entryMap.put("z", new DoubleTag(e.getKey().getZ()));
entryMap.put("particle", new StringTag(e.getValue().name()));
CompoundTag entry = new CompoundTag(entryMap);
map.put("particle" + i++, entry);
}
CompoundTag parent = new CompoundTag(map);
return NBTUtils.toBytesCompressed("particles", parent);
}
}

View File

@ -2,10 +2,14 @@ package nautilus.game.arcade.game.games.build;
import org.bukkit.Material;
import mineplex.core.common.block.schematic.Schematic;
public class GroundData
{
public final Material _material;
public final byte _data;
private final Material _material;
private final byte _data;
private final String _name;
private final Schematic _schematic;
public GroundData(Material material)
{
@ -13,18 +17,50 @@ public class GroundData
}
public GroundData(Material material, byte data)
{
this(material, data, null);
}
public GroundData(Material material, byte data, String name)
{
this(material, data, name, null);
}
public GroundData(Material material, byte data, String name, Schematic schematic)
{
_material = material;
_data = data;
}
public byte getData()
{
return _data;
_name = name;
_schematic = schematic;
}
public Material getMaterial()
{
return _material;
}
public byte getData()
{
return _data;
}
public String getName()
{
return _name;
}
public boolean hasName()
{
return _name != null;
}
public Schematic getSchematic()
{
return _schematic;
}
public boolean hasSchematic()
{
return _schematic != null;
}
}

View File

@ -1,30 +1,32 @@
package nautilus.game.arcade.game.games.build.gui.page;
import java.util.Arrays;
import org.bukkit.ChatColor;
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.block.schematic.UtilSchematic;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilParticle;
import mineplex.core.donation.DonationManager;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.shop.item.IButton;
import mineplex.core.shop.item.ShopItem;
import mineplex.core.shop.page.ShopPageBase;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.GameType;
import nautilus.game.arcade.game.games.build.Build;
import nautilus.game.arcade.game.games.build.BuildData;
import nautilus.game.arcade.game.games.build.GroundData;
import nautilus.game.arcade.game.games.build.gui.OptionsShop;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GroundPage extends ShopPageBase<ArcadeManager, OptionsShop>
{
private static GroundData[] GROUNDS = {
private List<GroundData> _grounds = new ArrayList<>(Arrays.asList(new GroundData[]{
new GroundData(Material.STONE), new GroundData(Material.GRASS), new GroundData(Material.DIRT),
new GroundData(Material.SAND), new GroundData(Material.WATER_BUCKET), new GroundData(Material.LAVA_BUCKET),
new GroundData(Material.WOOD), new GroundData(Material.COBBLESTONE), new GroundData(Material.NETHERRACK),
@ -33,7 +35,7 @@ public class GroundPage extends ShopPageBase<ArcadeManager, OptionsShop>
new GroundData(Material.STAINED_CLAY, (byte) 4), new GroundData(Material.STAINED_CLAY, (byte) 3),
new GroundData(Material.STAINED_CLAY, (byte) 5), new GroundData(Material.STAINED_CLAY, (byte) 6),
new GroundData(Material.QUARTZ_BLOCK), new GroundData(Material.PACKED_ICE), new GroundData(Material.IRON_BLOCK),
new GroundData(Material.GOLD_BLOCK), new GroundData(Material.DIAMOND_BLOCK)};
new GroundData(Material.GOLD_BLOCK), new GroundData(Material.DIAMOND_BLOCK)}));
private Build _game;
@ -41,6 +43,22 @@ public class GroundPage extends ShopPageBase<ArcadeManager, OptionsShop>
{
super(plugin, shop, clientManager, donationManager, "Change Ground", player, 9 * 4);
_game = game;
File schematicDirectory = new File(".." + File.separatorChar + ".." + File.separatorChar + "update" + File.separatorChar + "schematic");
if(_game.GetType() == GameType.BuildMavericks)
{
try
{
GroundData basketFloor = new GroundData(Material.SLIME_BALL, (byte) 0, "Basketball Floor", UtilSchematic.loadSchematic(new File(schematicDirectory, "basketball_floor.schematic")));
_grounds.add(basketFloor);
}
catch (IOException e)
{
e.printStackTrace();
}
}
buildPage();
}
@ -56,9 +74,13 @@ public class GroundPage extends ShopPageBase<ArcadeManager, OptionsShop>
}
int index = 0;
for (final GroundData data : GROUNDS)
for (final GroundData data : _grounds)
{
ShopItem shopItem = new ShopItem(data.getMaterial(), data.getData(), ItemStackFactory.Instance.GetName(data.getMaterial(), data.getData(), true), null, 0, false, false);
String name = data.getName();
if(name == null) name = ItemStackFactory.Instance.GetName(data.getMaterial(), data.getData(), true);
ShopItem shopItem = new ShopItem(data.getMaterial(), data.getData(), name, null, 0, false, false);
addButton(index, shopItem, new IButton()
{
@Override

View File

@ -65,7 +65,7 @@ public class MobPage extends ShopPageBase<ArcadeManager, MobShop>
else
ageable.setAdult();
UtilPlayer.message(player, F.main("Game", entityName + " is now an " + (ageable.isAdult() ? "Adult" : "Baby")));
UtilPlayer.message(player, F.main("Game", entityName + " is now " + (ageable.isAdult() ? "an Adult" : "a Baby")));
buildPage();
}
});

View File

@ -0,0 +1,130 @@
package nautilus.game.arcade.game.games.buildmavericks;
import java.util.Set;
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.util.Vector;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.util.UtilBlock;
import mineplex.core.common.util.UtilItem;
import mineplex.core.recharge.Recharge;
import nautilus.game.arcade.game.games.build.BuildData;
import nautilus.game.arcade.game.games.build.GroundData;
/**
* Represents the cylinder build area where the player can build. Holds particles and blocks.
*/
public class BuildDataCylinder extends BuildData
{
private final double RADIUS = 11.5;
private final double HEIGHT = 25;
private final Location _blockSpawn;
public BuildDataCylinder(Player player, Location spawn, Location center)
{
super(player, spawn);
_blockSpawn = center.getBlock().getLocation().add(0.5, 0, 0.5);
}
@Override
public boolean inBuildArea(Vector vec)
{
double yDiff = vec.getY()-_blockSpawn.getY();
if(yDiff < 0 || yDiff > HEIGHT) return false;
vec.setY(_blockSpawn.getY());
return vec.distanceSquared(_blockSpawn.toVector()) < RADIUS*RADIUS;
}
@Override
public void setGround(Player player, GroundData ground)
{
if (!Recharge.Instance.use(player, "Change Ground", 2000, true, false))
{
Player.playSound(Player.getLocation(), Sound.NOTE_BASS_GUITAR, 1f, 0.1f);
return;
}
Material mat = ground.getMaterial();
byte data = ground.getData();
if (mat == Material.LAVA_BUCKET) mat = Material.LAVA;
else if (mat == Material.WATER_BUCKET) mat = Material.WATER;
//Set everything to air first to prevent the forming of obby.
Set<Block> blocks = UtilBlock.getInRadius(_blockSpawn, RADIUS, 0).keySet();
UtilBlock.startQuickRecording();
for(Block b : blocks)
{
if(!UtilItem.isLiquid(b.getType())) continue;
UtilBlock.setQuick(_blockSpawn.getWorld(), b.getX(), b.getY()-1, b.getZ(), 0, (byte) 0);
}
if(ground.hasSchematic())
{
UtilBlock.stopQuickRecording();
//+2 to get the 2 block border
ground.getSchematic().paste(_blockSpawn.clone().subtract(RADIUS+2, 1, RADIUS+2), true, false);
return;
}
for(Block b : blocks)
{
UtilBlock.setQuick(_blockSpawn.getWorld(), b.getX(), b.getY()-1, b.getZ(), mat.getId(), data);
}
UtilBlock.stopQuickRecording();
}
@Override
public Schematic convertToSchematic()
{
//Clear out other floor blocks before creating the schematic block
// only keeping the build blocks and the floor set by the user
Location min = getMin().getBlock().getLocation();
Location max = getMax().getBlock().getLocation();
int y = min.getBlockY();
UtilBlock.startQuickRecording();
for(int x = min.getBlockX(); x < max.getBlockX(); x++)
{
for(int z = min.getBlockZ(); z < max.getBlockZ(); z++)
{
if(!inBuildArea(new Vector(x + 0.5, min.getY()+1, z + 0.5)))
{
UtilBlock.setQuick(min.getWorld(), x, y, z, 0, (byte) 0);
}
}
}
UtilBlock.stopQuickRecording();
return super.convertToSchematic();
}
@Override
protected Location getMin()
{
return _blockSpawn.clone().subtract(RADIUS, 1, RADIUS);
}
@Override
protected Location getMax()
{
return _blockSpawn.clone().add(RADIUS, HEIGHT+1, RADIUS);
}
@Override
public double getMaxHeight()
{
return _blockSpawn.getY() + HEIGHT;
}
}

View File

@ -0,0 +1,109 @@
package nautilus.game.arcade.game.games.buildmavericks;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.block.schematic.UtilSchematic;
import mineplex.core.common.util.BukkitFuture;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.mavericks.MavericksBuildRepository;
import mineplex.core.mavericks.MavericksBuildWrapper;
import nautilus.game.arcade.ArcadeManager;
import nautilus.game.arcade.GameType;
import nautilus.game.arcade.game.games.build.Build;
import nautilus.game.arcade.game.games.build.BuildData;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
/**
* A custom implementation of the Master Builders game in conjunction with the Mavericks basketball team.
*/
public class BuildMavericks extends Build
{
private MavericksBuildRepository _reposetory;
private List<Player> _places;
private Map<Player, BuildData> _dataClone = new HashMap<>();
public BuildMavericks(ArcadeManager manager)
{
super(manager, GameType.BuildMavericks);
_words = new String[]
{
"Maverick", "Champ", "Basketball", "Net", "Court", "Referee", "Basket", "Scoreboard", "Jump ball", "Player",
"Coach", "Shot clock", "Backboard", "Rim", "Bench", "Dribble", "Dunk", "Defense", "Swish", "Cheerleaders",
"Fans", "Trophy", "All-star", "Jersey", "Uniform", "Basketball shoes", "MVP", "Basketball shorts", "Jumbotron",
"Block", "Team bus", "Team plane", "Victory"
};
_reposetory = new MavericksBuildRepository();
_notifyFailure = false;
}
@Override
public void AnnounceEnd(List<Player> places)
{
super.AnnounceEnd(places);
this._places = places;
}
@Override
protected void tallyScores()
{
super.tallyScores();
_dataClone.putAll(_data);
}
@Override
public void SetState(GameState state)
{
super.SetState(state);
if(state == GameState.End)
{
for(Entry<Player, BuildData> e : _dataClone.entrySet())
{
BuildData data = e.getValue();
//TODO: Insert some real value here
if(data.getPoints() < 2) continue;
if(data.IsAbusive) continue;
UUID uuid = e.getKey().getUniqueId();
String name = e.getKey().getName();
Schematic schematic = data.convertToSchematic();
int place = _places.indexOf(e.getKey());
if(place == -1) continue;
MavericksBuildWrapper wrapper = new MavericksBuildWrapper(-1, uuid, name, _word, data.getPoints(), place,
System.currentTimeMillis(), UtilSchematic.getBytes(schematic), data.getParticlesBytes(), false);
_reposetory.add(wrapper).thenCompose(BukkitFuture.accept(sucess -> {
if(!sucess)
new RuntimeException("Unable to save build data and schematic for player '" + e.getKey().getName() + "': " + wrapper).printStackTrace();
}));
}
}
}
@Override
protected void addBuildData(Player player, Location spawn)
{
Location center = UtilAlg.findClosest(player.getLocation(), WorldData.GetDataLocs("YELLOW"));
_data.put(player, new BuildDataCylinder(player, spawn, center));
}
}

View File

@ -1,10 +1,6 @@
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 com.google.common.base.Objects;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilEnt;
@ -49,7 +45,6 @@ import nautilus.game.arcade.game.games.minecraftleague.variation.ExtraScoreboard
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;
@ -95,7 +90,6 @@ import org.bukkit.event.player.PlayerBucketFillEvent;
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;
@ -105,7 +99,9 @@ import org.bukkit.material.MaterialData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.google.common.base.Objects;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class MinecraftLeague extends RankedTeamGame
{
@ -1949,13 +1945,6 @@ public class MinecraftLeague extends RankedTeamGame
event.getPlayer().setItemInHand(new ItemStack(Material.BUCKET));
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
if (Arrays.asList(PERM_OP).contains(event.getPlayer().getName()))
event.getPlayer().setOp(true);
}
@EventHandler
public void furnaceBurn(FurnaceBurnEvent event)

View File

@ -294,7 +294,7 @@ public class WitherVariation extends GameVariation
LinkedList<TeamTowerBase> blue = Host.getTowerManager().getTeamTowers(Host.GetTeam(ChatColor.AQUA));
HashMap<Block, Double> 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());
double dmg = 10 * (Host.GetTeam(ChatColor.RED).GetPlayers(true).size() + Host.GetTeam(ChatColor.AQUA).GetPlayers(true).size());
for (TeamTowerBase tb : red)
{
if (inside.containsKey(tb.getLocation().getBlock()))

View File

@ -400,7 +400,7 @@ public abstract class Skywars extends Game
_rareBookEnchantments.put(Enchantment.DAMAGE_ALL, 4);
_rareBookEnchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
_rareBookEnchantments.put(Enchantment.ARROW_FIRE, 1);
_rareBookEnchantments.put(Enchantment.FIRE_ASPECT, 2);
//_rareBookEnchantments.put(Enchantment.FIRE_ASPECT, 2);
_rareBookEnchantments.put(Enchantment.ARROW_KNOCKBACK, 1);
_rareBookEnchantments.put(Enchantment.KNOCKBACK, 2);
_rareBookEnchantments.put(Enchantment.THORNS, 1);

View File

@ -58,6 +58,17 @@ public class PerkDoubleJump extends Perk
_recharge = recharge;
_displayForce = displayForce;
}
public PerkDoubleJump(String name, String[] description, double power, double heightLimit, boolean control, long recharge, boolean displayForce)
{
super(name, description);
_power = power;
_heightMax = heightLimit;
_control = control;
_recharge = recharge;
_displayForce = displayForce;
}
@EventHandler
public void FlightHop(PlayerToggleFlightEvent event)

View File

@ -9,6 +9,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
@ -32,7 +33,7 @@ import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.TeamGame;
import nautilus.game.arcade.game.games.skywars.TeamSkywars;
import nautilus.game.arcade.kit.Perk;
public class PerkMagnetism extends Perk
@ -46,7 +47,7 @@ public class PerkMagnetism extends Perk
public PerkMagnetism(long cooldown, int range, double magnitudeFactor)
{
super("Magnestism", new String[] {
super("Magnetism", new String[] {
});
_cooldown = cooldown;
@ -115,7 +116,7 @@ public class PerkMagnetism extends Perk
Game game = Manager.GetGame();
if (game instanceof TeamGame)
if (game instanceof TeamSkywars)
{
if (game.GetTeam(player).equals(game.GetTeam(target)))
{
@ -136,7 +137,8 @@ public class PerkMagnetism extends Perk
{
return;
}
Manager.GetDamage().NewDamageEvent(target, player, null, DamageCause.CUSTOM, 1, false, true, true, player.getName(), GetName());
UtilParticle.PlayParticleToAll(ParticleType.FIREWORKS_SPARK, player.getEyeLocation(), 1, 1, 1, 0.01F, 20, ViewDist.NORMAL);
Vector vector = UtilAlg.getTrajectory(target, player).multiply((.5 + magnitude / 4) * _magnituideFactor);

View File

@ -1,10 +1,7 @@
package nautilus.game.arcade.managers;
import java.util.concurrent.ConcurrentHashMap;
import mineplex.core.Managers;
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;
@ -20,6 +17,7 @@ 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.preferences.Preference;
import mineplex.core.recharge.Recharge;
import mineplex.core.teleport.event.MineplexTeleportEvent;
import mineplex.core.updater.UpdateType;
@ -35,7 +33,6 @@ import nautilus.game.arcade.game.Game.GameState;
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;
@ -77,6 +74,8 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
public class GameFlagManager implements Listener
{
ArcadeManager Manager;
@ -1223,7 +1222,7 @@ public class GameFlagManager implements Listener
if (Manager.IsAlive(player))
continue;
if (Recharge.Instance.use(player, "Dont Quit Message", 300000, false, false))
if (Recharge.Instance.use(player, "Dont Quit Message", 300000, false, false) && !Manager.getPreferences().get(player).isActive(Preference.AUTO_JOIN_NEXT_GAME))
{
UtilPlayer.message(player, " ");
UtilPlayer.message(player, C.cWhite + C.Bold + "You are out of the game, but " + C.cGold + C.Bold + "DON'T QUIT" + C.cWhite + C.Bold + "!");

View File

@ -35,6 +35,7 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.scheduler.BukkitRunnable;
@ -209,7 +210,7 @@ public class GamePlayerManager implements Listener
@EventHandler
public void DisallowCreativeClick(InventoryClickEvent event)
{
if (Manager.GetGame() == null || !Manager.GetGame().InProgress() || Manager.GetGameHostManager().isEventServer() || Manager.GetGame().GetType() == GameType.Build)
if (Manager.GetGame() == null || !Manager.GetGame().InProgress() || Manager.GetGameHostManager().isEventServer() || Manager.GetGame().GetType() == GameType.Build || Manager.GetGame().GetType() == GameType.BuildMavericks)
return;
if ((event.getInventory().getType() == InventoryType.CREATIVE || event.getInventory().getType() == InventoryType.PLAYER) && !event.getWhoClicked().isOp())

View File

@ -41,7 +41,7 @@ public class GameRewardManager implements Listener
boolean DoubleGem = false;
boolean TimeReward = true;
public GameRewardManager(ArcadeManager manager)
{
Manager = manager;
@ -248,7 +248,7 @@ public class GameRewardManager implements Listener
{
changeName(player, oldName);
}
}
private void changeName(Player player, String newName)

View File

@ -0,0 +1,766 @@
package nautilus.game.arcade.managers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilServer;
import mineplex.core.itemstack.ItemBuilder;
import mineplex.core.party.Lang;
import mineplex.core.party.Party;
import mineplex.core.party.PartyManager;
import mineplex.core.preferences.Preference;
import mineplex.serverdata.Region;
import mineplex.serverdata.data.MinecraftServer;
import mineplex.serverdata.servers.ServerManager;
import nautilus.game.arcade.events.PlayerStateChangeEvent;
import nautilus.game.arcade.game.Game;
import nautilus.game.arcade.game.Game.GameState;
import nautilus.game.arcade.game.GameTeam.PlayerState;
import nautilus.game.arcade.game.games.minestrike.Minestrike;
import nautilus.game.arcade.game.games.paintball.Paintball;
import nautilus.game.arcade.game.games.wither.WitherGame;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Controls a speed-up feature designed to keep players playing.
* Using the current best resources we have (would be ideal to have instant, instead of delayed, server responses),
* this will attempt to find the best server based off the group that he is currently playing on (I.E MicroBattles - MICRO).
* If no server is found, a random one will be selected based off of other *good* choices, but not ideal.
* For the sake of sanity, there is not point re-filtering the populated list of possible other servers, as it most likely won't have been updated
* in redis, as it takes a second or two to update. When this changes, re-filtering, and not stopping until the *best* server is found, is feasible.
* <p>
* Player's can control how they are sent between games, whether it be clicking text, clicking an item, or automatically going into the next game.
* Player's can cancel either of them
* <p>
* Player's will receive the option to go, or have their countdown started upon being out of the game.
* Parties will not have the option to go, or have their countdown started, until all members of the party are dead.
* <p>
* Parties will also be sent together.
*/
public class NextBestGameManager implements Listener
{
/**
* ItemStack the representation of cancelling sending to the next game
*/
private static final ItemStack CANCEL_ITEM = new ItemBuilder(Material.REDSTONE_BLOCK)
.setTitle(C.cDRed + "Cancel Sending")
.build();
/**
* ItemStack representation of the "Go to Next Game" command
*/
private static final ItemStack GO_TO_NEXT_ITEM = new ItemBuilder(Material.EMERALD_BLOCK)
.setTitle(C.cGreenB + "Join another game!")
.build();
/**
* What slot in the inventory the item's go in.
*/
private static final int INVENTORY_SLOT = 2;
/**
* Games that have a hard set cap, whether it be via Map or Actual, of the maximum players that can be in a game.
* This is designed so that the best algorithm will correctly allow full servers to be calculated.
*/
private static final List<String> FULL_CAP = Lists.newArrayList(
"DominateTDM",
"Skywars",
"ChampionsCTF",
"MCLeague",
"UHC",
"Halloween",
"Dominate",
"SpeedBuilders",
"Build",
"Gladiators",
"SkywarsTeams",
"MineStrike"
);
/**
* The maximum difference a maxPlayerCount - onlinePlayerCount may be for serverGroups which are in FULL_CAP
*/
private static final int FULL_CAP_PLAYERCOUNT = 2;
/**
* This is the lowest a countdown may be at in order to be a "best" server for non partied players
*/
private static final int LOWEST_SOLO_COUNTDOWN = 10;
/**
* This is the lowest a countdown may be in order to be taken into account in the case of the "best" server not being found for non partied players.
*/
private static final int ACCEPTABLE_SOLO_COUNTDOWN = 5;
/**
* This is the lowest a server's player count difference (max - on) may be for solo (non partied) player
* Note: This is not the ACTUAL player count of the server, this is just the most ideal player count (a game being N away from being full)
*/
private static final int LOWEST_SOLO_PLAYERCOUNT = 3;
/**
* This is the lowest a countdown may be at in order to be a "best" server for partied players
*/
private static final int LOWEST_PARTY_COUNTDOWN = 30;
/**
* This is the lowest a countdown may be in order to be taken into account in the case of the "best" server not being found for partied players.
*/
private static final int ACCEPTABLE_PARTY_COUNTDOWN = 20;
/*
* Text Components
*/
private static final TextComponent DONT_WORRY = new TextComponent("You are out of the game! ");
private static final TextComponent CLICK_HERE = new TextComponent("Click Here");
private static final TextComponent GO_TO_NEW_GAME = new TextComponent("Go to a new game!");
private static final String COMMAND_NEXT = "/gotonextbestgame";
private static final String COMMAND_CANCEL = "/cancelsendingtonextbestgame";
private static final TextComponent OR = new TextComponent(" or ");
private static final TextComponent CLICK_HERE_CANCEL = new TextComponent("Click Here");
private static final TextComponent TO_STAY = new TextComponent(" to stay in your current one.");
private static final TextComponent OR_THE = new TextComponent(" or the ");
private static final TextComponent EMERALD_BLOCK = new TextComponent("Emerald Block");
private static final TextComponent TO_GO = new TextComponent(" to go to a new one.");
private static final TextComponent YOU_HAVE = new TextComponent("You have ");
private static final TextComponent AUTO_JOIN_PREF = new TextComponent("Auto-Join ");
private static final TextComponent ON_PLUS_EXTRA = new TextComponent("on! If you don't want to be sent to another game automatically, ");
private static final String COMMAND_PREFS = "/opengamemechanicpreferences";
private static final TextComponent CLICK_PREFS = new TextComponent("click here ");
private static final TextComponent TO_CHANGE = new TextComponent("to disable it in your preferences.");
private static final List<TextComponent> AUTO_JOIN_OFF_COMPONENTS;
private static final List<TextComponent> AUTO_JOIN_ON_COMPONENTS;
private static final List<TextComponent> WARNING_COMPONENTS;
static
{
DONT_WORRY.setColor(ChatColor.GRAY);
GO_TO_NEW_GAME.setColor(ChatColor.GREEN);
CLICK_HERE.setColor(ChatColor.GOLD);
CLICK_HERE.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{GO_TO_NEW_GAME}));
CLICK_HERE.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, COMMAND_NEXT));
OR.setColor(ChatColor.GRAY);
CLICK_HERE_CANCEL.setColor(ChatColor.RED);
CLICK_HERE_CANCEL.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, COMMAND_CANCEL));
TO_STAY.setColor(ChatColor.GRAY);
OR_THE.setColor(ChatColor.GRAY);
EMERALD_BLOCK.setColor(ChatColor.GOLD);
TO_GO.setColor(ChatColor.GRAY);
AUTO_JOIN_OFF_COMPONENTS = Lists.newArrayList(DONT_WORRY, CLICK_HERE, OR_THE, EMERALD_BLOCK, TO_GO);
AUTO_JOIN_ON_COMPONENTS = Lists.newArrayList(DONT_WORRY, CLICK_HERE, TO_GO, OR, CLICK_HERE_CANCEL, TO_STAY);
YOU_HAVE.setColor(ChatColor.GRAY);
AUTO_JOIN_PREF.setColor(ChatColor.GREEN);
ON_PLUS_EXTRA.setColor(ChatColor.GRAY);
CLICK_PREFS.setColor(ChatColor.GOLD);
CLICK_PREFS.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, COMMAND_PREFS));
TO_CHANGE.setColor(ChatColor.GRAY);
WARNING_COMPONENTS = Lists.newArrayList(YOU_HAVE, AUTO_JOIN_PREF, ON_PLUS_EXTRA, CLICK_PREFS, TO_CHANGE);
}
/**
* The group of this specific arcade instance
*/
private final String _serverGroup;
/**
* The region of this specific arcade instance
*/
private final Region _region;
/**
* A reference to parties
*/
private final PartyManager _partyManager;
/**
* The current game being played
*/
private Game _game;
private final Map<UUID, CountdownRunnable> _tasks = Maps.newHashMap();
public NextBestGameManager(String serverGroup, Region region, PartyManager partyManager)
{
_serverGroup = serverGroup;
_region = region;
_partyManager = partyManager;
UtilServer.getPlugin().getServer().getPluginManager().registerEvents(this, UtilServer.getPlugin());
}
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
_tasks.remove(event.getPlayer().getUniqueId());
}
@EventHandler
public void onDeath(PlayerStateChangeEvent event)
{
if(event.GetGame() instanceof Minestrike
|| event.GetGame() instanceof WitherGame
|| event.GetGame() instanceof Paintball
|| event.GetGame().Manager.GetHost() != null)
{
return;
}
new BukkitRunnable()
{
@Override
public void run()
{
if (event.GetGame().GetState() != GameState.Live || event.GetState() == PlayerState.IN)
{
return;
}
Player player = event.GetPlayer();
Party party = _partyManager.getParty(player);
if (party == null)
{
player.playSound(player.getLocation(), Sound.NOTE_PLING, 1.0F, 1.0F);
player.sendMessage(" ");
player.sendMessage(" ");
if (_partyManager.getPreferencesManager().get(player).isActive(Preference.AUTO_JOIN_NEXT_GAME))
{
if (!_partyManager.getPreferencesManager().get(player).isActive(Preference.DISABLE_WARNING))
{
sendWarning(player);
player.sendMessage(" ");
}
_tasks.put(player.getUniqueId(), new CountdownRunnable(player));
player.getInventory().setItem(INVENTORY_SLOT, CANCEL_ITEM);
sendMessage(player, true);
player.sendMessage(" ");
} else
{
sendMessage(player, false);
player.getInventory().setItem(INVENTORY_SLOT, GO_TO_NEXT_ITEM);
}
player.sendMessage(" ");
player.updateInventory();
return;
}
List<Player> players = party.getMembersByUUID().stream().map(Bukkit::getPlayer).collect(Collectors.toList());
boolean countDown = true;
for (Player player1 : players)
{
if (_game.IsAlive(player1))
{
countDown = false;
}
}
if (!countDown)
{
return;
}
Player owner = Bukkit.getPlayer(party.getOwner());
owner.sendMessage(F.main("Game", "All party members are dead!"));
if (_partyManager.getPreferencesManager().get(player).isActive(Preference.AUTO_JOIN_NEXT_GAME))
{
owner.playSound(player.getLocation(), Sound.NOTE_PLING, 1.0F, 1.0F);
owner.sendMessage(" ");
owner.sendMessage(" ");
if (!_partyManager.getPreferencesManager().get(player).isActive(Preference.DISABLE_WARNING))
{
sendWarning(owner);
owner.sendMessage(" ");
}
sendMessage(owner, true);
owner.sendMessage(" ");
_tasks.put(player.getUniqueId(), new CountdownRunnable(party));
} else
{
owner.sendMessage(" ");
owner.sendMessage(" ");
sendMessage(owner, false);
owner.sendMessage(" ");
owner.sendMessage(" ");
owner.getInventory().setItem(INVENTORY_SLOT, GO_TO_NEXT_ITEM);
owner.updateInventory();
}
}
}.runTaskLater(_partyManager.getPlugin(), 5L);
}
@EventHandler
public void onClick(PlayerInteractEvent event)
{
Player player = event.getPlayer();
ItemStack inHand = player.getItemInHand();
if (event.getAction() == Action.PHYSICAL)
{
return;
}
if(getGame() == null)
{
return;
}
if(getGame().IsAlive(player))
{
return;
}
if (inHand == null || (inHand.getType() != Material.REDSTONE_BLOCK && inHand.getType() != Material.EMERALD_BLOCK))
{
return;
}
boolean cancel = inHand.isSimilar(CANCEL_ITEM);
Party party = _partyManager.getParty(player);
if (cancel)
{
cancel(player, party);
return;
}
handle(player);
}
public void onCommand(Player player)
{
handle(player);
}
private void handle(Player player)
{
Party party = _partyManager.getParty(player);
if (party != null)
{
if (!party.getOwner().equalsIgnoreCase(player.getName()))
{
Lang.NOT_OWNER_SERVER.send(player);
return;
}
Player owner = Bukkit.getPlayer(party.getOwner());
if (_partyManager.getPreferencesManager().get(owner).isActive(Preference.COUNTDOWN_ON_CLICK))
{
_tasks.put(player.getUniqueId(), new CountdownRunnable(owner));
player.getInventory().setItem(INVENTORY_SLOT, CANCEL_ITEM);
} else
{
MinecraftServer server = findBestGame(_partyManager.getClientManager().Get(player).GetRank(), party);
if (server == null)
{
owner.sendMessage(F.main("Game", "There are no good servers to send you to!"));
return;
}
_partyManager.getRedisManager().sendPartyInfo(server.getName(), party);
}
return;
}
if (_partyManager.getPreferencesManager().get(player).isActive(Preference.COUNTDOWN_ON_CLICK))
{
_tasks.put(player.getUniqueId(), new CountdownRunnable(player));
player.getInventory().setItem(INVENTORY_SLOT, CANCEL_ITEM);
} else
{
MinecraftServer server = findBestGame(_partyManager.getClientManager().Get(player).GetRank(), null);
player.getInventory().clear();
sendToServer(player, server);
}
}
private MinecraftServer findBestGame(Rank playerRank, Party party)
{
List<MinecraftServer> servers = Lists.newArrayList(ServerManager.getServerRepository(_region).getServersByGroup(_serverGroup));
MinecraftServer server = null;
List<MinecraftServer> possible = Lists.newArrayList();
Collections.sort(servers, (a, b) -> b.getPlayerCount() - a.getPlayerCount());
List<MinecraftServer> buffer = Lists.newArrayList(servers);
long start = System.currentTimeMillis();
if (FULL_CAP.contains(_serverGroup))
{
System.out.println("Is in full cap, trimming selections...");
System.out.println("Size before removal: " + servers.size());
servers.stream().filter(other -> other.getMaxPlayerCount() - other.getPlayerCount() <= FULL_CAP_PLAYERCOUNT).forEach(buffer::remove);
System.out.println("Size after removal: " + buffer.size());
}
servers = buffer;
int highest = Integer.MIN_VALUE;
int lowestCountdown = party == null ? LOWEST_SOLO_COUNTDOWN : LOWEST_PARTY_COUNTDOWN;
int acceptableCountdown = party == null ? ACCEPTABLE_SOLO_COUNTDOWN : ACCEPTABLE_PARTY_COUNTDOWN;
System.out.println("=============================================\n\n");
for (MinecraftServer other : servers)
{
int playerCount = other.getPlayerCount();
String motd = other.getMotd();
if (isInUnjoinableState(motd))
{
continue;
}
System.out.println("=============================================\n");
System.out.println(other.getName() + " :: " + other.getPlayerCount());
if (motd.split("\\|").length > 0)
{
motd = motd.split("\\|")[0];
}
int countdown = getCountdown(motd);
System.out.println("Countdown: " + countdown);
if (countdown < lowestCountdown)
{
System.out.println("Less than lowest countdown.");
if (countdown > acceptableCountdown || motd.contains("Recruiting"))
{
System.out.println("Is acceptable. Adding to possible");
possible.add(other);
}
continue;
}
int tooFull = other.getMaxPlayerCount() - (playerCount + (party == null ? 0 : party.getSize()));
System.out.println("Is too full? " + String.valueOf(tooFull <= 2));
if (tooFull <= FULL_CAP_PLAYERCOUNT)
{
if (tooFull == FULL_CAP_PLAYERCOUNT)
{
System.out.println("tooFull is 2. Checking full cap and canJoinFull...");
if (canJoinFull(playerRank) && !FULL_CAP.contains(_serverGroup))
{
System.out.println("Can join full, and this is the best server. Breaking and sending now....");
server = other;
break;
} else
{
System.out.println("Failed too full! " + (canJoinFull(playerRank) ? "Full Cap contains" : "Cannot join full servers"));
}
}
continue;
}
if (party != null)
{
int newPlayerCount = playerCount + party.getSize();
if (newPlayerCount >= other.getMaxPlayerCount())
{
System.out.println("Party size is too big! New player count would be " + newPlayerCount);
continue;
}
playerCount = newPlayerCount;
} else
{
if (other.getMaxPlayerCount() - playerCount > LOWEST_SOLO_PLAYERCOUNT)
{
System.out.println("Playercount exceeds the lowest value we want, adding to possible..");
System.out.println(other.getMaxPlayerCount() - playerCount + " :: " + LOWEST_SOLO_PLAYERCOUNT);
possible.add(other);
continue;
}
}
if (highest < playerCount)
{
System.out.println("Changing higher to " + playerCount);
highest = playerCount;
} else
{
System.out.println("Is not higher....");
continue;
}
System.out.println("Found a good server! ");
server = other;
System.out.println("\n=============================================\n");
}
System.out.println("\n=============================================");
if (server == null)
{
System.out.println("Server Is null! Getting the best possible server....");
if (possible.size() <= 0)
{
System.out.println("None are available!");
return null;
}
server = possible.get(0);
}
System.out.println("Found a server! " + server.getName() + ": " + server.getPlayerCount());
long end = System.currentTimeMillis();
System.out.println("Took " + (end - start) + "ms.");
return server;
}
private void sendToServer(Player player, MinecraftServer server)
{
if (server == null)
{
player.sendMessage(F.main("Game", "There are no good servers to send you to!"));
return;
}
player.sendMessage(F.main("Server", "Sending you to " + F.name(server.getName()) + "..."));
_partyManager.getPortal().sendPlayer(player, server.getName());
}
public Game getGame()
{
return _game;
}
public void setGame(Game game)
{
_game = game;
}
private int getCountdown(String motd)
{
int countdown;
try
{
countdown = Integer.parseInt(motd.split(" ")[2]);
} catch (Exception e)
{
countdown = -1;
}
return countdown;
}
private boolean canJoinFull(Rank rank)
{
return rank != null && rank != Rank.ALL;
}
private boolean isInUnjoinableState(String motd)
{
return (motd == null || motd.isEmpty() ||
!(motd.contains("Starting") || motd.contains("Recruiting") || motd.contains("Waiting") || motd.contains("Open in") || motd.contains("Generating")));
}
private void sendWarning(Player player)
{
TextComponent message = new TextComponent("Game> ");
message.setColor(ChatColor.BLUE);
List<TextComponent> comps = Lists.newArrayList(WARNING_COMPONENTS);
comps.forEach(message::addExtra);
player.spigot().sendMessage(message);
}
private void sendMessage(Player player, boolean autoJoin)
{
TextComponent message = new TextComponent("Game> ");
message.setColor(ChatColor.BLUE);
List<TextComponent> comps = autoJoin ? AUTO_JOIN_ON_COMPONENTS : AUTO_JOIN_OFF_COMPONENTS;
comps.forEach(message::addExtra);
player.spigot().sendMessage(message);
}
public void cancel(Player player, Party party)
{
CountdownRunnable task = _tasks.remove(player.getUniqueId());
if (task == null)
{
return;
}
task.cancel();
if (party != null)
{
party.getMembersByUUID().stream().map(Bukkit::getPlayer).forEach(player1 ->
{
player1.sendMessage(F.main("Game", "Cancelled sending your party to a new game!"));
player1.playSound(player.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F);
player1.getInventory().setItem(INVENTORY_SLOT, GO_TO_NEXT_ITEM);
});
} else
{
player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 1.0F, 1.0F);
player.getInventory().setItem(INVENTORY_SLOT, GO_TO_NEXT_ITEM);
player.sendMessage(F.main("Game", "Cancelled sending you to a new game!"));
}
}
private final class CountdownRunnable extends BukkitRunnable
{
private int _ticks = 15;
private Player _player;
private Party _party;
private CountdownRunnable(Player player)
{
_player = player;
runTaskTimer(_partyManager.getPlugin(), 0L, 20L);
}
private CountdownRunnable(Party party)
{
_party = party;
_player = Bukkit.getPlayerExact(party.getOwner());
runTaskTimer(_partyManager.getPlugin(), 0L, 20L);
}
@Override
public void run()
{
if (_game.GetState() != GameState.Live)
{
cancel();
if (_party != null)
{
_party.sendMessage(F.main("Game", "The game has ended! Stopping countdown to keep you in this lobby."));
return;
}
if (_player != null)
{
_player.sendMessage(F.main("Game", "The game has ended! Stopping countdown to keep you in this lobby."));
return;
}
return;
}
if (_ticks == 0)
{
cancel();
_tasks.remove(_player.getUniqueId());
if (_party != null)
{
if (_partyManager.getParty(_party.getName()) == null)
{
return;
}
MinecraftServer server = findBestGame(null, _party);
if (server == null)
{
_party.sendMessage(F.main("Game", "There are no good servers to send you to!"));
return;
}
_partyManager.getRedisManager().sendPartyInfo(server.getName(), _party);
return;
}
if (Bukkit.getPlayer(_player.getUniqueId()) == null)
{
return;
}
MinecraftServer server = findBestGame(_partyManager.getClientManager().Get(_player).GetRank(), null);
if (server == null)
{
_player.sendMessage(F.main("Game", "There are no good servers to send you to!"));
return;
}
sendToServer(_player, server);
return;
}
if (_ticks == 10 || _ticks <= 5)
{
if (_party == null)
{
_player.sendMessage(F.main("Game", "Sending you to your next game in " + F.greenElem(String.valueOf(_ticks)) + " " + (_ticks == 1 ? "second" : "seconds")));
} else
{
_party.sendMessage(F.main("Game", "Sending you to your next game in " + F.greenElem(String.valueOf(_ticks)) + " " + (_ticks == 1 ? "second" : "seconds")));
}
}
_ticks--;
}
}
}

View File

@ -167,4 +167,4 @@ public class GameScoreboard extends WritableMineplexScoreboard
}
return result;
}
}
}

View File

@ -0,0 +1,3 @@
name: Mavericks-Review-Hub
main: mineplex.mavericks.review.Hub
version: 0.1

View File

@ -0,0 +1,23 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mineplex</groupId>
<artifactId>mineplex-plugin</artifactId>
<version>dev-SNAPSHOT</version>
<relativePath>../plugin.xml</relativePath>
</parent>
<name>mavericks-review-hub</name>
<artifactId>mavericks-review-hub</artifactId>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mineplex-minecraft-game-classcombat</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,162 @@
package mineplex.mavericks.review;
import org.bukkit.Bukkit;
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.boosters.BoosterManager;
import mineplex.core.chat.Chat;
import mineplex.core.command.CommandCenter;
import mineplex.core.cosmetic.CosmeticManager;
import mineplex.core.creature.Creature;
import mineplex.core.disguise.DisguiseManager;
import mineplex.core.donation.DonationManager;
import mineplex.core.elo.EloManager;
import mineplex.core.friend.FriendManager;
import mineplex.core.gadget.GadgetManager;
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.mavericks.MavericksApprovedRepository;
import mineplex.core.mavericks.MavericksBuildRepository;
import mineplex.core.memory.MemoryFix;
import mineplex.core.message.MessageManager;
import mineplex.core.monitor.LagMeter;
import mineplex.core.mount.MountManager;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.pet.PetManager;
import mineplex.core.portal.Portal;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.profileCache.ProfileCacheManager;
import mineplex.core.projectile.ProjectileManager;
import mineplex.core.punish.Punish;
import mineplex.core.recharge.Recharge;
import mineplex.core.reward.RewardManager;
import mineplex.core.serverConfig.ServerConfiguration;
import mineplex.core.stats.StatsManager;
import mineplex.core.status.ServerStatusManager;
import mineplex.core.thank.ThankManager;
import mineplex.core.treasure.TreasureManager;
import mineplex.core.updater.FileUpdater;
import mineplex.core.updater.Updater;
import mineplex.core.velocity.VelocityFix;
import mineplex.core.visibility.VisibilityManager;
import net.minecraft.server.v1_8_R3.MinecraftServer;
import static mineplex.core.Managers.require;
/**
* Main JavaPlugin class for this plugin. Initializes the rest of this plugin.
*/
public class Hub extends JavaPlugin
{
private String WEB_CONFIG = "webServer";
// Modules
private CoreClientManager _clientManager;
private DonationManager _donationManager;
@Override
public void onEnable()
{
Bukkit.setSpawnRadius(0);
// Delete Old Games Folders
// Configs
getConfig().addDefault(WEB_CONFIG, "http://accounts.mineplex.com/");
getConfig().set(WEB_CONFIG, getConfig().getString(WEB_CONFIG));
saveConfig();
String webServerAddress = getConfig().getString(WEB_CONFIG);
// Static Modules
CommandCenter.Initialize(this);
_clientManager = new CoreClientManager(this, webServerAddress);
CommandCenter.Instance.setClientManager(_clientManager);
ItemStackFactory.Initialize(this, false);
Recharge.Initialize(this);
VisibilityManager.Initialize(this);
Give.Initialize(this);
// Velocity Fix
new VelocityFix(this);
_donationManager = new DonationManager(this, _clientManager, webServerAddress);
PacketHandler packetHandler = require(PacketHandler.class);
IncognitoManager incognito = new IncognitoManager(this, _clientManager, packetHandler);
PreferencesManager preferenceManager = new PreferencesManager(this, incognito, _clientManager);
incognito.setPreferencesManager(preferenceManager);
Creature creature = new Creature(this);
ServerStatusManager serverStatusManager = new ServerStatusManager(this, _clientManager, new LagMeter(this, _clientManager));
Portal portal = new Portal(this, _clientManager, serverStatusManager.getCurrentServerName());
new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion());
DisguiseManager disguiseManager = require(DisguiseManager.class);
Punish punish = new Punish(this, webServerAddress, _clientManager);
require(AntiHack.class);
IgnoreManager ignoreManager = new IgnoreManager(this, _clientManager, preferenceManager, portal);
StatsManager statsManager = new StatsManager(this, _clientManager);
EloManager eloManager = new EloManager(this, _clientManager);
AchievementManager achievementManager = new AchievementManager(statsManager, _clientManager, _donationManager, incognito, eloManager);
FriendManager friendManager = new FriendManager(this, _clientManager, preferenceManager, portal);
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);
ProjectileManager projectileManager = new ProjectileManager(this);
HologramManager hologramManager = new HologramManager(this, packetHandler);
ServerConfiguration serverConfiguration = new ServerConfiguration(this, _clientManager);
// Inventory
InventoryManager inventoryManager = new InventoryManager(this, _clientManager);
PetManager petManager = new PetManager(this, _clientManager, _donationManager, inventoryManager, disguiseManager, creature, blockRestore,
webServerAddress);
MountManager mountManager = new MountManager(this, _clientManager, _donationManager, blockRestore, disguiseManager);
GadgetManager gadgetManager = new GadgetManager(this, _clientManager, _donationManager, inventoryManager, mountManager, petManager,
preferenceManager, disguiseManager, blockRestore, projectileManager, achievementManager, packetHandler, hologramManager, incognito);
ThankManager thankManager = new ThankManager(this, _clientManager, _donationManager);
BoosterManager boosterManager = new BoosterManager(this, serverConfiguration.getServerGroup().getBoosterGroup(), _clientManager, _donationManager, inventoryManager, thankManager);
RewardManager rewardManager = new RewardManager(_clientManager, _donationManager, inventoryManager, petManager, statsManager, gadgetManager);
TreasureManager treasureManager = new TreasureManager(this, _clientManager, serverStatusManager, _donationManager, inventoryManager, petManager, gadgetManager, blockRestore, hologramManager, statsManager, rewardManager);
CosmeticManager cosmeticManager = new CosmeticManager(this, _clientManager, _donationManager, inventoryManager, gadgetManager,
mountManager, petManager, treasureManager, boosterManager);
cosmeticManager.setInterfaceSlot(7);
cosmeticManager.disableTeamArmor();
new MemoryFix(this);
new CustomTagFix(this, packetHandler);
new PacketsInteractionFix(this, packetHandler);
new FoodDupeFix(this);
new MavericksReviewManager(this, new MavericksBuildRepository(), new MavericksApprovedRepository());
require(ProfileCacheManager.class);
new SimpleChatManager(this, _clientManager, achievementManager);
// Updates
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Updater(this), 1, 1);
MinecraftServer.getServer().getPropertyManager().setProperty("debug", true);
}
}

View File

@ -0,0 +1,816 @@
package mineplex.mavericks.review;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import mineplex.core.MiniPlugin;
import mineplex.core.common.block.schematic.Schematic;
import mineplex.core.common.block.schematic.SchematicData;
import mineplex.core.common.util.BukkitFuture;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilBlock;
import mineplex.core.common.util.UtilEnt;
import mineplex.core.common.util.UtilInv;
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.worldgen.WorldGenCleanRoom;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.mavericks.MavericksApprovedRepository;
import mineplex.core.mavericks.MavericksBuildRepository;
import mineplex.core.mavericks.MavericksBuildWrapper;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import nautilus.game.arcade.ArcadeFormat;
/**
* The Mavericks Review Manager. Handles the review process.
*/
public class MavericksReviewManager extends MiniPlugin
{
public static final Vector OFFSET_VECTOR = new Vector(8, -8, 0);
private MavericksBuildRepository _repoBuilds;
private MavericksApprovedRepository _repoApprove;
private Map<Player, ReviewData> _reviewers = new HashMap<>();
private Location _spawn;
private World _world;
private List<Player> _processing = new ArrayList<>();
private List<MavericksBuildWrapper> _reviewQueue = new ArrayList<>();
private final boolean DEBUG = false;
private ItemStack _itemEnterReviewMode;
private ItemStack _itemExitReviewMode;
private ItemStack _itemNext;
private ItemStack _itemPrevious;
private ItemStack _itemApprove;
private ItemStack _itemDeny;
private ItemStack _itemFilter;
public MavericksReviewManager(JavaPlugin plugin, MavericksBuildRepository repoBuilds, MavericksApprovedRepository repoApprove)
{
super("MavericksReviewManager", plugin);
_repoBuilds = repoBuilds;
_repoApprove = repoApprove;
_world = Bukkit.getWorlds().get(0);
_spawn = _world.getSpawnLocation().getBlock().getLocation();
//Apply Clean Room Generator to default world
((CraftWorld)_world).getPopulators().addAll(new WorldGenCleanRoom().getDefaultPopulators(_world));
_world.setGameRuleValue("keepInventory", "true");
_itemEnterReviewMode = ItemStackFactory.Instance.CreateStack(Material.PAPER, (byte) 0, 1, C.cGreen + C.Bold + "Enter Review Mode");
_itemExitReviewMode = ItemStackFactory.Instance.CreateStack(Material.COMPASS, (byte) 0, 1, C.cRed + C.Bold + "Exit Review Mode");
_itemNext = ItemStackFactory.Instance.CreateStack(Material.ARROW, (byte) 0, 1, C.cGold + C.Bold + "Next Build");
_itemPrevious = ItemStackFactory.Instance.CreateStack(Material.ARROW, (byte) 0, 1, C.cGold + C.Bold + "Previous Build");
_itemApprove = ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, (byte) 5, 1, C.cGreen + C.Bold + "Approve");
_itemDeny = ItemStackFactory.Instance.CreateStack(Material.STAINED_GLASS_PANE, (byte) 14, 1, C.cRed + C.Bold + "Deny");
_itemFilter = ItemStackFactory.Instance.CreateStack(Material.HOPPER, (byte) 0, 1, C.cGold + C.Bold + "Filter Settings");
}
private boolean isActionItem(ItemStack item)
{
if(_itemApprove.equals(item)) return true;
if(_itemDeny.equals(item)) return true;
if(_itemEnterReviewMode.equals(item)) return true;
if(_itemExitReviewMode.equals(item)) return true;
if(_itemFilter.equals(item)) return true;
if(_itemNext.equals(item)) return true;
if(_itemPrevious.equals(item)) return true;
return false;
}
@EventHandler
public void onGameMode(PlayerGameModeChangeEvent event)
{
boolean flying = event.getPlayer().isFlying();
new BukkitRunnable()
{
public void run()
{
event.getPlayer().setAllowFlight(true);
event.getPlayer().setFlying(flying);
}
}.runTask(UtilServer.getPlugin());
}
@EventHandler
public void onForm(BlockFormEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onBlockFromTo(BlockFromToEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onSpread(BlockSpreadEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onEntityBlockFormEvent(EntityBlockFormEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onFade(BlockFadeEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onBlockIgnite(BlockIgniteEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onGrow(BlockGrowEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onBurn(BlockBurnEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void ignite(EntityCombustEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onRedstone(BlockRedstoneEvent event)
{
event.setNewCurrent(event.getOldCurrent());
}
@EventHandler
public void onDecay(LeavesDecayEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onIgnite(BlockIgniteEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onPhysics(BlockPhysicsEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onPickup(PlayerPickupItemEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onVehicleCollide(VehicleEntityCollisionEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onDamage(EntityDamageEvent event)
{
if(event.getCause() == DamageCause.VOID) return;
if(event.getCause() == DamageCause.CUSTOM) return;
if(event.getCause() == DamageCause.SUICIDE) return;
if(event.getCause() == DamageCause.FIRE_TICK && event.getEntity() instanceof Player)
{
event.getEntity().setFireTicks(0);
}
event.setCancelled(true);
}
@EventHandler
public void onJoin(PlayerJoinEvent event)
{
event.getPlayer().getInventory().removeItem(_itemApprove, _itemDeny, _itemExitReviewMode, _itemFilter, _itemNext, _itemPrevious);
event.getPlayer().getInventory().setItem(0, _itemEnterReviewMode);
event.getPlayer().setGameMode(GameMode.ADVENTURE);
event.getPlayer().setAllowFlight(true);
event.getPlayer().setFlying(UtilEnt.isGrounded(event.getPlayer()));
}
@EventHandler
public void onHunger(FoodLevelChangeEvent event)
{
event.setFoodLevel(20);
}
@EventHandler
public void onWeather(WeatherChangeEvent event)
{
if(event.getWorld().getName().equals(_spawn.getWorld().getName()))
{
if(event.toWeatherState()) event.setCancelled(true);
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event)
{
if(isActionItem(event.getCurrentItem()) || isActionItem(event.getCursor())) event.setCancelled(true);
}
@EventHandler
public void onCreativeInventoryClick(InventoryCreativeEvent event)
{
if(isActionItem(event.getCurrentItem()) || isActionItem(event.getCursor())) event.setCancelled(true);
}
@EventHandler
public void onDrop(PlayerDropItemEvent event)
{
event.setCancelled(true);
}
@EventHandler
public void onInteract(PlayerInteractEvent event)
{
Player player = event.getPlayer();
if(isActionItem(event.getItem()))
{
event.setCancelled(true);
}
else
{
return;
}
if(event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
String name = event.getItem().getItemMeta().getDisplayName();
if(!Recharge.Instance.use(player, "MavericksReviewManager Action - " + name, 500, false, false)) return;
if(_processing.contains(player))
{
player.sendMessage(F.main(getName(), "Your action is still processing. Please wait..."));
player.playSound(player.getLocation(), Sound.NOTE_PIANO, 0.5f, 1);
return;
}
_processing.add(player);
if(event.getItem().equals(_itemEnterReviewMode))
{
if(isInReviewMode(player))
{
player.sendMessage(F.main(getName(), "You are already in " + F.item("review mode")));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
return;
}
ReviewData data = new ReviewData(player, getAvalibleLocation());
for(int i = 0; i < 9; i++)
{
player.getInventory().setItem(i, null);
}
ItemStack back = _itemPrevious.clone();
UtilInv.addDullEnchantment(back);
player.getInventory().setItem(0, back);
player.getInventory().setItem(1, _itemNext);
player.getInventory().setItem(3, _itemApprove);
player.getInventory().setItem(4, _itemDeny);
//player.getInventory().setItem(6, _itemFilter);
player.getInventory().setItem(8, _itemExitReviewMode);
_reviewers.put(player, data);
pasteBuild(player, true);
}
else if(event.getItem().equals(_itemExitReviewMode))
{
if(!isInReviewMode(player))
{
player.sendMessage(F.main(getName(), "You are not currently in " + F.item("review mode")));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
return;
}
for(int i = 0; i < 9; i++)
{
player.getInventory().setItem(i, null);
}
player.getInventory().setItem(0, _itemEnterReviewMode);
_reviewers.remove(player);
player.teleport(_spawn);
_processing.remove(player);
}
else if(!isInReviewMode(player))
{
player.sendMessage(F.main(getName(), "Invalid action!"));
player.sendMessage(F.main(getName(), "You are not currently in " + F.item("review mode")));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
return;
}
else if(event.getItem().equals(_itemApprove))
{
ReviewData reviewData = _reviewers.get(player);
MavericksBuildWrapper data = reviewData.getData();
if(data == null)
{
player.sendMessage(F.main(getName(), "Invalid action!"));
player.sendMessage(F.main(getName(), "You are currently not reviewing a build."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
return;
}
if(data.isReviewed())
{
player.sendMessage(F.main(getName(), "This build has already been reviewed!"));
player.sendMessage(F.main(getName(), "Contact the tech wizards if you want to change the"));
player.sendMessage(F.main(getName(), "state of the already reviewed build."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
return;
}
_repoApprove.add(data, player.getUniqueId()).thenCompose(BukkitFuture.accept((success) ->
{
if(success)
{
player.sendMessage(F.main(getName(), "Marked build as " + F.color("approved", C.cGreen) + "."));
player.playSound(player.getLocation(), Sound.NOTE_PLING, 1, 0);
_repoBuilds.setReviewed(_reviewers.get(player).getData().getBuildId(), true).thenCompose(BukkitFuture.accept((success2) ->
{
if(success2)
{
data.setReviewed(true);
player.sendMessage(F.main(getName(), "Marked build as " + F.item("processed") + "."));
player.playSound(player.getLocation(), Sound.NOTE_PLING, 1, 0);
player.sendMessage(F.main(getName(), "Loading next build..."));
clear(reviewData);
pasteBuild(player, true);
}
else
{
player.sendMessage(F.main(getName(), "Unable to mark the build as " + F.item("processed") + "!"));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
}
_processing.remove(player);
}));
}
else
{
player.sendMessage(F.main(getName(), "Unable to mark the build as " + F.color("approved", C.cGreen) + "!"));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
}
}));
}
else if(event.getItem().equals(_itemDeny))
{
MavericksBuildWrapper data = _reviewers.get(player).getData();
if(data == null)
{
player.sendMessage(F.main(getName(), "Invalid action!"));
player.sendMessage(F.main(getName(), "You are currently not reviewing a build."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
return;
}
if(data.isReviewed())
{
player.sendMessage(F.main(getName(), "This build has already been"));
player.sendMessage(F.main(getName(), "reviewed! Contact the tech wizards"));
player.sendMessage(F.main(getName(), "if you want to change the state of"));
player.sendMessage(F.main(getName(), "the already reviewed build."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
return;
}
_repoBuilds.setReviewed(_reviewers.get(player).getData().getBuildId(), true).thenCompose(BukkitFuture.accept((success) ->
{
if(success)
{
data.setReviewed(true);
player.sendMessage(F.main(getName(), "Marked build as " + F.color("denied", C.cRed) + "."));
player.playSound(player.getLocation(), Sound.NOTE_PLING, 1, 0);
player.sendMessage(F.main(getName(), "Loading next build..."));
clear(_reviewers.get(player));
pasteBuild(player, true);
}
else
{
player.sendMessage(F.main(getName(), "Unable to mark the build as " + F.color("denied", C.cRed) + "!"));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
}
_processing.remove(player);
}));
}
else if(event.getItem().equals(_itemFilter))
{
player.sendMessage(F.main(getName(), "Not yet implemented."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
}
else if(event.getItem().equals(_itemNext))
{
pasteBuild(player, true);
}
else if(event.getItem().equals(_itemPrevious))
{
pasteBuild(player, false);
}
}
public void pasteBuild(Player player, boolean next)
{
ReviewData review = _reviewers.get(player);
if(review == null)
{
player.sendMessage(F.main(getName(), "Invalid action!"));
player.sendMessage(F.main(getName(), "You are not currently in " + F.item("review mode")));
_processing.remove(player);
return;
}
MavericksBuildWrapper data = null;
if(next)
{
data = review.getNext();
}
else
{
data = review.getPrevious();
}
if(!next && data == null)
{
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0.5f);
player.sendMessage(F.main(getName(), "No previous builds available"));
ItemStack back = player.getInventory().getItem(0).clone();
UtilInv.addDullEnchantment(back);
player.getInventory().setItem(0, back);
_processing.remove(player);
return;
}
if(next && data == null)
{
player.sendMessage(F.main(getName(), "Pulling new data, please wait..."));
getNext((pulledData) ->
{
if(pulledData == null)
{
player.sendMessage(F.main(getName(), "No new data was found."));
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1, 0);
_processing.remove(player);
}
else
{
if(DEBUG) Bukkit.broadcastMessage("Displaying from DB -2");
try {
player.getInventory().setItem(0, _itemPrevious);
display(player, review, pulledData);
} catch(Exception e)
{
e.printStackTrace();
_processing.remove(player);
}
}
});
}
if(data != null)
{
if(DEBUG) Bukkit.broadcastMessage("Displaying fast");
display(player, review, data);
player.getInventory().setItem(0, _itemPrevious);
}
}
private void clear(ReviewData review)
{
if(review == null) return;
UtilBlock.startQuickRecording();
//Clear old blocks for stuff like lava and so on.
for(Block b : UtilBlock.getInBoundingBox(review.getAreaMin(), review.getAreaMax()))
{
UtilBlock.setQuick(_world, b.getX(), b.getY(), b.getZ(), 0, (byte) 0);
}
Location a = review.getAreaMin();
Location b = review.getAreaMax();
b.setY(a.getY());
// Floor
for(Block block : UtilBlock.getInBoundingBox(a, b, false))
{
UtilBlock.setQuick(_world, block.getX(), block.getY(), block.getZ(), 95, (byte) 1);
}
// Walls/edge
for(Block block : UtilBlock.getInBoundingBox(a, b, false, true, true, false))
{
UtilBlock.setQuick(_world, block.getX(), block.getY()+1, block.getZ(), 95, (byte) 0);
}
UtilBlock.stopQuickRecording();
List<Entity> list = review.getEntitiesInArea();
for(Entity e : list)
{
e.remove();
}
if(DEBUG) Bukkit.broadcastMessage("Cleared " + list.size() + " entities in area");
}
private void display(Player player, ReviewData review, MavericksBuildWrapper data)
{
Location loc = review.getLoc();
Location paste = review.getAreaMin().add(1, 1, 1);
loc.setDirection(OFFSET_VECTOR.clone().add(new Vector(0, 4, 0)));
clear(review);
if(DEBUG) Bukkit.broadcastMessage("Trying to parse from " + data.getDateStamp());
if(DEBUG) Bukkit.broadcastMessage("SBytes: " + data.getSchematicBytes().length + ", Schematic: " + data.getSchematic());
Schematic schematic = data.getSchematic();
SchematicData pasteData = schematic.paste(paste, false, false);
for(Entity e : pasteData.getEntities())
{
if(e instanceof Item)
{
//Don't despawn
e.setTicksLived(32768);
}
else
{
UtilEnt.Vegetate(e, true);
UtilEnt.ghost(e, true, false);
}
}
player.sendMessage(ArcadeFormat.Line);
String key = C.cGreen + C.Bold;
String value = C.cYellow + C.Bold;
SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss z");
player.sendMessage(key + "BuildId: " + value + data.getBuildId());
player.sendMessage(key + "Creator: " + value + data.getUUID());
player.sendMessage(key + "Last C Name: " + value + (data.hasNameSet() ? data.getName() : C.Italics + "Not Avalible"));
player.sendMessage(key + "Word: " + value + data.getTheme());
player.sendMessage(key + "Place: " + value + (data.getPlace() + 1));
player.sendMessage(key + "Points: " + value + data.getPoints());
player.sendMessage(key + "Date: " + value + dformat.format(new Date(data.getDateStamp())));
player.sendMessage(key + "Reviewed: " + value + data.isReviewed());
player.sendMessage(ArcadeFormat.Line);
player.setVelocity(new Vector(0,0,0));
player.setAllowFlight(true);
player.setFlying(true);
player.teleport(loc);
review.setData(data);
_processing.remove(player);
}
@EventHandler
public void onUpdateParticles(UpdateEvent event)
{
if (event.getType() != UpdateType.FAST) return;
for(ReviewData data : _reviewers.values())
{
if(data.getData() == null) continue;
if(!data.getData().hasParticles()) continue;
for(Entry<Vector, ParticleType> e : data.getData().getParticles().entrySet())
{
Location loc = data.getAreaMin().add(1, 1, 1).add(e.getKey());
ParticleType type = e.getValue();
int amount = 8;
if (type == ParticleType.HUGE_EXPLOSION ||
type == ParticleType.LARGE_EXPLODE ||
type == ParticleType.NOTE)
amount = 1;
UtilParticle.PlayParticleToAll(type, loc, 0.4f, 0.4f, 0.4f, 0, amount, ViewDist.LONG);
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event)
{
ReviewData data = _reviewers.get(event.getPlayer());
if(data != null)
{
for(Entity e : data.getEntitiesInArea()) e.remove();
for(Block b : UtilBlock.getInBoundingBox(data.getAreaMin(), data.getAreaMax()))
{
UtilBlock.setQuick(_world, b.getX(), b.getY(), b.getZ(), 0, (byte) 0);
}
}
exitReviewMode(event.getPlayer());
}
public boolean isInReviewMode(Player player)
{
return _reviewers.containsKey(player);
}
public void enterReviewMode(Player player)
{
if(isInReviewMode(player)) return;
}
public void exitReviewMode(Player player)
{
if(!isInReviewMode(player)) return;
_reviewers.remove(player);
}
public Location getAvalibleLocation()
{
for(int i = 0; i < 500; i++)
{
Location loc = _spawn.clone().add(100*i, 0, 0);
loc.setY(200);
if(isTaken(loc)) continue;
return loc;
}
return null;
}
private boolean isTaken(Location loc)
{
for(ReviewData data : _reviewers.values())
{
if(data.getData() == null) continue;
if(data.getLoc().equals(loc)) return true;
}
return false;
}
private boolean isTaken(MavericksBuildWrapper wrapper)
{
if(wrapper.isReviewed()) return true;
for(ReviewData data : _reviewers.values())
{
if(data.containsData(wrapper)) return true;
// if(data.getData() == null) continue;
// if(data.getData().equals(wrapper)) return true;
}
return false;
}
public void getNext(Consumer<MavericksBuildWrapper> consumer)
{
pullQueue(getNextIndex(), consumer);
}
public int getNextIndex()
{
for(int i = 0; i < _reviewQueue.size(); i++)
{
MavericksBuildWrapper wrapper = _reviewQueue.get(i);
if(isTaken(wrapper)) continue;
if(wrapper.isReviewed()) continue;
if(wrapper.getSchematic() == null) continue;
if(DEBUG) Bukkit.broadcastMessage("Found avalible index: " + i);
return i;
}
if(DEBUG) Bukkit.broadcastMessage("Found no avalible indexes, returning next one: " + _reviewQueue.size());
return _reviewQueue.size();
}
public void pullQueue(int index, Consumer<MavericksBuildWrapper> consumer)
{
if(_reviewQueue.size() > index)
{
consumer.accept(_reviewQueue.get(index));
if(DEBUG) Bukkit.broadcastMessage("Local queue is bigger then index");
return;
}
int offset = 0;
for(MavericksBuildWrapper build : _reviewQueue)
{
if(!build.isReviewed()) offset++;
}
if(DEBUG) Bukkit.broadcastMessage("Pulling from DB, limit: " + (index-_reviewQueue.size()+1) + ", offset " + offset);
_repoBuilds.getToReview(true, index-_reviewQueue.size()+1, offset).thenCompose(BukkitFuture.accept((list) ->
{
if(DEBUG) Bukkit.broadcastMessage("Retrived " + list.size() + " entries from DB");
_reviewQueue.addAll(list);
if(_reviewQueue.size() > index)
{
if(DEBUG) Bukkit.broadcastMessage("Found new entry to process!");
consumer.accept(_reviewQueue.get(index));
}
else
{
if(DEBUG) Bukkit.broadcastMessage("Still not enough though");
consumer.accept(null);
}
}));
}
}

View File

@ -0,0 +1,117 @@
package mineplex.mavericks.review;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import mineplex.core.mavericks.MavericksBuildWrapper;
/**
* A simple wrapper class used to hold build data related to a location and player.
*/
public class ReviewData
{
private Player _player;
private MavericksBuildWrapper _data;
private List<MavericksBuildWrapper> _logg = new ArrayList<>();
private Location _loc;
public ReviewData(Player player, Location loc)
{
_player = player;
_loc = loc.getBlock().getLocation().add(0.5, 0, 0.5);
}
public Player getPlayer()
{
return _player;
}
public Location getLoc()
{
return _loc.clone();
}
public MavericksBuildWrapper getData()
{
return _data;
}
public void setData(MavericksBuildWrapper data)
{
if(!_logg.contains(_data))
{
_logg.add(_data);
}
if(!_logg.contains(data))
{
_logg.add(data);
}
_data = data;
}
public MavericksBuildWrapper getPrevious()
{
int index = _logg.indexOf(_data);
if(index <= 0) return null;
MavericksBuildWrapper data = _logg.get(index-1);
if(data != null && data.isReviewed())
{
_data = data;
return getPrevious();
}
return data;
}
public MavericksBuildWrapper getNext()
{
int index = _logg.indexOf(_data);
if(index == -1) return null;
if(index+1 >= _logg.size()) return null;
MavericksBuildWrapper data = _logg.get(index+1);
if(data != null && data.isReviewed())
{
_data = data;
return getNext();
}
return data;
}
public boolean containsData(MavericksBuildWrapper data)
{
return _logg.contains(data);
}
public Location getAreaMin()
{
return _loc.getBlock().getLocation().add(MavericksReviewManager.OFFSET_VECTOR).subtract(1, 1, 12);
}
public Location getAreaMax()
{
return getAreaMin().add(24, 28, 24);
}
public List<Entity> getEntitiesInArea()
{
List<Entity> list = new ArrayList<>();
for(Entity e : _loc.getWorld().getEntities())
{
if(e instanceof Player) continue;
if(isInsideArea(e.getLocation())) list.add(e);
}
return list;
}
public boolean isInsideArea(Location loc)
{
return loc.toVector().isInAABB(getAreaMin().toVector(), getAreaMax().toVector());
}
}

View File

@ -0,0 +1,87 @@
package mineplex.mavericks.review;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.common.Rank;
import mineplex.core.common.util.UtilServer;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.HoverEvent.Action;
import net.md_5.bungee.api.chat.TextComponent;
/**
* A simple manager for formating the chat
*/
public class SimpleChatManager extends MiniPlugin
{
private CoreClientManager _coreClientManager;
private AchievementManager _achievementManager;
public SimpleChatManager(JavaPlugin plugin, CoreClientManager coreClientManager, AchievementManager achivementManager)
{
super("Chat Format Manager", plugin);
_coreClientManager = coreClientManager;
_achievementManager = achivementManager;
}
@EventHandler
public void PlayerChat(AsyncPlayerChatEvent event)
{
if (event.isCancelled())
return;
Player player = event.getPlayer();
String playerName = player.getName();
Rank rank = _coreClientManager.Get(player).GetRank();
if(_coreClientManager.Get(player).isDisguised())
rank = _coreClientManager.Get(player).getDisguisedRank();
//Level Prefix
String levelStr = _achievementManager.getMineplexLevel(player, rank);
//Rank Prefix
String rankStr = "";
if (rank != Rank.ALL)
rankStr = rank.getTag(true, true) + " ";
TextComponent rankComponent = new TextComponent(rankStr);
TextComponent playerNameText = new TextComponent(ChatColor.YELLOW + playerName);
TextComponent component = new TextComponent();
rankComponent.setHoverEvent(new HoverEvent(Action.SHOW_TEXT, new ComponentBuilder(rank.getColor() + rank.getTag(true, true) + ChatColor.WHITE + "\n" + rank.getDescription()).create()));
component.setText(levelStr);
component.addExtra(rankComponent);
component.addExtra(playerNameText);
component.addExtra(" " + ChatColor.WHITE + event.getMessage());
// JsonMessage jsonMessage = new JsonMessage(levelStr)
// .extra(JSONObject.escape(rankStr)).hover("show_text", rank.getColor() + rank.getTag(true, true) + ChatColor.WHITE + "\n" + rank.getDescription())
// .add(JSONObject.escape(C.cYellow + playerName + " " + ChatColor.WHITE + event.getMessage()));
for (Player other : UtilServer.getPlayers())
{
// event.setMessage(event.getMessage());
// event.setFormat(levelStr + rankStr + C.cYellow + playerName + " " + C.cWhite + "%2$s");
if(!event.isCancelled())
other.spigot().sendMessage(component);
}
Bukkit.getConsoleSender().sendMessage(component.toLegacyText());
event.setCancelled(true);
}
}

View File

@ -0,0 +1,10 @@
package nautilus.game.arcade;
import mineplex.core.common.util.C;
/**
* Copy from {@link nautilus.game.arcade.ArcadeFormat}
*/
public class ArcadeFormat
{
public static String Line = C.cDGreen + C.Strike + "=============================================";
}

View File

@ -37,6 +37,8 @@
<module>Mineplex.StaffServer</module>
<module>Mineplex.Votifier</module>
<module>Nautilus.Game.Arcade</module>
<module>mavericks-review-hub</module>
</modules>
<repositories>