file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1
value | extension stringclasses 1
value | repo_name stringclasses 767
values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767
values | repo_pushed_at stringclasses 767
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Utils.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/Utils.java | package me.patothebest.gamecore.util;
import com.google.common.io.ByteStreams;
import me.patothebest.gamecore.PluginConfig;
import me.patothebest.gamecore.actionbar.ActionBar;
import me.patothebest.gamecore.chat.DefaultFontInfo;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.kit.WrappedPotionEffect;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.vector.ArenaLocation;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import sun.net.www.protocol.http.Handler;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.SplittableRandom;
import java.util.TreeMap;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static me.patothebest.gamecore.PluginConfig.*;
/**
* A collection of many utilities
*/
public class Utils {
private final static SplittableRandom RANDOM = new SplittableRandom();
public final static String SERVER_VERSION = ServerVersion.getVersion();
public final static File PLUGIN_DIR = new File("plugins" + File.separatorChar + PLUGIN_NAME + File.separatorChar);
private static final DecimalFormat ONE_DECIMAL_FORMAT = new DecimalFormat("0.0");
private static final DecimalFormat TWO_DECIMAL_FORMAT = new DecimalFormat("0.00");
public static final String DECRYPT_KEY = "TheTowers";
private static final String USER_ID = "%%__USER__%%";
//private static String USER_ID = new CryptoUtil().decryptSilently(DECRYPT_KEY, "QllFvMZZ/BY=");
//private static String USER_ID = new CryptoUtil().decryptSilently(DECRYPT_KEY, "/dB5CK74bTQ=");
private static Constructor<?> gameProfileConstructor;
private static Constructor<?> propertyConstructor;
private static Logger logger = Logger.getLogger("Minecraft"); // will be replaced
private static final Pattern DATE_VALIDATION = Pattern.compile("^(?:\\d+[dhmsw])+$");
private static final Pattern DATE_PART = Pattern.compile("(\\d+)([dhmsw])");
private static final NavigableMap<Long, String> SUFFIXES = new TreeMap<>();
static {
SUFFIXES.put(1_000L, "k");
SUFFIXES.put(1_000_000L, "M");
SUFFIXES.put(1_000_000_000L, "G");
SUFFIXES.put(1_000_000_000_000L, "T");
SUFFIXES.put(1_000_000_000_000_000L, "P");
SUFFIXES.put(1_000_000_000_000_000_000L, "E");
}
public static void setLogger(Logger logger) {
Utils.logger = logger;
}
private Utils () {}
/**
* Sets final field to the provided value
*
* @param clazz
* @param fieldName
* @param newValue
*
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setStaticFinalField(Class<?> clazz, String fieldName, Object newValue) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
setFinalField(clazz.getDeclaredField(fieldName), null, newValue);
}
/**
* Sets final field to the provided value
*
* @param field - the field which should be modified
* @param obj - the object whose field should be modified
* @param newValue - the new value for the field of obj being modified
*
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setFinalField(Field field, Object obj, Object newValue) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
setAccessible(Field.class.getDeclaredField("modifiers")).setInt(field, field.getModifiers() & ~Modifier.FINAL);
setAccessible(Field.class.getDeclaredField("root")).set(field, null);
setAccessible(Field.class.getDeclaredField("overrideFieldAccessor")).set(field, null);
setAccessible(field).set(obj, newValue);
}
/**
* Gets field reflectively
*
* @param clazz
* @param fieldName
* @param obj
*
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getFieldValue(Class<?> clazz, String fieldName, Object obj) {
try {
return (T) setAccessible(clazz.getDeclaredField(fieldName)).get(obj);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not get field value " + fieldName + " of " + clazz.getName(), t);
}
return null;
}
/**
* Gets field reflectively
*
* @param clazz
* @param fieldName
* @param obj
*
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getFieldValueNotDeclared(Class<?> clazz, String fieldName, Object obj) {
try {
return (T) setAccessible(clazz.getField(fieldName)).get(obj);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not get field value " + fieldName + " of " + clazz.getName(), t);
}
return null;
}
/**
* Gets Method reflectively
*
* @param clazz
* @param methodName
* @param obj
*
* @return
*/
private static Method getMethodValue(Class<?> clazz, String methodName, Class<?>... obj) {
try {
return clazz.getDeclaredMethod(methodName, obj);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not get method value " + methodName + " of " + clazz.getName(), t);
}
return null;
}
/**
* Gets Method reflectively
*
* @param clazz
* @param methodName
* @param obj
*
* @return
*/
public static Method getMethodNotDeclaredValue(Class<?> clazz, String methodName, Class<?>... obj) {
try {
return clazz.getMethod(methodName, obj);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not get method value " + methodName + " of " + clazz.getName(), t);
}
return null;
}
/**
* Sets accessibleobject accessible state an returns this object
*
* @param <T>
* @param object
*
* @return
*/
private static <T extends AccessibleObject> T setAccessible(T object) {
object.setAccessible(true);
return object;
}
/**
* Sets field reflectively
*
* @param clazz
* @param fieldName
* @param obj
* @param value
*/
public static void setFieldValue(Class<?> clazz, String fieldName, Object obj, Object value) {
try {
setAccessible(clazz.getDeclaredField(fieldName)).set(obj, value);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not set field value " + fieldName + " of " + clazz.getName(), t);
}
}
/**
* Sets field reflectively
*
* @param clazz
* @param fieldName
* @param obj
* @param value
*/
public static void setFieldValueNotDeclared(Class<?> clazz, String fieldName, Object obj, Object value) {
try {
setAccessible(clazz.getField(fieldName)).set(obj, value);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Could not set field value " + fieldName + " of " + clazz.getName(), t);
}
}
/**
* Gets a method from the specified class
* If it cannot retrieve the method, it will return null
*
* @param clazz the class
* @param name the name of the method
* @param parameterTypes the parameter array
*
* @return the {@code Method} object for the method of this class matching the specified name and parameters
*/
public static Method getMethodOrNull(Class<?> clazz, String name, Class<?>... parameterTypes) {
if (clazz == null) {
return null;
}
try {
return clazz.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* Gets a field from the specified class
* If it cannot retrieve the field, it will return null
*
* @param clazz the class
* @param name the name of the field
*
* @return the {@code Field} object for the specified field in this class
*/
public static Field getFieldOrNull(Class<?> clazz, String name) {
if (clazz == null) {
return null;
}
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* Invoke a static method
*
* @param clazz
* @param method
* @param parameterClasses
* @param parameters
*
* @return
*/
public static Object invokeStaticMethod(Class<?> clazz, String method, Class<?>[] parameterClasses, Object... parameters) {
return invokeStaticMethod(getMethodValue(clazz, method, parameterClasses), parameters);
}
/**
* Invoke a static method
*
* @param method
* @param parameters
*
* @return
*/
private static Object invokeStaticMethod(Method method, Object... parameters) {
try {
return method.invoke(null, parameters);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not invoke static method " + method.getName() + "!", e);
}
return null;
}
/**
* Invoke a non static method
*
* @param object
* @param method
* @param parameterClasses
* @param parameters
*
* @return
*/
public static Object invokeMethod(Object object, String method, Class<?>[] parameterClasses, Object... parameters) {
return invokeMethod(object, getMethodValue(object.getClass(), method, parameterClasses), parameters);
}
/**
* Invoke a non static method
*
* @param object
* @param method
* @param parameters
*
* @return
*/
public static Object invokeMethod(Object object, Method method, Object... parameters) {
try {
return method.invoke(object, parameters);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not invoke method " + method.getName() + "!", e);
}
return null;
}
/**
* Returns a random number using Java's Random
*
* @param next Maximum value.
*
* @return Random integer
* @see java.util.Random#nextInt(int)
*/
public static int random(int next) {
return RANDOM.nextInt(next);
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param number1 Value number 1
* @param number2 Value number 2.
*
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int number1, int number2) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
return Math.min(number1, number2) + (int) Math.round(-0.5f + (1 + Math.abs(number1 - number2)) * RANDOM.nextDouble());
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param number1 Value number 1
* @param number2 Value number 2.
*
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static double randDouble(double number1, double number2) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
return Math.min(number1, number2) + (-0.5f + (1 + Math.abs(number1 - number2)) * RANDOM.nextDouble());
}
/**
* Returns a craftbukkit CBS class
*
* @param nmsClassString the class name
*
* @return the NMS class
*/
public static Class<?> getCBSClass(String nmsClassString) {
try {
return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + nmsClassString);
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Could not get CBS class " + nmsClassString + "!", e);
}
return null;
}
/**
* Returns a minecraft NMS class
*
* @param nmsClassString the class name
*
* @return the NMS class
*/
public static Class<?> getNMSClass(String nmsClassString) {
try {
return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + nmsClassString);
} catch (ClassNotFoundException e) {
logger.log(Level.SEVERE, "Could not NMS CBS class " + nmsClassString + "!", e);
}
return null;
}
/**
* Returns a craftbukkit CBS class
*
* @param nmsClassString the class name
*
* @return the NMS class
*/
public static Class<?> getCBSClassOrNull(String nmsClassString) {
try {
return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + nmsClassString);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Returns a minecraft NMS class
*
* @param nmsClassString the class name
*
* @return the NMS class
*/
public static Class<?> getNMSClassOrNull(String nmsClassString) {
try {
return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + nmsClassString);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Sends a packet to the player via reflection
*
* @param p the bukkit player
* @param packet the packet object
*/
public static void sendPacket(Player p, Object packet) {
try {
//noinspection ConstantConditions
getNMSClass("PlayerConnection").getMethod("sendPacket", getNMSClass("Packet")).invoke(getNMSClass("EntityPlayer").getDeclaredField("playerConnection").get(getHandle(p)), packet);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not send packet " + packet.getClass() + "!", e);
}
}
/**
* Get's the player handle, also known as the EntityPlayer
*
* @param player the bukkit player
*
* @return the NMS player object
*/
public static Object getHandle(Player player) {
try {
return player.getClass().getMethod("getHandle").invoke(player);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not get player's handle!", e);
}
return null;
}
/**
* Creates a new object instance
*
* @param tClass the object class
* @param constructor the object constructor to initialize the class
* @param <T> the object type
*
* @return the created object
*/
public static <T> T createInstance(Class<T> tClass, Object... constructor) {
try {
Class[] classes = new Class[constructor.length];
for (int i = 0; i < constructor.length; i++) {
classes[i] = constructor[i].getClass();
}
Constructor<T> ctor = tClass.getConstructor(classes);
return ctor.newInstance(constructor);
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not create a new instance of " + tClass.getName() + "!", e);
}
return null;
}
/**
* Returns a serialized itemstack into string form
* <p>
* The serialized itemstack will look like:
* material:data,amount
*
* @param itemStack the itemstack to serialize
*
* @return the serialized itemstack
*/
public static String itemStackToString(final ItemStack itemStack) {
return (itemStack != null) ? (itemStack.getType() + ":" + itemStack.getDurability() + "," + itemStack.getAmount()) : null;
}
/**
* Returns an itemstack from a string
* <p>
* The format can be:
* - material
* - material:data
* - material,amount
* - material:data,amount
*
* @param string the serialized itemstack
*
* @return the deserialized itemtack
*/
public static ItemStack itemStackFromString(String string) {
if (string == null) {
return null;
}
String materialName = string;
int amount = 1;
if (materialName.contains(",")) {
materialName = string.substring(0, string.indexOf(','));
amount = isNumber(string.substring(string.indexOf(',') + 1)) ? Integer.parseInt(string.substring(string.indexOf(',') + 1)) : 1;
}
int data = materialName.indexOf(':');
if (data != -1 && isNumber(materialName.substring(data + 1)) && Integer.parseInt(materialName.substring(data + 1)) == 0) {
materialName = materialName.substring(0, data);
}
me.patothebest.gamecore.itemstack.Material material = me.patothebest.gamecore.itemstack.Material.matchMaterial(materialName).orElse(null);
//printDebug("PARSING ITEMS", "Original item: " + string, "Parsed material: " + (material == null ? "null" : material.toString()));
return material != null ? new ItemStackBuilder(material).amount(amount) : null;
}
/**
* Parses an item from config using SkyWarsReloaded format
* <p>
* The first value is the item, this should be the material
* name (as found on http://jd.bukkit.org/rb/apidocs/org/bukkit/Material.html)
* The second value is the quantity that will show up in the chest.
* <p>
* For wood, potions, wool, dirt, etc (Any item that has type data),
* you can use a : followed by the numerical data for the item you want.
* For example wood:2 would give you birch wood planks. You can find
* data values at: http://minecraft-ids.grahamedgecombe.com/
* <p>
* Potion data values can be found at: http://minecraft.gamepedia.com/Potion
* <p>
* Enchantments can be added using the enchantment name (written with no spaces)
* followed by a : and then the enchantment level number.
*
* @param itemData the item data
* @return the parsedItem
*/
public static ItemStack parseItem(String[] itemData) {
if (itemData.length < 2) {
return null;
}
ItemStackBuilder itemStack;
if (itemData[0].contains(":")) {
String[] materialAndData = itemData[0].split(":");
Material material = Material.getMaterial(materialAndData[0].toUpperCase());
int amount = Integer.parseInt(itemData[1]);
if (amount < 1) {
return null;
}
short data = (short) Integer.parseInt(materialAndData[1].toUpperCase());
itemStack = new ItemStackBuilder(material).amount(amount).data(data);
} else {
itemStack = new ItemStackBuilder(Material.getMaterial(itemData[0].toUpperCase())).amount(Integer.parseInt(itemData[1]));
}
if (itemData.length > 2) {
for (int x = 2; x < itemData.length; x++) {
String[] splitString = itemData[x].split(":");
if (splitString[0].equalsIgnoreCase("name")) {
itemStack.name(splitString[1]);
} else if (splitString[0].equalsIgnoreCase("color")) {
if (itemStack.getType().name().startsWith("LEATHER")) {
itemStack.color(getColor(splitString[1]));
}
} else {
itemStack.addUnsafeEnchantment(getEnchant(splitString[0]), Integer.parseInt(splitString[1]));
}
}
}
return itemStack;
}
/**
* Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor.
*
* @param playerInventory to turn into an array of strings.
* @return Array of strings: [ main content, armor content ]
* @throws IllegalStateException
*/
public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException {
//get the main content part, this doesn't return the armor
String content = toBase64(playerInventory);
String armor = itemStackArrayToBase64(playerInventory.getArmorContents());
return new String[] { content, armor };
}
/**
*
* A method to serialize an {@link ItemStack} array to Base64 String.
*
* <p />
*
* Based off of {@link #toBase64(Inventory)}.
*
* @param items to turn into a Base64 String.
* @return Base64 string of the items.
* @throws IllegalStateException
*/
public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory
dataOutput.writeInt(items.length);
// Save every element in the list
for (ItemStack item : items) {
dataOutput.writeObject(item);
}
// Serialize that array
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
/**
* A method to serialize an inventory to Base64 string.
*
* <p />
*
* Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub.
*
* <a href="https://gist.github.com/aadnk/8138186">Original Source</a>
*
* @param inventory to serialize
* @return Base64 string of the provided inventory
* @throws IllegalStateException
*/
public static String toBase64(Inventory inventory) throws IllegalStateException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory
dataOutput.writeInt(inventory.getSize());
// Save every element in the list
for (int i = 0; i < inventory.getSize(); i++) {
dataOutput.writeObject(inventory.getItem(i));
}
// Serialize that array
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
/**
*
* A method to get an {@link Inventory} from an encoded, Base64, string.
*
* <p />
*
* Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub.
*
* <a href="https://gist.github.com/aadnk/8138186">Original Source</a>
*
* @param data Base64 string of data containing an inventory.
* @return Inventory created from the Base64 string.
* @throws IOException
*/
public static Inventory fromBase64(String data) throws IOException {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());
// Read the serialized inventory
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, (ItemStack) dataInput.readObject());
}
dataInput.close();
return inventory;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e);
}
}
/**
* Gets an array of ItemStacks from Base64 string.
*
* <p />
*
* Base off of {@link #fromBase64(String)}.
*
* @param data Base64 string to convert to ItemStack array.
* @return ItemStack array created from the Base64 string.
* @throws IOException
*/
public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack[] items = new ItemStack[dataInput.readInt()];
// Read the serialized inventory
for (int i = 0; i < items.length; i++) {
items[i] = (ItemStack) dataInput.readObject();
}
dataInput.close();
return items;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e);
}
}
/**
*
* A method to serialize an {@link ItemStack} array to Base64 String.
*
* <p />
*
* Based off of {@link #toBase64(Inventory)}.
*
* @param items to turn into a Base64 String.
* @return Base64 string of the items.
* @throws IllegalStateException
*/
public static String potionEffectArrayToBase64(WrappedPotionEffect[] items) throws IllegalStateException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory
dataOutput.writeInt(items.length);
// Save every element in the list
for (WrappedPotionEffect item : items) {
dataOutput.writeObject(item);
}
// Serialize that array
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e);
}
}
/**
* Gets an array of wrapped potion effects from Base64 string.
*
* <p />
*
* Base off of {@link #fromBase64(String)}.
*
* @param data Base64 string to convert to ItemStack array.
* @return WrappedPotionEffect array created from the Base64 string.
* @throws IOException
*/
public static WrappedPotionEffect[] potionEffectsFromBase64(String data) throws IOException {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
WrappedPotionEffect[] items = new WrappedPotionEffect[dataInput.readInt()];
// Read the serialized inventory
for (int i = 0; i < items.length; i++) {
items[i] = (WrappedPotionEffect) dataInput.readObject();
}
dataInput.close();
return items;
} catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e);
}
}
/**
* Gets the user id who bought the plugin
*
* @return the user who bought the plugin
*/
public static String getUserId() {
return USER_ID;
}
/**
* Opens a connection with reflection
*
* @param url the url
*
* @return the url connection
*/
public static URLConnection openConnectionReflectively(URL url) {
return (URLConnection) invokeMethod(new Handler(), setAccessible(getMethodOrNull(Handler.class, "openConnection", URL.class)), url);
}
/**
* Schedules to disable a plugin
*
* @param plugin the plugin to disable
*/
public static void scheduleToDisable(Plugin plugin) {
new WrappedBukkitRunnable() {
@Override
public void run() {
Bukkit.getPluginManager().disablePlugin(plugin);
}
}.runTask(plugin);
}
/**
* Gets an enum element from its name
*
* @param enumClass the enum class
* @param enumString the element's name
* @param <E> the element type
*
* @return the element
*/
public static <E extends Enum<E>> E getEnumValueFromString(Class<E> enumClass, String enumString) {
return getEnumValueFromString(enumClass, enumString, null);
}
/**
* Gets an enum element from its name
*
* @param enumClass the enum class
* @param enumString the element's name
* @param defaultEnumValue the value to return when no value is found
* @param <E> the element type
*
* @return the element
*/
public static <E extends Enum<E>> E getEnumValueFromString(Class<E> enumClass, String enumString, E defaultEnumValue) {
for (E enumElement : EnumSet.allOf(enumClass)) {
if (enumElement.name().equalsIgnoreCase(enumString)) {
return enumElement;
}
}
return defaultEnumValue;
}
/**
* Gets an enum element from its name
*
* @param enumClass the enum class
* @param enumString the element's name
*
* @return the element
*/
public static Object getEnumObjectRaw(Class<? extends Enum> enumClass, String enumString) {
Enum[] enumConstants = enumClass.getEnumConstants();
for (Enum enumConstant : enumConstants) {
if (enumConstant.name().equals(enumString)) {
return enumConstant;
}
}
return null;
}
/**
* Get all the zip files in a directory
*
* @param directory the main directory
* @param subDirectory the subdirectory
*
* @return the list of files
*/
public static ArrayList<String> getZipFilesFromDirectory(String directory, String subDirectory) {
final File folder = new File(directory + File.separator + subDirectory);
// validate if the folder actually exists
if (!folder.exists()) {
return null;
}
// create the list of files we are going to return
final ArrayList<String> files = new ArrayList<>();
// get all the files in the folder and
// validate if the array is empty
File[] listFiles = folder.listFiles();
assert listFiles != null;
for (int length = listFiles.length, i = 0; i < length; ++i) {
final File file = listFiles[i];
// skip directories
if (!file.isFile()) {
continue;
}
// get the file's name
String name = file.getName();
if (name.length() >= 5) {
// get the file extension
name = name.substring(name.length() - 4);
// validate if the file is a zip file
if (name.equals(".zip")) {
// add the file to the list
files.add(file.getName().substring(0, file.getName().length() - 4));
}
}
}
return files;
}
/**
* Concatenate two arrays
*
* @param a first array
* @param b second array
* @param <T> array type
*
* @return concatenated array
*/
public static <T> T[] concatenateArray(T[] a, T[] b) {
int aLen = a.length;
int bLen = b.length;
// create the new array
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
// copy the old arrays into the new array
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
/**
* Concatenate two arrays
*
* @param a first array
* @param b second array
* @param <T> array type
*
* @return concatenated array
*/
public static <T> T[] concatenateArray(T[] a, T[] b, Class<T> arrayClass) {
int aLen = a.length;
int bLen = b.length;
// create the new array
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(arrayClass, aLen + bLen);
// copy the old arrays into the new array
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
/**
* Combines two lists
*
* @param a first array
* @param b second array
* @param <T> list type
*
* @return combined list
*/
public static <T> List<T> combineLists(List<T> a, List<T> b) {
return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList());
}
/**
* Sorts a {@link Map} of String, Integer by
* the highest values
*
* @param map the map
* @return the sorted list
*/
public static List<Map.Entry<String, Integer>> sortMap(Map<String, Integer> map) {
ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
return entries;
}
/**
* Create a directory if it doesn't exist
*
* @param dir the directory
*
* @return the directory
*/
public static File createDirectoryIfNotExists(File dir) {
// validate if the directory exists
if (!dir.exists()) {
// attempt to create the directory
if (dir.mkdirs()) {
logger.log(Level.INFO, "Successfully created directory " + dir.getAbsolutePath());
} else {
logger.log(Level.SEVERE, "Failed to create directory");
}
}
return dir;
}
/**
* Unzip a file
*
* @param zipFile input zip file
* @param outputFolder zip file output folder
*/
public static boolean unZip(String zipFile, String outputFolder) {
File directory = new File(outputFolder);
// if the output directory doesn't exist, create it
if (!directory.exists())
directory.mkdirs();
// buffer for read and write data to file
byte[] buffer = new byte[2048];
try {
FileInputStream fInput = new FileInputStream(zipFile);
ZipInputStream zipInput = new ZipInputStream(fInput);
ZipEntry entry = zipInput.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
File file = new File(outputFolder + File.separator + entryName);
//System.out.println("Unzip file " + entryName + " to " + file.getAbsolutePath());
// create the directories of the zip directory
if (entry.isDirectory()) {
File newDir = new File(file.getAbsolutePath());
if (!newDir.exists()) {
boolean success = newDir.mkdirs();
if (!success) {
logger.log(Level.SEVERE, "Problem creating folder: " + newDir.getName());
}
}
} else {
FileOutputStream fOutput = new FileOutputStream(file);
int count;
while ((count = zipInput.read(buffer)) > 0) {
// write 'count' bytes to the file output stream
fOutput.write(buffer, 0, count);
}
fOutput.close();
}
// close ZipEntry and take the next one
zipInput.closeEntry();
entry = zipInput.getNextEntry();
}
// close the last ZipEntry
zipInput.closeEntry();
zipInput.close();
fInput.close();
return true;
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not unzip file " + zipFile + "!", e);
return false;
}
}
/**
* Delete a folder with subfolders
*
* @param folder the folder
*/
public static void deleteFolder(final File folder) {
// validate if the folder exists
if (!folder.exists()) {
return;
}
final File[] files = folder.listFiles();
// delete files if any
if (files != null) {
File[] array;
for (int length = (array = files).length, i = 0; i < length; ++i) {
final File f = array[i];
// fist validate if it is a subfolder or a file
if (f.isDirectory()) {
// delete all the files of the subfolder
deleteFolder(f);
} else {
// delete the file
f.delete();
}
}
}
// delete the folder
folder.delete();
}
/**
* Copy a file
*
* @param source source file
* @param dest destination file
*
* @throws IOException in case any errors
*/
public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
try (InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(dest)) {
// create the streams
// create the byte buffer
byte[] buf = new byte[1024];
int bytesRead;
// read the bytes from the source file
while ((bytesRead = input.read(buf)) > 0) {
// write the bytes from the buffer to the destination file
output.write(buf, 0, bytesRead);
}
}
}
/**
* Writes a file's contents to a file writer
*
* @param bufferedWriter the writer to write to
* @param inputStream the fileinputstream to read
*/
public static void writeFileToWriter(BufferedWriter bufferedWriter, InputStream inputStream) throws IOException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader input = new BufferedReader(reader);
String currentLine;
while ((currentLine = input.readLine()) != null) {
bufferedWriter.write(currentLine + "\n");
}
input.close();
}
/**
* Copies a folder
*
* @param src the source folder
* @param dest the folder where the output will be
*
* @throws IOException if there's any error
*/
private static void copyFolder(final File src, final File dest) throws IOException {
if (src.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
}
final String[] files = src.list();
if (files.length > 0) {
for (final String file : files) {
final File srcFile = new File(src, file);
final File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
}
} else {
final InputStream in = new FileInputStream(src);
final OutputStream out = new FileOutputStream(dest);
final byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
/**
* Compresses a directory in zip format
*
* @param directoryToZip the directory we are going to zip
* @param zipLocation the zip file location
*/
public static void zipIt(File directoryToZip, File zipLocation) {
List<File> fileList = new ArrayList<>();
getAllFiles(directoryToZip, fileList);
writeZipFile(zipLocation, directoryToZip, fileList);
}
/**
* Adds all the files in a directory to a list
*
* @param dir the directory
* @param fileList the list of files we are going to add the files in
*/
private static void getAllFiles(File dir, List<File> fileList) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.getName().endsWith(".lock")) {
fileList.add(file);
}
if (file.isDirectory()) {
getAllFiles(file, fileList);
}
}
}
/**
* Writes the zip file
*
* @param directoryToZip the zip file we are going to put all the compressed files in
* @param fileList the list of files that we are going to compress
*/
private static void writeZipFile(File directoryToZip, File mainDirectory, List<File> fileList) {
try (FileOutputStream fos = new FileOutputStream(directoryToZip);
ZipOutputStream zos = new ZipOutputStream(fos)){
for (File file : fileList) {
if (file.isDirectory()) {
addFolderToZip(mainDirectory, file, zos);
} else {
addFileToZip(mainDirectory, file, zos);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not create zip file " + directoryToZip + "!", e);
}
}
/**
* Adds the file to a zip file
*
* @param mainDirectory the folder where all the files are located
* @param file the file to add to the zip file
* @param zos the outputstream we are going to write into
*
* @throws IOException if there are any errors
*/
private static void addFileToZip(File mainDirectory, File file, ZipOutputStream zos) throws IOException {
FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ);
InputStream fis = Channels.newInputStream(fileChannel);
// we want the zipEntry's path to be a relative path that is relative
// to the directory being zipped, so chop off the rest of the path
String zipFilePath = file.getPath().substring(mainDirectory.getPath().length() + 1);
//System.out.println(zipFilePath);
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
try {
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error reading file " + file.getName(), e);
}
zos.closeEntry();
fis.close();
}
/**
* Adds the folder to a zip file
*
* @param mainDirectory the folder where all the files are located
* @param file the file to add to the zip file
* @param zos the outputstream we are going to write into
*
* @throws IOException if there are any errors
*/
private static void addFolderToZip(File mainDirectory, File file, ZipOutputStream zos) throws IOException {
// we want the zipEntry's path to be a relative path that is relative
// to the directory being zipped, so chop off the rest of the path
String zipFilePath = file.getPath().substring(mainDirectory.getPath().length() + 1) + "/";
//System.out.println(zipFilePath);
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
zos.closeEntry();
}
/**
* Gets a random element from a stream
*
* @param stream the stream
* @param <E> the stream type
*
* @return the randomly picked element
*/
public static <E> E getRandomElementFromStream(Stream<E> stream) {
return getRandomElementFromList(stream.collect(Collectors.toList()));
}
/**
* Gets a random element from a list
*
* @param list the list
* @param <E> the list type
*
* @return the randomly picked element
*/
public static <E> E getRandomElementFromList(List<E> list) {
if(list.isEmpty()) {
return null;
}
// RANDOM.nextDouble() returns a number greater than or equal to 0.0 and less than 1
return list.get((int) (RANDOM.nextDouble() * list.size()));
}
/**
* Gets a random element from a collection
*
* @param collection the list
* @param <E> the collection type
*
* @return the randomly picked element
*/
public static <E> E getRandomElementFromCollection(Collection<E> collection) {
return collection.stream().skip((int) (collection.size() * RANDOM.nextDouble())).findFirst().orElse(null);
}
/**
* Copies a file from inside the jar
*
* @param plugin the plugin
* @param resource the file inside the jar
*
* @return the copied file
*/
public static File loadResource(Plugin plugin, String resource) {
return loadResource(plugin, resource, plugin.getDataFolder(), resource);
}
/**
* Copies a file from inside the jar
*
* @param plugin the plugin
* @param resource the file inside the jar
*
* @return the copied file
*/
public static File loadResource(Plugin plugin, String resource, File folder, String finalName) {
// create the output folder if it doesn't exist
if (!folder.exists()) {
folder.mkdir();
}
File resourceFile = new File(folder, finalName);
try {
// checks if the file already exists to
// prevent overriding already written files
if (!resourceFile.exists()) {
// actually create a file we can use to write in
resourceFile.createNewFile();
// copy all the bytes from the original file
try (InputStream in = plugin.getResource(resource);
OutputStream out = new FileOutputStream(resourceFile)) {
ByteStreams.copy(in, out);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// returns the copied file object
return resourceFile;
}
/**
* Reads a file as a string
*
* @param file the file to read
* @return the file as a string
*/
public static String readFileAsString(File file) {
StringBuilder buffer = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String temp;
while ((temp = reader.readLine()) != null) {
buffer.append(temp).append('\n');
}
} catch(IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* List directory contents for a resource folder. Not recursive.
* This is basically a brute-force implementation.
* Works for regular files and also JARs.
*
* @param clazz Any java class that lives in the same place as the resources you want.
* @param path Should end with "/", but not start with one.
*
* @return Just the name of each member item, not the full paths.
* @throws URISyntaxException
* @throws IOException
* @author Greg Briggs
*/
public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
URL dirURL = clazz.getClassLoader().getResource(path);
if (dirURL != null && dirURL.getProtocol().equals("file")) {
// A file path: easy enough
return new File(dirURL.toURI()).list();
}
if (dirURL == null) {
/*
* In case of a jar file, we can't actually find a directory.
* Have to assume the same jar as clazz.
*/
String me = clazz.getName().replace(".", "/") + ".class";
dirURL = clazz.getClassLoader().getResource(me);
}
if (dirURL.getProtocol().equals("jar")) {
// A JAR path
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
Set<String> result = new HashSet<>(); //avoid duplicates in case it is a subdirectory
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(path)) { //filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}
throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
/**
* Returns the url contents as as string
*
* @param url the url to query
* @param charset the charset
* @return the url contents
* @throws IOException if anything fails
*/
public static String urlToString(URL url, Charset charset) throws IOException{
try (InputStream in = url.openStream()) {
InputStreamReader inR = new InputStreamReader(in, charset);
BufferedReader buf = new BufferedReader(inR);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = buf.readLine()) != null) {
stringBuilder.append(line).append('\n');
}
return stringBuilder.toString();
}
}
/**
* Checks if a string array contains the specified string
*
* @param array the string array
* @param string the string
*
* @return if the array contains the string
*/
public static boolean containsString(String[] array, String string) {
for (String anArray : array) {
if (anArray.equalsIgnoreCase(string)) {
return true;
}
}
return false;
}
/**
* Checks if a string is a number
*
* @param number the string to validate
*
* @return true if its a number
*/
public static boolean isNumber(String number) {
try {
Integer.parseInt(number);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Transforms a DyeColor into a ChatColor
*
* @param color the dye color
*
* @return the bukkit chat color
*/
public static ChatColor getColorFromDye(DyeColor color) {
switch (color) {
case WHITE:
return ChatColor.WHITE;
case ORANGE:
return ChatColor.GOLD;
case MAGENTA:
case PINK:
case PURPLE:
return ChatColor.LIGHT_PURPLE;
case LIGHT_BLUE:
case CYAN:
return ChatColor.AQUA;
case YELLOW:
return ChatColor.YELLOW;
case LIME:
return ChatColor.GREEN;
case GRAY:
case BLACK: // BLACK cannot be easily seen in chat
case BROWN:
return ChatColor.DARK_GRAY;
case BLUE:
return ChatColor.BLUE; // DARK_BLUE cannot be easily seen in chat
case GREEN:
return ChatColor.DARK_GREEN;
case RED:
return ChatColor.RED;
//case LIGHT_GRAY:
//case SILVER:
// SILVER was renamed to LIGHT_GRAY
default:
return ChatColor.GRAY;
}
}
/**
* Gets the {@link Color} value from its name
*
* @param colorName the color name
*
* @return the Color
*/
public static Color getColor(String colorName) {
switch (colorName.toLowerCase()) {
case "aqua":
return Color.AQUA;
case "black":
return Color.BLACK;
case "blue":
return Color.BLUE;
case "fuschia":
return Color.FUCHSIA;
case "gray":
return Color.GRAY;
case "green":
return Color.GREEN;
case "lime":
return Color.LIME;
case "maroon":
return Color.MAROON;
case "olive":
return Color.OLIVE;
case "orange":
return Color.ORANGE;
case "purple":
return Color.PURPLE;
case "red":
return Color.RED;
case "silver":
return Color.SILVER;
case "teal":
return Color.TEAL;
case "white":
return Color.WHITE;
case "yellow":
return Color.YELLOW;
case "navy":
default:
return Color.NAVY;
}
}
/**
* Gets the {@link Enchantment} from its name using
* user-friendly names. Why did bukkit think of using
* weird names such as WATER_WORKER for Aqua Affinity or
* DIG_SPEED for efficiency
*
* @param enchant the enchantment name
*
* @return the enchantment
*/
public static Enchantment getEnchant(String enchant) {
switch (enchant.toLowerCase()
.replace("-", "")
.replace("_", "")
.replace(" ", "")) {
case "protection":
return Enchantment.PROTECTION_ENVIRONMENTAL;
case "projectileprotection":
return Enchantment.PROTECTION_PROJECTILE;
case "fireprotection":
return Enchantment.PROTECTION_FIRE;
case "featherfall":
return Enchantment.PROTECTION_FALL;
case "blastprotection":
return Enchantment.PROTECTION_EXPLOSIONS;
case "respiration":
return Enchantment.OXYGEN;
case "aquaaffinity":
return Enchantment.WATER_WORKER;
case "sharpness":
return Enchantment.DAMAGE_ALL;
case "smite":
return Enchantment.DAMAGE_UNDEAD;
case "baneofarthropods":
return Enchantment.DAMAGE_ARTHROPODS;
case "knockback":
return Enchantment.KNOCKBACK;
case "fireaspect":
return Enchantment.FIRE_ASPECT;
case "depthstrider":
return Enchantment.DEPTH_STRIDER;
case "looting":
return Enchantment.LOOT_BONUS_MOBS;
case "power":
return Enchantment.ARROW_DAMAGE;
case "punch":
return Enchantment.ARROW_KNOCKBACK;
case "flame":
return Enchantment.ARROW_FIRE;
case "infinity":
return Enchantment.ARROW_INFINITE;
case "efficiency":
return Enchantment.DIG_SPEED;
case "silktouch":
return Enchantment.SILK_TOUCH;
case "unbreaking":
return Enchantment.DURABILITY;
case "fortune":
return Enchantment.LOOT_BONUS_BLOCKS;
case "luckofthesea":
return Enchantment.LUCK;
default:
return Enchantment.getByName(enchant.toUpperCase());
}
}
/**
* Sends a centered message to the player, assuming they have the
* default texture pack or a texture pack which does not modify
* the font size.
*
* @param player the player the message will be sent to
* @param message the message to send
*/
public static void sendCenteredMessage(Player player, String message) {
if (message == null || message.isEmpty()) {
player.sendMessage("");
return;
}
message = ChatColor.translateAlternateColorCodes('&', message);
int messagePxSize = 0;
boolean previousCode = false;
boolean isBold = false;
for (char c : message.toCharArray()) {
if (c == ChatColor.COLOR_CHAR) {
previousCode = true;
} else if (previousCode) {
previousCode = false;
isBold = c == 'l' || c == 'L';
} else {
DefaultFontInfo dFI = DefaultFontInfo.getDefaultFontInfo(c);
messagePxSize += isBold ? dFI.getBoldLength() : dFI.getLength();
messagePxSize++;
}
}
int halvedMessageSize = messagePxSize / 2;
int toCompensate = 154 - halvedMessageSize;
int spaceLength = DefaultFontInfo.SPACE.getLength() + 1;
int compensated = 0;
StringBuilder sb = new StringBuilder();
while (compensated < toCompensate) {
sb.append(" ");
compensated += spaceLength;
}
player.sendMessage(sb.toString() + message);
}
/**
* Displays a progress bar on the action bar of the player
*
* @param prefix the prefix of the progress bar
* @param amount the progress percentage (0.0 to 1.0)
* @param suffix the suffix of the progress bar
* @param players the players to send the progress bar to
*/
public static void displayProgress(String prefix, double amount, String suffix, Player... players) {
String progressBar = makeProgress(amount, 24, '#', ChatColor.GREEN, ChatColor.WHITE);
for (Player player : players) {
ActionBar.sendActionBar(player, (prefix == null ? "" : prefix + ChatColor.RESET + " ") + progressBar + (suffix == null ? "" : ChatColor.RESET + " " + suffix));
}
}
/**
* Generates a progress bar
*
* @param completion the percentage completed (0-1)
* @param bars the amount of bars to display
* @param barChar the char to use as the bar
* @param completeColor the color of the completed portion
* @param incompleteColor the color of the incompleted protion
* @return the generated progress bar
*/
public static String makeProgress(double completion, double bars, char barChar, ChatColor completeColor, ChatColor incompleteColor) {
StringBuilder progressBar = new StringBuilder(completeColor.toString());
boolean colorChange = false;
for (int i = 0; i < bars; i++) {
if (!colorChange && i / bars >= completion) {
progressBar.append(incompleteColor);
colorChange = true;
}
progressBar.append(barChar);
}
return progressBar.toString();
}
/**
* Formats a decimal to one decimal places
* 2.34567 will become 2.3
*
* @param number the number to round
* @return the rounded number in string format
*/
public static String roundToOneDecimal(double number) {
return ONE_DECIMAL_FORMAT.format(number);
}
/**
* Formats a decimal to two decimal places
* 2.34567 will become 2.34
*
* @param number the number to round
* @return the rounded number in string format
*/
public static String roundToTwoDecimals(double number) {
return TWO_DECIMAL_FORMAT.format(number);
}
/**
* Gets a random firework effect
*
* @return the random firework effect
*/
public static FireworkEffect getRandomEffect() {
FireworkEffect.Builder fireworkEffect = FireworkEffect.builder();
double randomType = RANDOM.nextDouble();
if (randomType > 0.5D) {
fireworkEffect.with(FireworkEffect.Type.BURST);
} else if (randomType > 0.25D) {
fireworkEffect.with(FireworkEffect.Type.STAR);
} else if (randomType > 0.15D) {
fireworkEffect.with(FireworkEffect.Type.BALL_LARGE);
} else {
fireworkEffect.with(FireworkEffect.Type.BALL);
}
boolean hasColour = false;
if (RANDOM.nextDouble() > 0.75D) {
fireworkEffect.withColor(Color.RED);
hasColour = true;
}
if (RANDOM.nextDouble() > 0.75D) {
fireworkEffect.withColor(Color.BLUE);
hasColour = true;
}
if (RANDOM.nextDouble() > 0.75D) {
fireworkEffect.withColor(Color.YELLOW);
hasColour = true;
}
if (RANDOM.nextDouble() > 0.75D) {
fireworkEffect.withColor(Color.AQUA);
hasColour = true;
}
if (!hasColour) {
fireworkEffect.withColor(Color.RED);
}
return fireworkEffect.build();
}
/**
* Formats a list of strings to go in a lore of an item
*
* @param title the title
* @param lines the lines
*
* @return the formatted lines
*/
public static List<String> orderListForLore(String title, List<String> lines) {
if (lines == null || lines.isEmpty()) {
return null;
}
List<String> newList = new ArrayList<>();
newList.add(ChatColor.YELLOW + title);
lines.forEach(line -> newList.add(ChatColor.GRAY + "- " + ChatColor.WHITE + line));
return newList;
}
/**
* Transforms a collection size to a multiple of nine for
* bukkit inventories, since they require the size to be a
* multiple of nine
*
* @param collection the collection
*
* @return the transformed slot
*/
public static int transformToInventorySize(Collection<?> collection) {
return transformToInventorySize(collection.size());
}
/**
* Transforms a number to a multiple of nine for the use in
* bukkit inventories, since they require the size to be a
* multiple of nine
*
* @param size the size of the list
*
* @return the transformed slot
*/
public static int transformToInventorySize(long size) {
return Math.min(((int) Math.ceil((Math.max(1, size)) / 9.0)) * 9, 54);
}
/**
* Gets the offset between two locations
*
* @param a Location a
* @param b Location b
*
* @return the offset between these two locations
*/
public static double offset(final Location a, final Location b) {
return offset(a.toVector(), b.toVector());
}
/**
* Gets the offset between two vectors
*
* @param a Vector a
* @param b Vector b
*
* @return the offset between these two vectors
*/
public static double offset(final Vector a, final Vector b) {
return a.subtract(b).length();
}
/**
* Returns if a location is between the radius of another location
*
* @param baseLocation the base location
* @param location the location to check
* @param radius the radius
*
* @return true if the location is withing the radius of the base location
*/
public static boolean isLocationInRadius(Location baseLocation, Location location, int radius) {
return abs(baseLocation.getX() - location.getX()) < radius &&
abs(baseLocation.getY() - location.getY()) < radius &&
abs(baseLocation.getZ() - location.getZ()) < radius;
}
/**
* Makes a player "bounce" to a location by applying velocity
*
* @param player the player to bounce
* @param location the location to bounce to
*/
public static void bounceTo(Player player, Location location) {
// Location a = player.getLocation();
//
// Vector from = new Vector(a.getX(), a.getY(), a.getZ());
// Vector to = new Vector(b.getX(), b.getY(), b.getZ());
//
// Vector velocity = to.subtract(from);
// player.setVelocity(velocity.normalize());
Vector a = player.getLocation().toVector().setY(0);
Vector b = location.toVector().setY(0);
Vector subtract = b.subtract(a);
player.setVelocity(subtract);
}
/**
* Rotates a vector with a pitch around the x coordinate
*
* @param vector the vector
* @param pitch the pitch
*/
public static void rotateX(Vector vector, double pitch) {
double cos = Math.cos(pitch);
double sin = Math.sin(pitch);
double y = vector.getY() * cos + vector.getZ() * sin;
double z = vector.getY() * -sin + vector.getZ() * cos;
vector.setY(y).setZ(z);
}
/**
* Rotates a vector with a yaw around the y coordinate
*
* @param vector the vector
* @param yaw the yaw
*/
public static void rotateY(Vector vector, double yaw) {
double cos = Math.cos(yaw);
double sin = Math.sin(yaw);
double x = vector.getX() * cos + vector.getZ() * sin;
double z = vector.getX() * -sin + vector.getZ() * cos;
vector.setX(x).setZ(z);
}
/**
* Converts an angle to radians
*
* @param angle the angle in degrees
* @return the angle in radians
*/
public static double degToRadians(double angle) {
return angle * Math.PI / 180;
}
/**
* Gets the middle location from a list of locations
*
* @param locs the list of locations
*
* @return the middle location
*/
public static Location getCenterLocation(List<ArenaLocation> locs) {
if (locs.isEmpty()) {
return null;
}
Vector vec = new Vector(0, 0, 0);
locs.forEach(location -> vec.add(location.toVector()));
vec.multiply(1.0 / (double) locs.size());
return vec.toLocation(locs.get(0).getWorld());
}
/**
* Returns the absolute value of a {@code double} value.
* If the argument is not negative, the argument minus one is returned.
* If the argument is negative, the negation of the argument is returned.
*
* @param a the argument whose absolute value is to be determined
*
* @return the absolute value of the argument.
*/
private static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a - 1;
}
/**
* Checks whether or not a collection contains an element
*
* @param collection the collection
* @param predicate the predicate
* @param <T> the collection type
*
* @return true if collection contains element
*/
public static <T> boolean collectionContains(Collection<T> collection, Predicate<? super T> predicate) {
return getFromCollection(collection, predicate) != null;
}
/**
* Checks whether or not a stream contains an element
*
* @param stream the stream
* @param predicate the predicate
* @param <T> the collection type
*
* @return true if stream contains element
*/
public static <T> boolean streamContains(Stream<T> stream, Predicate<? super T> predicate) {
return getFromStream(stream, predicate) != null;
}
/**
* Gets the element from a collection using a predicate
*
* @param collection the collection
* @param predicate the predicate
* @param <T> the collection type
*
* @return true the element if the collection contains it or null
*/
public static <T> T getFromCollection(Collection<T> collection, Predicate<? super T> predicate) {
return getFromStream(collection.stream(), predicate);
}
/**
* Gets a nameable object from a collection using its name
*
* @param collection the collection
* @param name the object's name
* @param <T> the stream type
*
* @return the nameable object if the collection contains it or null
*/
public static <T extends NameableObject> T getFromCollection(Collection<T> collection, String name) {
return getFromCollection(collection, t -> t.getName().equalsIgnoreCase(name));
}
/**
* Gets a nameable object from a stream using its name
*
* @param stream the stream
* @param name the object's name
* @param <T> the stream type
*
* @return the nameable object if the stream contains it or null
*/
public static <T extends NameableObject> T getFromStream(Stream<T> stream, String name) {
return getFromStream(stream, t -> t.getName().equalsIgnoreCase(name));
}
/**
* Gets the element from a stream using a predicate
*
* @param stream the stream
* @param predicate the predicate
* @param <T> the stream type
*
* @return the element if the stream contains it or null
*/
public static <T> T getFromStream(Stream<T> stream, Predicate<? super T> predicate) {
return stream.filter(predicate).findAny().orElse(null);
}
/**
* Returns a list of strings from a collection of nameable objects
*
* @param collection the collection of nameable objects
* @param <T> the nameable object
*
* @return the list of the object names
*/
public static <T extends NameableObject> List<String> toList(Collection<T> collection) {
return toList(collection.stream());
}
/**
* Returns a list of strings from a list of nameable objects
*
* @param stream the stream of nameable objects
* @param <T> the nameable object
*
* @return the list of the object names
*/
public static <T extends NameableObject> List<String> toList(Stream<T> stream) {
return stream.map(NameableObject::getName).collect(Collectors.toList());
}
/**
* Divide the first argument by the second and round the result up to the next integer.
*
* @param numerator Assumed to be >= 0
* @param denominator Assumed to be > 0
*/
public static int divideRoundingUp(int numerator, int denominator) {
return (numerator + denominator - 1) / denominator;
}
/**
* Gets the current timestamp using a simple date format. You
* can specify what format to use. You can use formats such as
* - yyyy-MM-dd HH:mm:ss.SSS
* - dd/MM/yyyy
*
* @param format the format
*
* @return the current timestamp with the specified date format
* @see SimpleDateFormat
*/
public static String getCurrentTimeStamp(String format) {
SimpleDateFormat sdfDate = new SimpleDateFormat(format);// - dd/MM/yyyy
Date now = new Date();
return sdfDate.format(now);
}
/**
* Returns a formatted string in the format mm:ss from the
* given time
*
* @param pTime the time in seconds
*
* @return the mm:ss formatted time
*/
public static String secondsToString(long pTime) {
return pTime > 3600 ? String.format("%02d:%02d:%02d", pTime / 3600, pTime / 60 % 60, pTime % 60) : String.format("%02d:%02d", pTime / 60, pTime % 60);
}
/**
* Gets the number of the week of the year using the gregorian calendar
*
* @return the week of the year
*/
public static int getWeekOfTheYear() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
/**
* Gets the month number of the year
* <p>
* Since apparently January = 0, we add 1 so that January = 1
*
* @return the month number
*/
public static int getMonthOfTheYear() {
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
* Gets the year we are in
*
* @return the year
*/
public static int getYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
* Formats a location into a nice string
*
* @param location the location to format
* @param commandSender the sender for the localization
*
* @return the formatted string
*/
public static String locationToString(Location location, CommandSender commandSender) {
return CoreLang.LOCATION_TO_INFO.replace(commandSender, location.getWorld().getName(), location.getX() + ", " + location.getY() + ", " + location.getZ());
}
/**
* Formats a location into a nice message containing only the coordinates
*
* @param location the location to format
* @param commandSender the sender for the localization
*
* @return the formatted string
*/
public static String locationToCoords(Location location, CommandSender commandSender) {
return CoreLang.LOCATION_TO_COORDS.replace(commandSender, location.getX() + ", " + location.getY() + ", " + location.getZ());
}
/**
* Capitalizes only the first letter of a string, really
* useful when using enums
*
* @param originalString the string to capitalize
*
* @return the capitalized string
*/
public static String capitalizeFirstLetter(String originalString) {
return originalString.toUpperCase().charAt(0) + originalString.toLowerCase().substring(1);
}
/**
* Converts a List of SerializableObject to a List<Map<String, Object>>
*
* @param serializableObjects the list of serializable objects
*
* @return the list of serialized objects
*/
public static List<Map<String, Object>> serializeList(List<? extends SerializableObject> serializableObjects) {
return serializableObjects.stream().map(SerializableObject::serialize).collect(Collectors.toList());
}
/**
* Deserialize a list of Map<String, Object> to a List of elements
* using a mapper
*
* @param list the list
* @param mapper the mapper
* @param <E> the element type
*
* @return the list of deserialized objects
*/
public static <E extends SerializableObject> List<E> deserializeList(List<Map<String, Object>> list, Function<Map<String, Object>, E> mapper) {
return list.stream().map(mapper).collect(Collectors.toList());
}
/**
* Prints a formatted error message
*
* @param lines the error lines
*/
public static void printError(Object... lines) {
logger.log(Level.SEVERE, "");
logger.log(Level.SEVERE, "******** ERROR ********");
logger.log(Level.SEVERE, PluginConfig.PLUGIN_NAME);
for (Object line : lines) {
if(line instanceof Throwable) {
logger.log(Level.SEVERE, "", (Throwable) line);
continue;
}
if(line instanceof Iterable) {
for (Object o : ((Iterable) line)) {
logger.log(Level.SEVERE, String.valueOf(o));
}
continue;
}
logger.log(Level.SEVERE, String.valueOf(line));
}
logger.log(Level.SEVERE, "***********************");
logger.log(Level.SEVERE, "");
}
/**
* Prints a formatted debug message
*
* @param lines the debug lines
*/
public static void printDebug(Object... lines) {
System.out.println();
System.out.println("******** DEBUG ********");
System.out.println(PluginConfig.PLUGIN_NAME);
for (Object line : lines) {
if(line instanceof Throwable) {
((Throwable) line).printStackTrace(System.out);
continue;
}
if(line instanceof Iterable) {
for (Object o : ((Iterable) line)) {
System.out.println(o);
}
continue;
}
System.out.println(line);
}
System.out.println("***********************");
System.out.println();
}
/**
* Sets the max amount of players the server has
*
* @param maxPlayerCount the max amount of players
*
* @throws ReflectiveOperationException in case any errors
*/
public static void setMaxPlayers(int maxPlayerCount) throws ReflectiveOperationException {
Object playerlist = getCBSClass("CraftServer").getDeclaredMethod("getHandle", null).invoke(Bukkit.getServer(), null);
Field maxplayers = playerlist.getClass().getSuperclass().getDeclaredField("maxPlayers");
maxplayers.setAccessible(true);
maxplayers.set(playerlist, maxPlayerCount);
}
// -------------------------------------------- //
// NO AI - START
// -------------------------------------------- //
// Credits to vemacs for this
// https://gist.github.com/vemacs/6cd43a50950796458984
private static Method getHandle;
private static Method getNBTTag;
private static Class<?> nmsEntityClass;
private static Class<?> nbtTagClass;
private static Method c;
private static Method setInt;
private static Method f;
public static void setAiEnabled(Entity entity, boolean enabled) {
try {
((LivingEntity)entity).setAI(enabled);
} catch (Throwable e) {
try {
if (getHandle == null) {
Class<?> craftEntity = getCBSClass("entity.CraftEntity");
assert craftEntity != null;
getHandle = craftEntity.getDeclaredMethod("getHandle");
getHandle.setAccessible(true);
}
Object nmsEntity = getHandle.invoke(entity);
if (nmsEntityClass == null) {
nmsEntityClass = getNMSClass("Entity");
}
if (getNBTTag == null) {
assert nmsEntityClass != null;
getNBTTag = nmsEntityClass.getDeclaredMethod("getNBTTag");
getNBTTag.setAccessible(true);
}
Object tag = getNBTTag.invoke(nmsEntity);
if (nbtTagClass == null) {
nbtTagClass = getNMSClass("NBTTagCompound");
}
if (tag == null) {
assert nbtTagClass != null;
tag = nbtTagClass.newInstance();
}
if (c == null) {
c = nmsEntityClass.getDeclaredMethod("c", nbtTagClass);
c.setAccessible(true);
}
c.invoke(nmsEntity, tag);
if (setInt == null) {
setInt = nbtTagClass.getDeclaredMethod("setInt", String.class, Integer.TYPE);
setInt.setAccessible(true);
}
int value = enabled ? 0 : 1;
setInt.invoke(tag, "NoAI", value);
if (f == null) {
f = nmsEntityClass.getDeclaredMethod("f", nbtTagClass);
f.setAccessible(true);
}
f.invoke(nmsEntity, tag);
} catch (Exception e2) {
logger.log(Level.SEVERE, "Could not set ai state!", e);
}
}
}
// -------------------------------------------- //
// NO AI - END
// -------------------------------------------- //
/**
* Gets a GameProfile (for itemstack heads)
*
* @return the GameProfile object
* @throws Exception in case any errors
*/
public static Object createGameProfile() throws Exception {
if (gameProfileConstructor == null) {
Class<?> gameProfileClass;
try { // 1.7
gameProfileClass = Class.forName("net.minecraft.util.com.mojang.authlib.GameProfile");
} catch (ClassNotFoundException e) { // 1.8
gameProfileClass = Class.forName("com.mojang.authlib.GameProfile");
}
gameProfileConstructor = gameProfileClass.getDeclaredConstructor(UUID.class, String.class);
gameProfileConstructor.setAccessible(true);
}
return gameProfileConstructor.newInstance(UUID.randomUUID(), null);
}
/**
* Gets a GameProfile (for itemstack heads)
*
* @return the GameProfile object
* @throws Exception in case any errors
*/
public static Object createProperty(String propery, String value) throws Exception {
if (propertyConstructor == null) {
Class<?> propertyClass;
try { // 1.7
propertyClass = Class.forName("net.minecraft.util.com.mojang.authlib.properties.Property");
} catch (ClassNotFoundException e) { // 1.8
propertyClass = Class.forName("com.mojang.authlib.properties.Property");
}
propertyConstructor = propertyClass.getDeclaredConstructor(String.class, String.class);
propertyConstructor.setAccessible(true);
}
return propertyConstructor.newInstance(propery, value);
}
public static SplittableRandom getRandom() {
return RANDOM;
}
/**
* Resets a player completely.
* Health, food level, inventory, gamemode survival
*
* @param player the player to clear
*/
public static void clearPlayer(Player player) {
player.setAllowFlight(false);
player.setFlying(false);
player.setMaxHealth(20.0);
player.setHealth(20.0);
player.setFoodLevel(20);
player.getInventory().setArmorContents(null);
player.getInventory().clear();
player.updateInventory();
player.setLevel(0);
player.setExp(0.0f);
player.setGameMode(GameMode.SURVIVAL);
// player.setVelocity(new org.bukkit.util.Vector(0, 0, 0));
player.setFallDistance(0);
for (final PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
}
/**
* Converts a configuration date string to millis
* The format of the string is <time><unit>
* Ex:
* 1d = 1 day
* 1h = 1 hour
* 1m1s = 1 minute and 1 second
*
* @param date the date string
* @return the date string converted to millis or -1 if no match
*/
public static long dateStringToMillis(String date) {
if (!DATE_VALIDATION.matcher(date).matches()) {
return -1;
}
long millis = 0;
Matcher matcher = DATE_PART.matcher(date);
while (matcher.find()) {
long number = Long.parseLong(matcher.group(1));
String unit = matcher.group(2);
if (unit.equalsIgnoreCase("s")) {
millis += number * 1_000;
} else if (unit.equalsIgnoreCase("m")) {
millis += number * 60_000;
} else if (unit.equalsIgnoreCase("h")) {
millis += number * 3_600_000;
} else if (unit.equalsIgnoreCase("d")) {
millis += number * 84_400_000;
} else if (unit.equalsIgnoreCase("w")) {
millis += number * 590_800_000;
} else {
throw new IllegalStateException("Got unknown unit " + unit);
}
}
return millis;
}
/**
* Formats a big value to a small value
* 1,000 = 1K
* 1,000,000 = 1M
* etc
*
* @param value the value to format
* @return the formatted value
*/
public static String formatLong(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return formatLong(Long.MIN_VALUE + 1);
if (value < 0) return "-" + formatLong(-value);
if (value < 1000) return Long.toString(value); //deal with easy case
Map.Entry<Long, String> e = SUFFIXES.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();
long truncated = value / (divideBy / 10); //the number part of the output times 10
@SuppressWarnings("IntegerDivisionInFloatingPointContext")
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
/**
* Formats a millis time into a typed time
* eg. 3 hours 4 minutes 3 seconds
*
* @param player the player to get the translations from
* @param time the time in millis
* @return the formatted time
*/
public static String createTime(Player player, long time) {
time /= 1000;
long seconds = time % 60;
long minutes = time / 60 % 60;
long hours = time / 3600 % 24;
long days = time / 86_400 % 7;
long weeks = time / 604_800;
StringBuilder timeStr = new StringBuilder();
if (weeks > 0) {
timeStr.append(" ").append(weeks).append(" ").append((weeks == 1 ? CoreLang.TIME_WEEK : CoreLang.TIME_WEEKS).getMessage(player));
}
if (days > 0) {
timeStr.append(" ").append(days).append(" ").append((days == 1 ? CoreLang.TIME_DAYS : CoreLang.TIME_DAYS).getMessage(player));
}
if (hours > 0) {
timeStr.append(" ").append(hours).append(" ").append((hours == 1 ? CoreLang.TIME_HOUR : CoreLang.TIME_HOURS).getMessage(player));
}
if (minutes > 0) {
timeStr.append(" ").append(minutes).append(" ").append((minutes == 1 ? CoreLang.TIME_MINUTE : CoreLang.TIME_MINUTES).getMessage(player));
}
if (seconds > 0) {
timeStr.append(" ").append(seconds).append(" ").append((seconds == 1 ? CoreLang.TIME_SECOND : CoreLang.TIME_SECONDS).getMessage(player));
}
return timeStr.substring(1);
}
} | 88,658 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
EnchantGlow.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/EnchantGlow.java | package me.patothebest.gamecore.util;
import org.bukkit.enchantments.Enchantment;
public class EnchantGlow {
private static Enchantment glow;
public static void setGlow(Enchantment glow) {
EnchantGlow.glow = glow;
}
public static Enchantment getGlow() {
return glow;
}
} | 311 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ThrowableConsumer.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/ThrowableConsumer.java | package me.patothebest.gamecore.util;
import java.util.function.Consumer;
@FunctionalInterface
public interface ThrowableConsumer<T> extends Consumer<T> {
default void accept(T t) {
try {
acceptThrows(t);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
void acceptThrows(T t) throws Exception;
}
| 378 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ServerVersion.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/ServerVersion.java | package me.patothebest.gamecore.util;
import org.bukkit.Bukkit;
public class ServerVersion {
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
public static String getBukkitVersion() {
return Bukkit.getVersion();
}
}
| 335 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
StringUtil.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/StringUtil.java | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.patothebest.gamecore.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* String utilities.
*
* @author sk89q
*/
public final class StringUtil {
private StringUtil() {
}
/**
* Trim a string if it is longer than a certain length.
*
* @param str
* @param len
* @return
*/
public static String trimLength(String str, int len) {
if (str.length() > len) {
return str.substring(0, len);
}
return str;
}
/**
* Join an array of strings into a string.
*
* @param str
* @param delimiter
* @param initialIndex
* @return
*/
public static String joinString(String[] str, String delimiter,
int initialIndex) {
if (str == null || str.length == 0) {
return "";
}
StringBuilder buffer = new StringBuilder(str[initialIndex]);
for (int i = initialIndex + 1; i < str.length; ++i) {
buffer.append(delimiter).append(str[i]);
}
return buffer.toString();
}
/**
* Join an array of strings into a string.
*
* @param str
* @param delimiter
* @param initialIndex
* @param quote
* @return
*/
public static String joinQuotedString(String[] str, String delimiter,
int initialIndex, String quote) {
if (str.length == 0) {
return "";
}
StringBuilder buffer = new StringBuilder();
buffer.append(quote);
buffer.append(str[initialIndex]);
buffer.append(quote);
for (int i = initialIndex + 1; i < str.length; ++i) {
buffer.append(delimiter).append(quote).append(str[i]).append(quote);
}
return buffer.toString();
}
/**
* Join an array of strings into a string.
*
* @param str
* @param delimiter
* @return
*/
public static String joinString(String[] str, String delimiter) {
return joinString(str, delimiter, 0);
}
/**
* Join an array of strings into a string.
*
* @param str
* @param delimiter
* @param initialIndex
* @return
*/
public static String joinString(Object[] str, String delimiter,
int initialIndex) {
if (str.length == 0) {
return "";
}
StringBuilder buffer = new StringBuilder(str[initialIndex].toString());
for (int i = initialIndex + 1; i < str.length; ++i) {
buffer.append(delimiter).append(str[i].toString());
}
return buffer.toString();
}
/**
* Join an array of strings into a string.
*
* @param str
* @param delimiter
* @param initialIndex
* @return
*/
public static String joinString(int[] str, String delimiter,
int initialIndex) {
if (str.length == 0) {
return "";
}
StringBuilder buffer = new StringBuilder(Integer.toString(str[initialIndex]));
for (int i = initialIndex + 1; i < str.length; ++i) {
buffer.append(delimiter).append(str[i]);
}
return buffer.toString();
}
/**
* Join an list of strings into a string.
*
* @param str
* @param delimiter
* @param initialIndex
* @return
*/
public static String joinString(Collection<?> str, String delimiter,
int initialIndex) {
if (str.size() == 0) {
return "";
}
StringBuilder buffer = new StringBuilder();
int i = 0;
for (Object o : str) {
if (i >= initialIndex) {
if (i > 0) {
buffer.append(delimiter);
}
buffer.append(o.toString());
}
++i;
}
return buffer.toString();
}
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
*
* <pre>
* StringUtil.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtil.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtil.getLevenshteinDistance("","") = 0
* StringUtil.getLevenshteinDistance("","a") = 1
* StringUtil.getLevenshteinDistance("aaapppp", "") = 7
* StringUtil.getLevenshteinDistance("frog", "fog") = 1
* StringUtil.getLevenshteinDistance("fly", "ant") = 3
* StringUtil.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtil.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtil.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtil.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input <code>null</code>
*/
public static int getLevenshteinDistance(String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
* The difference between this impl. and the previous is that, rather
* than creating and retaining a matrix of size s.length()+1 by
* t.length()+1, we maintain two single-dimensional arrays of length
* s.length()+1. The first, d, is the 'current working' distance array
* that maintains the newest distance cost counts as we iterate through
* the characters of String s. Each time we increment the index of
* String t we are comparing, d is copied to p, the second int[]. Doing
* so allows us to retain the previous cost counts as required by the
* algorithm (taking the minimum of the cost count to the left, up one,
* and diagonally up and to the left of the current cost count being
* calculated). (Note that the arrays aren't really copied anymore, just
* switched...this is clearly much better than cloning an array or doing
* a System.arraycopy() each time through the outer loop.)
*
* Effectively, the difference between the two implementations is this
* one does not cause an out of memory condition when calculating the LD
* over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int[] p = new int[n + 1]; // 'previous' cost array, horizontally
int[] d = new int[n + 1]; // cost array, horizontally
int[] _d; // placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char tj; // jth character of t
int cost; // cost
for (i = 0; i <= n; ++i) {
p[i] = i;
}
for (j = 1; j <= m; ++j) {
tj = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; ++i) {
cost = s.charAt(i - 1) == tj ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left
// and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1]
+ cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
public static <T extends Enum<?>> T lookup(Map<String, T> lookup, String name, boolean fuzzy) {
String testName = name.replaceAll("[ _]", "").toLowerCase();
T type = lookup.get(testName);
if (type != null) {
return type;
}
if (!fuzzy) {
return null;
}
int minDist = -1;
for (Map.Entry<String, T> entry : lookup.entrySet()) {
final String key = entry.getKey();
if (key.charAt(0) != testName.charAt(0)) {
continue;
}
int dist = getLevenshteinDistance(key, testName);
if ((dist < minDist || minDist == -1) && dist < 2) {
minDist = dist;
type = entry.getValue();
}
}
return type;
}
public static List<String> complete(String prefix, Iterable<String> options) {
final String prefixLower = prefix.toLowerCase();
final int pos = prefixLower.lastIndexOf(' ');
final List<String> matches = new ArrayList<>();
options.forEach(option -> {
if(option.toLowerCase().startsWith(prefixLower)) {
matches.add(pos == -1 ? option : option.substring(pos + 1));
}
});
Collections.sort(matches);
return matches;
}
}
| 10,775 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
SerializableObject.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/SerializableObject.java | package me.patothebest.gamecore.util;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.HashMap;
import java.util.Map;
/**
* Represents an object that may be serialized.
*/
public interface SerializableObject extends ConfigurationSerializable {
/**
* Creates a Map representation of this class.
* <p>
* This class must provide a method to restore this class, as defined in
* the {@link ConfigurationSerializable} interface javadocs.
*
* @return Map containing the current state of this class
*/
@Override
default Map<String, Object> serialize() {
Map<String, Object> data = new HashMap<>();
serialize(data);
return data;
}
void serialize(Map<String, Object> data);
}
| 793 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ObjectProvider.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/util/ObjectProvider.java | package me.patothebest.gamecore.util;
import java.util.Map;
public interface ObjectProvider<T> {
T loadObject(String configName, Map<String, Object> data);
}
| 166 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopItem.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopItem.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.util.NameableObject;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public interface ShopItem extends NameableObject {
List<String> getDescription();
int getPrice();
ItemStack getDisplayItem();
String getPermission();
String getDisplayName();
boolean isPermanent();
default boolean isFree() {
return getPrice() <= 0;
}
}
| 465 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopMenu.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopMenu.java | package me.patothebest.gamecore.cosmetics.shop;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.gui.inventory.button.ClickTypeButton;
import me.patothebest.gamecore.gui.inventory.page.GUIMultiPage;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.entity.Player;
public class ShopMenu<ShopItemType extends ShopItem, PlayerType extends IPlayer> extends GUIMultiPage {
private final ShopManager<ShopItemType> shopManager;
private final PlayerManager playerManager;
private final ShopFactory shopFactory;
@Inject protected ShopMenu(CorePlugin plugin, @Assisted Player player, @Assisted ShopManager<ShopItemType> shopManager, PlayerManager playerManager, ShopFactory shopFactory) {
super(plugin, player, shopManager.getTitle(), Utils.transformToInventorySize(shopManager.getShopItems()));
this.shopManager = shopManager;
this.playerManager = playerManager;
this.shopFactory = shopFactory;
build();
}
@SuppressWarnings("unchecked")
@Override
protected void buildContent() {
final PlayerType iPlayer = (PlayerType) playerManager.getPlayer(getPlayer());
shopManager.getShopItems().stream().skip(pageSize * currentPage).limit(pageSize).forEachOrdered(shopItem -> {
ItemStackBuilder itemStackShopItem = new ItemStackBuilder(shopItem.getDisplayItem().clone())
.name(shopItem.getDisplayName());
if(!shopItem.getDescription().isEmpty() && !shopItem.getDescription().get(0).isEmpty()) {
itemStackShopItem.addLore(shopItem.getDescription());
}
if (!iPlayer.canUse(shopItem) && !shopItem.isFree()) {
itemStackShopItem.blankLine()
.addLore(CoreLang.GUI_SHOP_PRICE.replace(getPlayer(), (shopItem.isFree() ? CoreLang.GUI_SHOP_FREE.getMessage(getPlayer()) : shopItem.getPrice() + "")));
}
ItemStackBuilder itemStack = itemStackShopItem.clone().blankLine();
boolean canBuyUses = false;
ShopAction action = ShopAction.DO_NOTHING;
if (shopItem.getPermission() == null || shopItem.getPermission().isEmpty() || getPlayer().hasPermission(shopItem.getPermission())) {
if (iPlayer.isSelected(shopItem)) {
if(shopItem.isPermanent()) {
itemStack.addLore(CoreLang.GUI_SHOP_SELECTED.getMessage(getPlayer())).glowing(true);
} else {
canBuyUses = true;
itemStack.addLore(CoreLang.GUI_SHOP_USES_LORE.replace(iPlayer, iPlayer.getRemainingUses(shopItem)));
itemStack.blankLine();
itemStack.addLore(CoreLang.GUI_SHOP_RIGHT_CLICK.getMessage(getPlayer()));
itemStack.addLore(CoreLang.GUI_SHOP_SELECTED.getMessage(getPlayer())).glowing(true);
}
} else if (shopItem.isFree()) {
itemStack.addLore(CoreLang.GUI_SHOP_CLICK_TO_SELECT.getMessage(getPlayer()));
action = ShopAction.SELECT;
} else if (iPlayer.canUse(shopItem)) {
if(shopItem.isPermanent() || iPlayer.isPermanent(shopItem)) {
itemStack.addLore(CoreLang.GUI_SHOP_LEFT_CLICK_SELECT.getMessage(getPlayer()));
action = ShopAction.SELECT;
} else {
canBuyUses = true;
itemStack.addLore(CoreLang.GUI_SHOP_USES_LORE.replace(iPlayer, iPlayer.getRemainingUses(shopItem)));
itemStack.blankLine();
itemStack.addLore(CoreLang.GUI_SHOP_RIGHT_CLICK.getMessage(getPlayer()));
itemStack.addLore(CoreLang.GUI_SHOP_LEFT_CLICK_SELECT.getMessage(getPlayer()));
action = ShopAction.SELECT;
}
} else {
if(shopItem.isPermanent()) {
itemStack.addLore(CoreLang.GUI_SHOP_CLICK_TO_BUY.getMessage(getPlayer()));
action = ShopAction.BUY;
} else {
canBuyUses = true;
itemStack.addLore(CoreLang.GUI_SHOP_USES_LORE.replace(iPlayer, 0));
itemStack.blankLine();
itemStack.addLore(CoreLang.GUI_SHOP_CLICK_TO_BUY.getMessage(getPlayer()));
action = ShopAction.BUY;
}
}
} else {
itemStack.addLore(CoreLang.GUI_SHOP_NO_PERMISSION_STRING.replace(getPlayer()));
}
ShopAction finalAction = action;
boolean finalCanBuyUses = canBuyUses;
addButton(new ClickTypeButton(itemStack).action((clickType) -> {
switch (finalAction) {
case DO_NOTHING:
case SELECT:
if(!clickType.name().contains("LEFT") && finalCanBuyUses) {
if (iPlayer.getMoney() < shopItem.getPrice()) {
CoreLang.GUI_SHOP_NOT_ENOUGH_MONEY.sendMessage(player);
break;
}
ItemStackBuilder item2 = new ItemStackBuilder(itemStackShopItem);
shopFactory.createUsesShopMenu(player, item2, shopManager, shopItem);
refresh();
} else if(finalAction == ShopAction.SELECT) {
iPlayer.selectItem(shopItem);
CoreLang.GUI_SHOP_YOU_SELECTED.replaceAndSend(player, shopItem.getDisplayName());
refresh();
}
break;
case BUY:
if (iPlayer.getMoney() < shopItem.getPrice()) {
CoreLang.GUI_SHOP_NOT_ENOUGH_MONEY.sendMessage(player);
break;
}
ItemStackBuilder item2 = new ItemStackBuilder(itemStackShopItem);
shopFactory.createUsesShopMenu(player, item2, shopManager, shopItem);
break;
}
}));
});
}
@Override
protected int getListCount() {
return shopManager.getShopItems().size();
}
}
| 6,779 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopFactory.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopFactory.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.player.IPlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface ShopFactory {
<ShopItemType extends ShopItem, PlayerType extends IPlayer> ShopMenu<ShopItemType, PlayerType> createShopMenu(Player player, ShopManager<ShopItemType> shopManager);
<ShopItemType extends ShopItem, PlayerType extends IPlayer> ShopMenuUses<ShopItemType, PlayerType> createUsesShopMenu(Player player, ItemStack displayItem, ShopManager<ShopItemType> shopManager, ShopItemType shopItemType);
}
| 602 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AbstractShopItem.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/AbstractShopItem.java | package me.patothebest.gamecore.cosmetics.shop;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public abstract class AbstractShopItem implements ShopItem {
private final String configName;
private final String displayName;
private final List<String> description;
private final int price;
private final String permission;
private final boolean permanent;
public AbstractShopItem() {
configName = "";
displayName = "";
description = Collections.emptyList();
price = 0;
permission = "";
permanent = true;
}
@SuppressWarnings("unchecked")
public AbstractShopItem(String configName, Map<String, Object> data) {
this.configName = configName;
this.displayName = (String) data.get("name");
this.description = (List<String>) data.get("description");
this.price = (int) data.getOrDefault("price", 0);
this.permission = (String) data.getOrDefault("permission", "");
this.permanent = (boolean) data.getOrDefault("permanent", true);
}
@Override
public final List<String> getDescription() {
return description;
}
@Override
public final int getPrice() {
return price;
}
@Override
public final String getPermission() {
return permission;
}
@Override
public final String getDisplayName() {
return displayName;
}
@Override
public final String getName() {
return configName;
}
@Override
public final boolean isPermanent() {
return permanent;
}
}
| 1,626 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopRegistry.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopRegistry.java | package me.patothebest.gamecore.cosmetics.shop;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.logger.InjectLogger;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.Module;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
@Singleton
@ModuleName("Shop Registry")
public class ShopRegistry implements ActivableModule {
private final Map<String, ShopManager> shopManagersName = new HashMap<>();
private final Map<Class<? extends ShopItem>, ShopManager> shopItemsManagers = new HashMap<>();
private final CorePlugin corePlugin;
@InjectLogger private Logger logger;
@Inject private ShopRegistry(CorePlugin corePlugin) {
this.corePlugin = corePlugin;
}
@Override
public void onPreEnable() {
corePlugin.getModuleInstances().forEach(entry -> {
Module module = entry.getValue();
if (module instanceof ShopManager) {
registerShop((ShopManager) module);
logger.info("Registered shop " + module.getClass().getSimpleName());
}
});
}
public Map<String, ShopManager> getShopManagersNamesMap() {
return shopManagersName;
}
public Map<Class<? extends ShopItem>, ShopManager> getShopItemsManagers() {
return shopItemsManagers;
}
@SuppressWarnings("unchecked")
private void registerShop(ShopManager shopManager) {
shopManagersName.put(shopManager.getShopName(), shopManager);
shopItemsManagers.put(shopManager.getShopItemClass(), shopManager);
}
}
| 1,751 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopAction.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopAction.java | package me.patothebest.gamecore.cosmetics.shop;
public enum ShopAction {
SELECT,
BUY,
DO_NOTHING
}
| 114 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopMenuUses.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopMenuUses.java | package me.patothebest.gamecore.cosmetics.shop;
import com.google.inject.assistedinject.Assisted;
import me.patothebest.gamecore.gui.inventory.button.SimpleButton;
import me.patothebest.gamecore.itemstack.Material;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.gui.inventory.GUIPage;
import me.patothebest.gamecore.gui.inventory.button.IncrementingButton;
import me.patothebest.gamecore.gui.inventory.button.IncrementingButtonAction;
import me.patothebest.gamecore.gui.inventory.button.PlaceHolder;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.itemstack.StainedGlassPane;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import javax.inject.Inject;
import javax.inject.Provider;
public class ShopMenuUses<ShopItemType extends ShopItem, PlayerType extends IPlayer> extends GUIPage {
private int itemUses = 1;
private final ItemStack displayItem;
private final ShopManager<ShopItemType> shopManager;
private final ShopItemType shopItem;
private final PlayerManager playerManager;
private final ShopFactory shopFactory;
private final Provider<Economy> economyProvider;
private final static int[] GRAY_STAINED_PANES = new int[]{3, 5, 28, 29, 30, 32, 33, 34, 37, 39, 41, 43, 46, 47, 48, 50, 51, 52};
@Inject public ShopMenuUses(CorePlugin plugin, @Assisted Player player, @Assisted ItemStack displayItem, @Assisted ShopManager<ShopItemType> shopManager, @Assisted ShopItemType shopItem, PlayerManager playerManager, ShopFactory shopFactory, Provider<Economy> economyProvider) {
super(plugin, player, shopManager.getTitle(), 54);
this.displayItem = displayItem;
this.shopManager = shopManager;
this.shopItem = shopItem;
this.playerManager = playerManager;
this.shopFactory = shopFactory;
this.economyProvider = economyProvider;
build();
}
@SuppressWarnings("unchecked")
@Override
public void buildPage() {
final PlayerType iPlayer = (PlayerType) playerManager.getPlayer(getPlayer());
if (economyProvider.get() == null) {
CoreLang.GUI_USER_CHOOSE_ECONOMY_PLUGIN_ERROR.sendMessage(iPlayer);
getPlayer().closeInventory();
return;
}
if (!shopItem.isPermanent()) {
IncrementingButtonAction onUpdateUses = (amount) -> {
itemUses = Math.max(Math.min(itemUses + amount, 64), 1);
refresh();
};
addButton(new IncrementingButton(-10, onUpdateUses), 19);
addButton(new IncrementingButton(-5, onUpdateUses), 20);
addButton(new IncrementingButton(-1, onUpdateUses), 21);
addButton(new IncrementingButton(1, onUpdateUses), 23);
addButton(new IncrementingButton(5, onUpdateUses), 24);
addButton(new IncrementingButton(10, onUpdateUses), 25);
}
displayItem.setAmount(itemUses);
addButton(new SimpleButton(new ItemStackBuilder(Material.EMERALD).name(ChatColor.GREEN + (economyProvider.get() != null ? economyProvider.get().currencyNamePlural() : "")).lore(ChatColor.GRAY.toString() + (shopItem.getPrice() * itemUses) + (economyProvider.get() != null ? " " + economyProvider.get().currencyNamePlural() : "") + " will be deducted from your account")), 4);
addButton(new PlaceHolder(displayItem), 22);
addButton(new SimpleButton(new ItemStackBuilder().createCancelItem()).action(() -> shopFactory.createShopMenu(player, shopManager)), 38);
if (iPlayer.getMoney() >= shopItem.getPrice() * itemUses) {
addButton(new SimpleButton(new ItemStackBuilder().createConfirmItem()).action(() -> {
EconomyResponse economyResponse = economyProvider.get().withdrawPlayer(player, shopItem.getPrice() * itemUses);
if (!economyResponse.transactionSuccess()) {
player.sendMessage(CoreLang.GUI_USER_CHOOSE_ERROR_OCCURRED.getMessage(player));
player.sendMessage(ChatColor.RED + "ERROR: " + economyResponse.errorMessage);
return;
}
if (shopItem.isPermanent()) {
iPlayer.buyItemPermanently(shopItem);
player.sendMessage(CoreLang.GUI_SHOP_YOU_BOUGHT.replace(player, shopItem.getDisplayName()));
} else {
iPlayer.buyItemUses(shopItem, itemUses);
player.sendMessage(CoreLang.GUI_SHOP_PURCHASED_USES.replace(player, itemUses, shopItem.getDisplayName()));
}
iPlayer.selectItem(shopItem);
shopFactory.createShopMenu(player, shopManager);
}), 42);
} else {
addPlaceholder(new ItemStackBuilder().material(Material.BARRIER).name(iPlayer, CoreLang.GUI_KIT_SHOP_NOT_ENOUGH_MONEY), 42);
}
for (int grayStainedPane : GRAY_STAINED_PANES) {
addPlaceholder(new ItemStackBuilder(StainedGlassPane.GRAY).name(""), grayStainedPane);
}
for (int i = 0; i < 54; i++) {
if (isFree(i)) {
addPlaceholder(new ItemStackBuilder(StainedGlassPane.WHITE).name(""), i);
}
}
}
}
| 5,546 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopCommand.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.chat.CommandPagination;
import me.patothebest.gamecore.command.BaseCommand;
import me.patothebest.gamecore.command.ChildOf;
import me.patothebest.gamecore.command.Command;
import me.patothebest.gamecore.command.CommandContext;
import me.patothebest.gamecore.command.CommandException;
import me.patothebest.gamecore.command.CommandPermissions;
import me.patothebest.gamecore.command.CommandsManager;
import me.patothebest.gamecore.command.LangDescription;
import me.patothebest.gamecore.command.NestedCommand;
import me.patothebest.gamecore.modules.Module;
import me.patothebest.gamecore.modules.RegisteredCommandModule;
import me.patothebest.gamecore.permission.Permission;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.util.CommandUtils;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List;
public class ShopCommand implements Module {
private final ShopRegistry shopRegistry;
private final PlayerManager playerManager;
private final ShopFactory shopFactory;
@Inject private ShopCommand(ShopRegistry shopRegistry, PlayerManager playerManager, ShopFactory shopFactory) {
this.shopRegistry = shopRegistry;
this.playerManager = playerManager;
this.shopFactory = shopFactory;
}
@ChildOf(BaseCommand.class)
public static class Parent implements RegisteredCommandModule {
private final CommandsManager<CommandSender> commandsManager;
@Inject private Parent(CommandsManager<CommandSender> commandsManager) {
this.commandsManager = commandsManager;
}
@Command(
aliases = {"shop"},
langDescription = @LangDescription(
element = "SHOP_COMMANDS_DESC",
langClass = CoreLang.class
)
)
@NestedCommand(value = ShopCommand.class)
public void shop(CommandContext args, CommandSender sender) throws CommandException {
new CommandPagination(commandsManager, args).display(sender);
}
}
@Command(
aliases = {"openshop", "openmenu", "open"},
usage = "<shop>",
min = 1,
max = 1,
langDescription = @LangDescription(
element = "",
langClass = CoreLang.class
)
)
public List<String> openShop(CommandContext args, CommandSender sender) throws CommandException {
Player player = CommandUtils.getPlayer(sender);
if(args.getSuggestionContext() != null) {
return CommandUtils.complete(args.getString(0), shopRegistry.getShopManagersNamesMap().keySet());
}
//CommandUtils.validateTrue(!playerManager.getPlayer(player).isInArena(), CoreLang.YOU_CANNOT_EXECUTE_COMMANDS);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(0));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
shopFactory.createShopMenu(player, shopManager);
return null;
}
@SuppressWarnings("Duplicates")
@Command(
aliases = {"give", "add"},
usage = "<player> <shop> <item> [amount] [-p(ermanent)]",
flags = "p",
min = 3,
max = 4,
langDescription = @LangDescription(
element = "SHOP_ITEMS_GIVE_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.ADMIN)
public List<String> giveShopItems(CommandContext args, CommandSender sender) throws CommandException {
if (args.getSuggestionContext() != null) {
switch (args.getSuggestionContext().getIndex()) {
case 0:
return CommandUtils.completePlayers(args.getString(0));
case 1:
return CommandUtils.complete(args.getString(1), shopRegistry.getShopManagersNamesMap().keySet());
case 2:
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
return CommandUtils.complete(args.getString(2), Utils.toList(shopManager.getShopItems()));
default:
return null;
}
}
IPlayer player = CommandUtils.getPlayer(args, playerManager, 0);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
ShopItem shopItem = shopManager.getShopItemsMap().get(args.getString(2));
CommandUtils.validateNotNull(shopItem, CoreLang.SHOP_ITEM_NOT_FOUND);
if (shopItem.isPermanent() || args.hasFlag('p')) {
player.buyItemPermanently(shopItem);
CoreLang.SHOP_ITEMS_GIVEN_PERMANENT.replaceAndSend(sender, player.getName(), shopItem.getName(), shopManager.getName());
} else {
int amount = args.getInteger(3, -1);
CommandUtils.validateTrue(amount > 0, CoreLang.SHOP_ITEMS_GIVE_MUST_BE_POSITIVE);
player.buyItemUses(shopItem, args.getInteger(3));
CoreLang.SHOP_ITEMS_GIVEN.replaceAndSend(sender, player.getName(), amount, shopItem.getName(), shopManager.getName());
}
return null;
}
@SuppressWarnings("Duplicates")
@Command(
aliases = {"giveall", "addall"},
usage = "<player> <shop> [amount] [-p(ermanent]",
flags = "p",
min = 2,
max = 3,
langDescription = @LangDescription(
element = "SHOP_ITEMS_GIVE_ALL_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.ADMIN)
public List<String> giveAll(CommandContext args, CommandSender sender) throws CommandException {
if (args.getSuggestionContext() != null) {
switch (args.getSuggestionContext().getIndex()) {
case 0:
return CommandUtils.completePlayers(args.getString(0));
case 1:
return CommandUtils.complete(args.getString(1), shopRegistry.getShopManagersNamesMap().keySet());
default:
return null;
}
}
IPlayer player = CommandUtils.getPlayer(args, playerManager, 0);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
int amount = -1;
if (args.isInBounds(2)) {
amount = args.getInteger(2, -1);
CommandUtils.validateTrue(amount > 0, CoreLang.SHOP_ITEMS_GIVE_MUST_BE_POSITIVE);
}
for (ShopItem shopItem : shopManager.getShopItems()) {
if (args.hasFlag('p')) {
player.buyItemPermanently(shopItem);
CoreLang.SHOP_ITEMS_GIVEN_PERMANENT.replaceAndSend(sender, player.getName(), shopItem.getName(), shopManager.getName());
} else if (amount != -1 && !shopItem.isPermanent()) {
player.buyItemUses(shopItem, amount);
CoreLang.SHOP_ITEMS_GIVEN.replaceAndSend(sender, player.getName(), amount, shopItem.getName(), shopManager.getName());
}
}
return null;
}
@SuppressWarnings("Duplicates")
@Command(
aliases = {"set"},
usage = "<player> <shop> <item> <amount>",
min = 4,
max = 4,
langDescription = @LangDescription(
element = "SHOP_ITEMS_SET_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.ADMIN)
public List<String> setShopItems(CommandContext args, CommandSender sender) throws CommandException {
if (args.getSuggestionContext() != null) {
switch (args.getSuggestionContext().getIndex()) {
case 0:
return CommandUtils.completePlayers(args.getString(0));
case 1:
return CommandUtils.complete(args.getString(1), shopRegistry.getShopManagersNamesMap().keySet());
case 2:
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
return CommandUtils.complete(args.getString(2), Utils.toList(shopManager.getShopItems()));
default:
return null;
}
}
IPlayer player = CommandUtils.getPlayer(args, playerManager, 0);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
ShopItem shopItem = shopManager.getShopItemsMap().get(args.getString(2));
CommandUtils.validateNotNull(shopItem, CoreLang.SHOP_ITEM_NOT_FOUND);
CommandUtils.validateTrue(!shopItem.isPermanent(), CoreLang.SHOP_ITEM_IS_PERMANENT);
int amount = args.getInteger(3);
CommandUtils.validateTrue(amount > 0, CoreLang.SHOP_ITEMS_GIVE_MUST_BE_POSITIVE);
player.setItemAmount(shopItem, args.getInteger(3));
CoreLang.SHOP_ITEMS_GIVEN.replaceAndSend(sender, player.getName(), amount, shopItem.getName(), shopManager.getName());
return null;
}
@SuppressWarnings("Duplicates")
@Command(
aliases = {"remove", "take", "reset"},
usage = "<player> <shop> <item> [amount]",
min = 3,
max = 4,
langDescription = @LangDescription(
element = "SHOP_ITEMS_REMOVE_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.ADMIN)
public List<String> removeShopItems(CommandContext args, CommandSender sender) throws CommandException {
if (args.getSuggestionContext() != null) {
switch (args.getSuggestionContext().getIndex()) {
case 0:
return CommandUtils.completePlayers(args.getString(0));
case 1:
return CommandUtils.complete(args.getString(1), shopRegistry.getShopManagersNamesMap().keySet());
case 2:
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
return CommandUtils.complete(args.getString(2), Utils.toList(shopManager.getShopItems()));
default:
return null;
}
}
IPlayer player = CommandUtils.getPlayer(args, playerManager, 0);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
ShopItem shopItem = shopManager.getShopItemsMap().get(args.getString(2));
CommandUtils.validateNotNull(shopItem, CoreLang.SHOP_ITEM_NOT_FOUND);
if (shopItem.isPermanent()) {
player.removeItem(shopItem);
CoreLang.SHOP_ITEMS_REMOVED_PERMANENT.replaceAndSend(sender, player.getName(), shopItem.getName(), shopManager.getName());
} else {
if (args.isInBounds(3)) {
int amount = args.getInteger(3, -1);
CommandUtils.validateTrue(amount > 0, CoreLang.SHOP_ITEMS_TAKE_MUST_BE_POSITIVE);
player.removeItem(shopItem, args.getInteger(3));
CoreLang.SHOP_ITEMS_REMOVED.replaceAndSend(sender, player.getName(), amount, shopItem.getName(), shopManager.getName());
} else {
player.removeItem(shopItem);
CoreLang.SHOP_ITEMS_REMOVED_PERMANENT.replaceAndSend(sender, player.getName(), shopItem.getName(), shopManager.getName());
}
}
return null;
}
@SuppressWarnings("Duplicates")
@Command(
aliases = {"removeall", "takeall", "resetall"},
usage = "<player> <shop> [amount]",
min = 2,
max = 3,
langDescription = @LangDescription(
element = "SHOP_ITEMS_REMOVE_ALL_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.ADMIN)
public List<String> removeAll(CommandContext args, CommandSender sender) throws CommandException {
if (args.getSuggestionContext() != null) {
switch (args.getSuggestionContext().getIndex()) {
case 0:
return CommandUtils.completePlayers(args.getString(0));
case 1:
return CommandUtils.complete(args.getString(1), shopRegistry.getShopManagersNamesMap().keySet());
default:
return null;
}
}
IPlayer player = CommandUtils.getPlayer(args, playerManager, 0);
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(args.getString(1));
CommandUtils.validateNotNull(shopManager, CoreLang.SHOP_NOT_FOUND);
int amount = -1;
if (args.isInBounds(2)) {
amount = args.getInteger(2, -1);
CommandUtils.validateTrue(amount > 0, CoreLang.SHOP_ITEMS_TAKE_MUST_BE_POSITIVE);
}
for (ShopItem shopItem : shopManager.getShopItems()) {
if (amount == -1) {
player.removeItem(shopItem);
CoreLang.SHOP_ITEMS_REMOVED_PERMANENT.replaceAndSend(sender, player.getName(), shopItem.getName(), shopManager.getName());
} else {
player.removeItem(shopItem, amount);
CoreLang.SHOP_ITEMS_REMOVED.replaceAndSend(sender, player.getName(), amount, shopItem.getName(), shopManager.getName());
}
}
return null;
}
}
| 14,475 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopManager.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.lang.interfaces.ILang;
import java.util.Collection;
import java.util.Map;
public interface ShopManager<ShopItemType extends ShopItem> {
Collection<ShopItemType> getShopItems();
ILang getTitle();
ILang getName();
Map<String, ShopItemType> getShopItemsMap();
Class<ShopItemType> getShopItemClass();
String getShopName();
}
| 434 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AbstractShopManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/AbstractShopManager.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.logger.InjectImplementationLogger;
import me.patothebest.gamecore.phase.phases.GamePhase;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.player.ArenaLeaveEvent;
import me.patothebest.gamecore.event.player.PlayerSelectItemEvent;
import me.patothebest.gamecore.file.FlatFile;
import me.patothebest.gamecore.file.ReadOnlyFile;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ListenerModule;
import me.patothebest.gamecore.modules.ReloadableModule;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.util.ObjectProvider;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractShopManager<ShopItemType extends ShopItem> implements ShopManager<ShopItemType>, ActivableModule, ReloadableModule, ListenerModule {
private final Class<ShopItemType> shopItemTypeClass;
protected final ReadOnlyFile readOnlyFile;
protected final CorePlugin plugin;
protected final Map<String, ShopItemType> shopItems = new LinkedHashMap<>();
protected final PlayerManager playerManager;
protected ObjectProvider<ShopItemType> shopItemTypeObjectProvider;
protected ShopItemType defaultItem = null;
protected boolean deselectOnDeplete = false;
@InjectImplementationLogger private Logger logger;
@SuppressWarnings("unchecked")
public AbstractShopManager(CorePlugin plugin, PlayerManager playerManager) {
this.plugin = plugin;
this.playerManager = playerManager;
this.readOnlyFile = new ReadOnlyFile(getShopName());
try {
Type genericSuperclass = getClass().getGenericSuperclass();
Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
shopItemTypeClass = (Class<ShopItemType>) Class.forName(type.getTypeName());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@EventHandler
public void onPhaseChange(ArenaPhaseChangeEvent event) {
if (!(event.getNewPhase() instanceof GamePhase)) {
return;
}
for (Player player : event.getArena().getPlayers()) {
IPlayer player1 = playerManager.getPlayer(player);
ShopItemType selectedItem = player1.getSelectedItem(getShopItemClass());
if (selectedItem == null) {
continue;
}
if (!player1.useItem(selectedItem)) {
player1.deSelectItem(selectedItem);
} else if (deselectOnDeplete) {
if (!player1.canUse(selectedItem)) {
player1.deSelectItem(selectedItem);
}
}
}
}
@EventHandler
public void onPlayerLeave(ArenaLeaveEvent event) {
if (deselectOnDeplete) {
return;
}
IPlayer player1 = playerManager.getPlayer(event.getPlayer());
ShopItemType selectedItem = player1.getSelectedItem(getShopItemClass());
if (selectedItem == null) {
return;
}
if (!player1.canUse(selectedItem)) {
player1.deSelectItem(selectedItem);
}
}
@Override
public void onPreEnable() {
boolean newFile = false;
FlatFile file = readOnlyFile;
if (!readOnlyFile.getFile().exists()) {
newFile = true;
file = new FlatFile(getShopName()) {
@Override
protected void writeFile(BufferedWriter writer) throws IOException {
super.writeFile(writer);
Utils.writeFileToWriter(writer, plugin.getResource(getShopName() + ".yml"));
}
};
file.load();
}
readOnlyFile.load();
if (shopItemTypeObjectProvider == null) {
throw new IllegalStateException("Shop item provider is not initialized for " + getShopName() + "!");
}
logger.log(Level.CONFIG, ChatColor.YELLOW + "Loading items");
ConfigurationSection shopConfigurationSection = readOnlyFile.getConfigurationSection(getShopName());
for (String itemName : shopConfigurationSection.getKeys(false)) {
ShopItemType shopItem;
try {
shopItem = shopItemTypeObjectProvider.loadObject(itemName, shopConfigurationSection.getConfigurationSection(itemName).getValues(true));
} catch (Throwable throwable) {
if (newFile) {
file.set(getShopName() + "." + itemName, null);
} else {
Utils.printError("Could not load item " + itemName, throwable.getMessage());
}
continue;
}
if (shopConfigurationSection.getBoolean(itemName + ".default")) {
defaultItem = shopItem;
}
shopItems.put(itemName, shopItem);
logger.log(Level.CONFIG, "Loaded {0}", itemName);
}
if (newFile) {
file.save();
readOnlyFile.load();
}
logger.log(Level.INFO, "Loaded {0} items!", shopItems.size());
}
@Override
public void onReload() {
Map<CorePlayer, ShopItem> selectedItems = new HashMap<>();
Map<CorePlayer, Map<ShopItem, Integer>> ownedItems = new HashMap<>();
for (CorePlayer player : playerManager.getPlayers()) {
ShopItem remove = player.getSelectedShopItems().remove(shopItemTypeClass);
if (remove != null) {
selectedItems.put(player, remove);
}
Map<ShopItem, Integer> removeOwned = player.getOwnedItems().remove(shopItemTypeClass);
if (removeOwned != null) {
ownedItems.put(player, removeOwned);
}
}
onDisable();
shopItems.clear();
defaultItem = null;
readOnlyFile.load();
onPreEnable();
onEnable();
onPostEnable();
ownedItems.forEach((player, ownedItemMap) -> {
HashMap<ShopItem, Integer> playerItems = new HashMap<>();
ownedItemMap.forEach((shopItem, amount) -> {
playerItems.put(shopItems.get(shopItem.getName()), amount);
});
player.getOwnedItems().put(shopItemTypeClass, playerItems);
});
selectedItems.forEach((player, shopItem) -> {
player.getSelectedShopItems().put(shopItemTypeClass, shopItems.get(shopItem.getName()));
plugin.callEvent(new PlayerSelectItemEvent(player, shopItem));
});
}
@Override
public Class<ShopItemType> getShopItemClass() {
return shopItemTypeClass;
}
@Override
public String getReloadName() {
return getShopName();
}
public ShopItemType getDefaultItem() {
return defaultItem;
}
@Override
public Collection<ShopItemType> getShopItems() {
return shopItems.values();
}
@Override
public Map<String, ShopItemType> getShopItemsMap() {
return shopItems;
}
}
| 7,779 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopFactoryImpl.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopFactoryImpl.java | package me.patothebest.gamecore.cosmetics.shop;
import com.google.inject.Inject;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import javax.inject.Provider;
public class ShopFactoryImpl implements ShopFactory {
private final CorePlugin plugin;
private final PlayerManager playerManager;
private final Provider<Economy> economyProvider;
@Inject private ShopFactoryImpl(CorePlugin plugin, PlayerManager playerManager, Provider<Economy> economyProvider) {
this.plugin = plugin;
this.playerManager = playerManager;
this.economyProvider = economyProvider;
}
@Override
public <ShopItemType extends ShopItem, PlayerType extends IPlayer> ShopMenu<ShopItemType, PlayerType> createShopMenu(Player player, ShopManager<ShopItemType> shopManager) {
return new ShopMenu<>(plugin, player, shopManager, playerManager, this);
}
@Override
public <ShopItemType extends ShopItem, PlayerType extends IPlayer> ShopMenuUses<ShopItemType, PlayerType> createUsesShopMenu(Player player, ItemStack displayItem, ShopManager<ShopItemType> shopManager, ShopItemType shopItemType) {
return new ShopMenuUses<>(plugin, player, displayItem, shopManager, shopItemType, playerManager, this, economyProvider);
}
}
| 1,482 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopModule.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/ShopModule.java | package me.patothebest.gamecore.cosmetics.shop;
import me.patothebest.gamecore.storage.StorageModule;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.cosmetics.shop.entities.ShopFlatFileEntity;
import me.patothebest.gamecore.cosmetics.shop.entities.ShopMySQLEntity;
import me.patothebest.gamecore.storage.flatfile.FlatFileEntity;
import me.patothebest.gamecore.storage.mysql.MySQLEntity;
public class ShopModule extends StorageModule {
public ShopModule(CorePlugin plugin) {
super(plugin);
}
@Override
protected void configure() {
super.configure();
registerModule(ShopRegistry.class);
registerModule(ShopCommand.Parent.class);
}
@Override
protected Class<? extends FlatFileEntity> getFlatFileEntity() {
return ShopFlatFileEntity.class;
}
@Override
protected Class<? extends MySQLEntity> getSQLEntity() {
return ShopMySQLEntity.class;
}
}
| 963 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopMySQLEntity.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/entities/ShopMySQLEntity.java | package me.patothebest.gamecore.cosmetics.shop.entities;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.cosmetics.shop.ShopItem;
import me.patothebest.gamecore.cosmetics.shop.ShopManager;
import me.patothebest.gamecore.cosmetics.shop.ShopRegistry;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.modifiers.PlayerModifier;
import me.patothebest.gamecore.player.modifiers.ShopModifier;
import me.patothebest.gamecore.storage.mysql.LoadSynchronously;
import me.patothebest.gamecore.storage.mysql.MySQLEntity;
import me.patothebest.gamecore.util.Utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Singleton
@LoadSynchronously
public class ShopMySQLEntity implements MySQLEntity {
private final ShopRegistry shopRegistry;
@Inject ShopMySQLEntity(ShopRegistry shopRegistry) {
this.shopRegistry = shopRegistry;
}
/**
* Loads a player's extra information
*
* @param player the player loaded
* @param connection the connection
*/
@Override
public void loadPlayer(CorePlayer player, Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.SELECT_OWNED_ITEMS);
preparedStatement.setInt(1, player.getPlayerId());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String shopName = resultSet.getString("shop_name");
String itemName = resultSet.getString("item_name");
int uses = resultSet.getInt("uses");
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(shopName);
if(shopManager == null) {
Utils.printError("Loading owned items", "Shop " + shopName + " not found!", "Player: " + player.getName());
continue;
}
ShopItem shopItem = shopManager.getShopItemsMap().get(itemName);
if(shopItem == null) {
Utils.printError("Loading owned items", "Shop item " + itemName + " not found!", "Player: " + player.getName());
continue;
}
player.buyItemUses(shopItem, uses);
}
resultSet.close();
preparedStatement.close();
preparedStatement = connection.prepareStatement(Queries.SELECT_SELECTED_ITEMS);
preparedStatement.setInt(1, player.getPlayerId());
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String shopName = resultSet.getString("shop_name");
String itemName = resultSet.getString("item_name");
ShopManager<?> shopManager = shopRegistry.getShopManagersNamesMap().get(shopName);
if(shopManager == null) {
Utils.printError("Loading selected items", "Shop " + shopName + " not found!", "Player: " + player.getName());
continue;
}
ShopItem shopItem = shopManager.getShopItemsMap().get(itemName);
if(shopItem == null) {
Utils.printError("Loading selected items", "Shop item " + itemName + " not found!", "Player: " + player.getName());
continue;
}
player.selectItem(shopItem);
}
resultSet.close();
preparedStatement.close();
}
/**
* Saves a player's extra information
*
* @param player the player to save
* @param connection the connection
*/
@Override
public void savePlayer(CorePlayer player, Connection connection) throws SQLException {
}
@Override
public void updatePlayer(CorePlayer player, Connection connection, PlayerModifier updatedType, Object... args) throws SQLException {
if(!(updatedType instanceof ShopModifier)) {
return;
}
ShopItem shopItem = (ShopItem) args[0];
switch ((ShopModifier)updatedType) {
case BOUGHT_ITEM: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.INSERT_OWNED_ITEM);
preparedStatement.setInt(1, player.getPlayerId());
preparedStatement.setString(2, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.setString(3, shopItem.getName());
preparedStatement.setInt(4, (Integer) args[1]);
preparedStatement.execute();
preparedStatement.close();
break;
} case BOUGHT_ITEM_USES:
case USED_ITEM: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.UPDATE_OWNED_ITEM);
preparedStatement.setInt(1, (Integer) args[1]);
preparedStatement.setInt(2, player.getPlayerId());
preparedStatement.setString(3, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.setString(4, shopItem.getName());
preparedStatement.execute();
preparedStatement.close();
break;
} case DEPLETED_ITEM: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.REMOVE_OWNED_ITEM);
preparedStatement.setInt(1, player.getPlayerId());
preparedStatement.setString(2, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.setString(3, shopItem.getName());
preparedStatement.execute();
preparedStatement.close();
break;
} case SELECT_DEFAULT: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.INSERT_SELECTED_ITEM);
preparedStatement.setInt(1, player.getPlayerId());
preparedStatement.setString(2, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.setString(3, shopItem.getName());
preparedStatement.execute();
preparedStatement.close();
break;
} case UPDATE_SELECT_DEFAULT: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.UPDATE_SELECTED_ITEM);
preparedStatement.setString(1, shopItem.getName());
preparedStatement.setInt(2, player.getPlayerId());
preparedStatement.setString(3, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.execute();
preparedStatement.close();
break;
} case REMOVE_SELECTED_ITEM: {
PreparedStatement preparedStatement = connection.prepareStatement(Queries.REMOVE_SELECTED_ITEM);
preparedStatement.setInt(1, player.getPlayerId());
preparedStatement.setString(2, shopRegistry.getShopItemsManagers().get(shopItem.getClass()).getShopName());
preparedStatement.execute();
preparedStatement.close();
break;
}
}
}
/**
* Gets all the statements needed to create the
* table(s) for the specific entity.
*
* @return the create table statements
*/
@Override
public String[] getCreateTableStatements() {
return new String[]{Queries.CREATE_TABLE_SHOP_ITEMS, Queries.CREATE_TABLE_SELECTED_ITEMS};
}
} | 7,632 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ShopFlatFileEntity.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/entities/ShopFlatFileEntity.java | package me.patothebest.gamecore.cosmetics.shop.entities;
import com.google.inject.Inject;
import me.patothebest.gamecore.cosmetics.shop.ShopRegistry;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.storage.StorageException;
import me.patothebest.gamecore.storage.flatfile.FlatFileEntity;
import me.patothebest.gamecore.storage.flatfile.PlayerProfileFile;
public class ShopFlatFileEntity implements FlatFileEntity {
private final ShopRegistry shopRegistry;
@Inject private ShopFlatFileEntity(ShopRegistry shopRegistry) {
this.shopRegistry = shopRegistry;
}
@Override
public void loadPlayer(CorePlayer player, PlayerProfileFile playerProfileFile) throws StorageException {
}
@Override
public void savePlayer(CorePlayer player, PlayerProfileFile playerProfileFile) throws StorageException {
}
}
| 877 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Queries.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/shop/entities/Queries.java | package me.patothebest.gamecore.cosmetics.shop.entities;
import me.patothebest.gamecore.PluginConfig;
class Queries {
private static final String OWNED_ITEMS_TABLE_NAME = PluginConfig.SQL_PREFIX + "_owned_items";
private static final String SELECTED_ITEMS_TABLE_NAME = PluginConfig.SQL_PREFIX + "_selected_items";
static final String CREATE_TABLE_SHOP_ITEMS =
"CREATE TABLE IF NOT EXISTS `" + OWNED_ITEMS_TABLE_NAME + "` (\n" +
" `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `player_id` int(11) NOT NULL,\n" +
" `shop_name` varchar(36) NOT NULL,\n" +
" `item_name` varchar(36) NOT NULL,\n" +
" `uses` int(11) NOT NULL,\n" +
" PRIMARY KEY (`entry_id`),\n" +
" UNIQUE KEY `entry_id` (`entry_id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=latin1;\n";
static final String CREATE_TABLE_SELECTED_ITEMS =
"CREATE TABLE IF NOT EXISTS `" + SELECTED_ITEMS_TABLE_NAME + "` (\n" +
" `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `player_id` int(11) NOT NULL,\n" +
" `shop_name` varchar(36) NOT NULL,\n" +
" `item_name` varchar(36) NOT NULL,\n" +
" PRIMARY KEY (`entry_id`),\n" +
" UNIQUE KEY `entry_id` (`entry_id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=latin1;\n";
static final String INSERT_OWNED_ITEM = "INSERT INTO " + OWNED_ITEMS_TABLE_NAME + " VALUES(NULL, ?, ?, ?, ?);";
static final String UPDATE_OWNED_ITEM = "UPDATE " + OWNED_ITEMS_TABLE_NAME + " SET uses=? WHERE player_id=? AND shop_name=? AND item_name=?";
// static final String DELETE_OWNED_ITEM = "DELETE FROM " + OWNED_ITEMS_TABLE_NAME + " WHERE entry_id=?";
static final String REMOVE_OWNED_ITEM = "DELETE FROM " + OWNED_ITEMS_TABLE_NAME + " WHERE player_id=? AND shop_name=? AND item_name=?";
static final String SELECT_OWNED_ITEMS = "SELECT * FROM " + OWNED_ITEMS_TABLE_NAME + " WHERE player_id=?";
static final String INSERT_SELECTED_ITEM = "INSERT INTO " + SELECTED_ITEMS_TABLE_NAME + " VALUES(NULL, ?, ?, ?);";
// static final String DELETE_SELECTED_ITEM = "DELETE FROM " + SELECTED_ITEMS_TABLE_NAME + " WHERE entry_id=?";
static final String UPDATE_SELECTED_ITEM = "UPDATE " + SELECTED_ITEMS_TABLE_NAME + " SET item_name=? WHERE player_id=? AND shop_name=?";
static final String REMOVE_SELECTED_ITEM = "DELETE FROM " + SELECTED_ITEMS_TABLE_NAME + " WHERE player_id=? AND shop_name=?";
static final String SELECT_SELECTED_ITEMS = "SELECT * FROM " + SELECTED_ITEMS_TABLE_NAME + " WHERE player_id=?";
}
| 2,704 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CageStructure.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/cage/CageStructure.java | package me.patothebest.gamecore.cosmetics.cage;
import com.google.inject.Provider;
import me.patothebest.gamecore.nms.NMS;
import me.patothebest.gamecore.util.Callback;
import org.bukkit.Location;
import org.bukkit.block.Block;
public enum CageStructure {
INDIVIDUAL(new int[3][5][3], structure -> {
structure[0] = new int[][] { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 } };
structure[1] = new int[][] { { 2, 1, 2 }, { 2, 0, 2 }, { 2, 0, 2 }, { 2, 0, 2 }, { 2, 1, 2 } };
structure[2] = new int[][] { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 } };
}),
TEAM(new int[5][5][5], structure -> {
structure[0] = new int[][] { { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 } };
structure[1] = new int[][] { { 2, 1, 1, 1, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 1, 1, 1, 2 } };
structure[2] = new int[][] { { 2, 1, 1, 1, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 1, 1, 1, 2 } };
structure[3] = new int[][] { { 2, 1, 1, 1, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 0, 0, 0, 2 }, { 2, 1, 1, 1, 2 } };
structure[4] = new int[][] { { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2 } };
}),
MEGA(new int[7][5][7], structure -> {
structure[0] = new int[][] { { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 } };
structure[1] = new int[][] { { 2, 1, 1, 1, 1, 1, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 1, 1, 1, 1, 1, 2 } };
structure[2] = new int[][] { { 2, 1, 1, 1, 1, 1, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 1, 1, 1, 1, 1, 2 } };
structure[3] = new int[][] { { 2, 1, 1, 1, 1, 1, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 1, 1, 1, 1, 1, 2 } };
structure[4] = new int[][] { { 2, 1, 1, 1, 1, 1, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 1, 1, 1, 1, 1, 2 } };
structure[5] = new int[][] { { 2, 1, 1, 1, 1, 1, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 0, 0, 0, 0, 0, 2 }, { 2, 1, 1, 1, 1, 1, 2 } };
structure[6] = new int[][] { { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2 } };
}),
;
private final int[][][] structure;
CageStructure(int[][][] structure, Callback<int[][][]> callback) {
this.structure = structure;
callback.call(structure);
}
public int getOffset() {
return (structure.length-1)/2;
}
public int[][][] getStructure() {
return structure;
}
public void createCage(Provider<NMS> nms, Cage cageType, Location location) { //loop through x values
for (int x = 0; x < structure.length; x++) {
//loop through y values for the current x value
for (int y = 0; y < structure[x].length; y++) {
//loop through all z values for the current x and y value
for (int z = 0; z < structure[x][y].length; z++) {
Location offsetLocation = location.clone();
//goes to new location in relation to start
offsetLocation.add(x, y, z);
Block block = offsetLocation.getBlock();
//checks if the block is not air
if (structure[x][y][z] != 0) {
//if it isn't it will replace it with the id at the x y z coordinate
switch (structure[x][y][z]) {
case 1:
nms.get().setBlock(block, cageType.getInnerMaterial());
break;
case 2:
nms.get().setBlock(block, cageType.getOuterMaterial());
break;
}
}
}
}
}
}
}
| 4,403 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Cage.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/cage/Cage.java | package me.patothebest.gamecore.cosmetics.cage;
import me.patothebest.gamecore.itemstack.Material;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopItem;
import me.patothebest.gamecore.file.ParserException;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.itemstack.StainedGlass;
import me.patothebest.gamecore.util.FinalSupplier;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
import java.util.function.Supplier;
public class Cage extends AbstractShopItem {
private final Supplier<ItemStack> outerMaterialSupplier;
private final Supplier<ItemStack> innerMaterialSupplier;
public Cage(Material innerMaterial, Material outerMaterial) {
super();
outerMaterialSupplier = new FinalSupplier<>(new ItemStackBuilder(outerMaterial));
innerMaterialSupplier = new FinalSupplier<>(new ItemStackBuilder(innerMaterial));
}
public Cage(String configName, Map<String, Object> data) {
super(configName, data);
if(((String)data.get("outer-material")).equalsIgnoreCase("rainbow")) {
outerMaterialSupplier = StainedGlass::getRandom;
} else {
ItemStack itemStack = Utils.itemStackFromString((String) data.get("outer-material"));
if(itemStack == null) {
throw new ParserException("Outer material of cage " + configName + " could not be parsed!");
}
outerMaterialSupplier = () -> itemStack;
}
if(((String)data.get("inner-material")).equalsIgnoreCase("rainbow")) {
innerMaterialSupplier = StainedGlass::getRandom;
} else {
ItemStack itemStack = Utils.itemStackFromString((String) data.get("inner-material"));
if(itemStack == null) {
throw new ParserException("Inner material of cage " + configName + " could not be parsed!");
}
innerMaterialSupplier = () -> itemStack;
}
}
public ItemStack getOuterMaterial() {
return outerMaterialSupplier.get();
}
public ItemStack getInnerMaterial() {
return innerMaterialSupplier.get();
}
@Override
public ItemStack getDisplayItem() {
return getOuterMaterial();
}
}
| 2,308 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CageManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/cage/CageManager.java | package me.patothebest.gamecore.cosmetics.cage;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.itemstack.Material;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopManager;
import me.patothebest.gamecore.player.PlayerManager;
@Singleton
@ModuleName("Cage Manager")
public class CageManager extends AbstractShopManager<Cage> {
public static final Cage NULL_CAGE = new Cage(Material.AIR, Material.AIR);
private static final Cage DEFAULT_CAGE = new Cage(Material.GLASS, Material.GLASS);
@Inject private CageManager(CorePlugin plugin, PlayerManager playerManager) {
super(plugin, playerManager);
this.shopItemTypeObjectProvider = Cage::new;
this.deselectOnDeplete = true;
}
@Override
public void onPreEnable() {
super.onPreEnable();
if (defaultItem == null) {
shopItems.put("default", DEFAULT_CAGE);
}
}
@Override
public String getShopName() {
return "cages";
}
@Override
public Cage getDefaultItem() {
return defaultItem == null ? DEFAULT_CAGE : defaultItem;
}
@Override
public ILang getTitle() {
return CoreLang.SHOP_CAGE_TITLE;
}
@Override
public ILang getName() {
return CoreLang.SHOP_CAGE_NAME;
}
}
| 1,534 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CageModule.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/cage/CageModule.java | package me.patothebest.gamecore.cosmetics.cage;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.injector.AbstractBukkitModule;
public class CageModule extends AbstractBukkitModule<CorePlugin> {
public CageModule(CorePlugin plugin) {
super(plugin);
}
@Override
protected void configure() {
registerModule(CageManager.class);
}
}
| 394 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CageModel.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/cage/model/CageModel.java | package me.patothebest.gamecore.cosmetics.cage.model;
import me.patothebest.gamecore.cosmetics.cage.CageStructure;
import me.patothebest.gamecore.itemstack.Material;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.model.AbstractModel;
import me.patothebest.gamecore.nms.NMS;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class CageModel extends AbstractModel {
private final CageStructure cage;
public CageModel(NMS nms, CageStructure cage, Location location) {
this.nms = nms;
this.cage = cage;
this.originLocation = location;
}
@Override
public void spawn() {
//loop through x values
for (int x = 0; x < cage.getStructure().length; x++) {
//loop through y values for the current x value
for (int y = 0; y < cage.getStructure()[x].length; y++) {
//loop through all z values for the current x and y value
for (int z = 0; z < cage.getStructure()[x][y].length; z++) {
//checks if the block is not air
if (cage.getStructure()[x][y][z] != 0) {
Vector offset = new Vector(x - cage.getOffset(), y - 1, z - cage.getOffset());
addPiece(offset, new ItemStackBuilder(Material.GLASS));
}
}
}
}
}
}
| 1,420 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ProjectileManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/projectiletrails/ProjectileManager.java | package me.patothebest.gamecore.cosmetics.projectiletrails;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopManager;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
@Singleton
@ModuleName("Projectile Manager")
public class ProjectileManager extends AbstractShopManager<ProjectileTrail> {
private final ProjectileTracker projectileTracker;
@Inject private ProjectileManager(CorePlugin plugin, PlayerManager playerManager, ProjectileTracker projectileTracker) {
super(plugin, playerManager);
this.projectileTracker = projectileTracker;
shopItemTypeObjectProvider = ProjectileTrail::new;
}
@EventHandler
public void onShoot(ProjectileLaunchEvent event) {
if(!(event.getEntity().getShooter() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity().getShooter();
IPlayer player1 = playerManager.getPlayer(player);
if(!player1.isPlaying()) {
return;
}
ProjectileTrail selectedItem = player1.getSelectedItem(ProjectileTrail.class);
if(selectedItem == null) {
return;
}
projectileTracker.trackProjectile(event.getEntity(), selectedItem);
}
@EventHandler
public void onShoot(EntityShootBowEvent event) {
if(!(event.getEntity() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity();
IPlayer player1 = playerManager.getPlayer(player);
if(!player1.isPlaying()) {
return;
}
ProjectileTrail selectedItem = player1.getSelectedItem(ProjectileTrail.class);
if(selectedItem == null) {
return;
}
projectileTracker.trackProjectile((Projectile) event.getProjectile(), selectedItem);
}
@Override
public ILang getTitle() {
return CoreLang.SHOP_PROJECTILE_TRAIL_TITLE;
}
@Override
public ILang getName() {
return CoreLang.SHOP_PROJECTILE_TRAIL_NAME;
}
@Override
public String getShopName() {
return "projectile-trails";
}
}
| 2,651 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ProjectileTracker.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/projectiletrails/ProjectileTracker.java | package me.patothebest.gamecore.cosmetics.projectiletrails;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import fr.mrmicky.fastparticle.FastParticle;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.util.CacheCollection;
import me.patothebest.gamecore.util.WrappedBukkitRunnable;
import org.bukkit.Location;
import org.bukkit.entity.Projectile;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
@Singleton
@ModuleName("Projectile Tracker")
public class ProjectileTracker extends WrappedBukkitRunnable implements ActivableModule {
private final Collection<TrackedProjectile> trackedProjectiles = new CacheCollection<>(cacheBuilder -> cacheBuilder.expireAfterWrite(5, TimeUnit.MINUTES));
private final CorePlugin plugin;
@Inject private ProjectileTracker(CorePlugin plugin) {
this.plugin = plugin;
}
@Override
public void onEnable() {
runTaskTimer(plugin, 0L, 1L);
}
@Override
public void run() {
for (TrackedProjectile trackedProjectile : trackedProjectiles) {
if(!trackedProjectile.isValid()) {
trackedProjectiles.remove(trackedProjectile);
return;
}
if(!trackedProjectile.canSpawn()) {
return;
}
Location location = trackedProjectile.getProjectile().getLocation();
FastParticle.spawnParticle(location.getWorld(), trackedProjectile.getParticleType(), location, 1, 0, 0, 0, 0);
}
}
public void trackProjectile(Projectile projectile, ProjectileTrail projectileTrail) {
trackedProjectiles.add(new TrackedProjectile(projectile, projectileTrail));
}
}
| 1,838 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ProjectileTrail.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/projectiletrails/ProjectileTrail.java | package me.patothebest.gamecore.cosmetics.projectiletrails;
import fr.mrmicky.fastparticle.ParticleType;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopItem;
import me.patothebest.gamecore.file.ParserValidations;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
public class ProjectileTrail extends AbstractShopItem {
private final ParticleType particleType;
private final ItemStack displayItem;
private final int durationInMillis;
private final int interval;
public ProjectileTrail(String configName, Map<String, Object> data) {
super(configName, data);
this.particleType = Utils.getEnumValueFromString(ParticleType.class, (String) data.get("effect"));
this.displayItem = Utils.itemStackFromString((String) data.get("display-item"));
this.durationInMillis = ((int) data.getOrDefault("duration", 300))*1000;
this.interval = (int) data.getOrDefault("interval", 2);
ParserValidations.isTrue(particleType.isSupported(), "The particle effect " + particleType.getName() + " is not supported on this version.");
}
@Override
public ItemStack getDisplayItem() {
return displayItem;
}
public ParticleType getParticleType() {
return particleType;
}
public int getDurationInMillis() {
return durationInMillis;
}
public int getInterval() {
return interval;
}
}
| 1,465 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
TrackedProjectile.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/projectiletrails/TrackedProjectile.java | package me.patothebest.gamecore.cosmetics.projectiletrails;
import fr.mrmicky.fastparticle.ParticleType;
import org.bukkit.entity.Projectile;
import java.lang.ref.WeakReference;
class TrackedProjectile {
private final WeakReference<Projectile> projectile;
private final ProjectileTrail projectileTrail;
private long groundTime = 0;
private int ticksLived;
TrackedProjectile(Projectile projectile, ProjectileTrail projectileTrail) {
this.projectile = new WeakReference<>(projectile);
this.projectileTrail = projectileTrail;
}
boolean isValid() {
if(projectile.get() == null || projectile.get().isDead()) {
return false;
}
if(!projectile.get().isOnGround()) {
return true;
}
if(groundTime == 0) {
groundTime = System.currentTimeMillis();
}
return System.currentTimeMillis() - groundTime < getDurationInMillis();
}
Projectile getProjectile() {
return projectile.get();
}
ParticleType getParticleType() {
return projectileTrail.getParticleType();
}
int getDurationInMillis() {
return projectileTrail.getDurationInMillis();
}
boolean canSpawn() {
return ticksLived++ % projectileTrail.getInterval() == 0;
}
}
| 1,321 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
TrackedWalkTrail.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/walkparticles/TrackedWalkTrail.java | package me.patothebest.gamecore.cosmetics.walkparticles;
import fr.mrmicky.fastparticle.ParticleType;
class TrackedWalkTrail {
private final WalkTrail walkTrail;
private int ticksLived;
TrackedWalkTrail(WalkTrail walkTrail) {
this.walkTrail = walkTrail;
}
ParticleType getParticleType() {
return walkTrail.getParticleType();
}
int getAmount () {
return walkTrail.getAmount();
}
boolean canSpawn() {
return ticksLived++ % walkTrail.getInterval() == 0;
}
}
| 534 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
WalkTrail.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/walkparticles/WalkTrail.java | package me.patothebest.gamecore.cosmetics.walkparticles;
import fr.mrmicky.fastparticle.ParticleType;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopItem;
import me.patothebest.gamecore.file.ParserValidations;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
public class WalkTrail extends AbstractShopItem {
private final ParticleType particleType;
private final ItemStack displayItem;
private final int interval;
private final int amount;
public WalkTrail(String configName, Map<String, Object> data) {
super(configName, data);
this.particleType = Utils.getEnumValueFromString(ParticleType.class, (String) data.get("effect"));
this.displayItem = Utils.itemStackFromString((String) data.get("display-item"));
this.interval = (int) data.getOrDefault("interval", 2);
this.amount = (int) data.getOrDefault("amount", 1);
ParserValidations.isTrue(particleType.isSupported(), "The particle effect " + particleType.getName() + " is not supported on this version.");
}
@Override
public ItemStack getDisplayItem() {
return displayItem;
}
public ParticleType getParticleType() {
return particleType;
}
public int getInterval() {
return interval;
}
public int getAmount() {
return amount;
}
}
| 1,399 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
WalkTrailsManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/walkparticles/WalkTrailsManager.java | package me.patothebest.gamecore.cosmetics.walkparticles;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import fr.mrmicky.fastparticle.FastParticle;
import fr.mrmicky.fastparticle.ParticleType;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopManager;
import me.patothebest.gamecore.event.player.PlayerDeSelectItemEvent;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.phase.phases.GamePhase;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.player.PlayerSelectItemEvent;
import me.patothebest.gamecore.event.player.PlayerStateChangeEvent;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashMap;
import java.util.Map;
@Singleton
@ModuleName("Walk Trails Manager")
public class WalkTrailsManager extends AbstractShopManager<WalkTrail> {
private final Map<Player, TrackedWalkTrail> walkTrails = new HashMap<>();
@Inject private WalkTrailsManager(CorePlugin plugin, PlayerManager playerManager) {
super(plugin, playerManager);
shopItemTypeObjectProvider = WalkTrail::new;
}
@EventHandler
public void onJoin(ArenaPhaseChangeEvent event) {
if (!(event.getNewPhase() instanceof GamePhase)) {
return;
}
for (Player player : event.getArena().getPlayers()) {
trackPlayer(player);
}
}
@EventHandler
public void onDeath(PlayerStateChangeEvent event) {
if (event.getPlayerState() == PlayerStateChangeEvent.PlayerState.PLAYER) {
return;
}
walkTrails.remove(event.getPlayer());
}
@EventHandler
public void onAlive(PlayerStateChangeEvent event) {
if (event.getPlayerState() != PlayerStateChangeEvent.PlayerState.PLAYER) {
return;
}
if (event.getArena().isInGame()) {
trackPlayer(event.getPlayer());
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
walkTrails.remove(event.getPlayer());
}
@EventHandler
public void onSelect(PlayerSelectItemEvent event) {
trackPlayer(event.getPlayer().getPlayer());
}
@EventHandler
public void onDeselect(PlayerDeSelectItemEvent event) {
walkTrails.remove(event.getPlayer().getPlayer());
}
private void trackPlayer(Player player) {
IPlayer corePlayer = playerManager.getPlayer(player);
if(!corePlayer.isPlaying()) {
return;
}
WalkTrail selectedItem = corePlayer.getSelectedItem(WalkTrail.class);
if(selectedItem == null) {
return;
}
walkTrails.put(player, new TrackedWalkTrail(selectedItem));
}
@EventHandler
public void onMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
TrackedWalkTrail walkTrail = walkTrails.get(player);
if (walkTrail == null) {
return;
}
if (player.isSneaking()){
return;
}
if(!walkTrail.canSpawn()) {
return;
}
for (int i = 0; i < walkTrail.getAmount(); i++) {
Location location = player.getLocation();
double distance = Utils.randDouble(0, 1);
double angle = Utils.randDouble(0, Math.PI * 2);
location.add(Math.cos(angle) * distance, Utils.randDouble(0, 0.375), Math.sin(angle) * distance);
if (walkTrail.getParticleType() == ParticleType.NOTE) {
FastParticle.spawnParticle(location.getWorld(), walkTrail.getParticleType(), location, 1, 0, 0, 0, Utils.randInt(0, 24));
} else {
FastParticle.spawnParticle(location.getWorld(), walkTrail.getParticleType(), location, 1, 0, 0, 0, 0);
}
}
}
@Override
public ILang getTitle() {
return CoreLang.SHOP_WALK_TRAILS_TITLE;
}
@Override
public ILang getName() {
return CoreLang.SHOP_WALK_TRAILS_NAME;
}
@Override
public String getShopName() {
return "walk-trails";
}
}
| 4,540 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RepeatingVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/RepeatingVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects;
import com.google.inject.Inject;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.util.WrappedBukkitRunnable;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class RepeatingVictoryEffect implements IVictoryEffect {
@Inject private CorePlugin plugin;
@Override
public final void display(IPlayer player) {
AtomicInteger times = new AtomicInteger(0);
new WrappedBukkitRunnable() {
@Override
public void run() {
if (!player.getPlayer().isOnline()) {
cancel();
return;
}
if (!player.isInArena()) {
cancel();
return;
}
if (times.incrementAndGet() > (20.0 / getPeriod()) * 15.0) {
cancel();
return;
}
displayEffect(player);
}
}.runTaskTimer(plugin, 0L, getPeriod());
}
public abstract void displayEffect(IPlayer player);
public abstract long getPeriod();
}
| 1,224 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
IVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/IVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects;
import me.patothebest.gamecore.player.IPlayer;
import org.bukkit.event.Listener;
public interface IVictoryEffect extends Listener {
void display(IPlayer player);
}
| 229 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
VictoryEffectItem.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/VictoryEffectItem.java | package me.patothebest.gamecore.cosmetics.victoryeffects;
import com.google.common.base.Preconditions;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopItem;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
public class VictoryEffectItem extends AbstractShopItem {
private final VictoryEffectType victoryEffectType;
private final ItemStack displayItem;
VictoryEffectItem(String configName, Map<String, Object> data) {
super(configName, data);
this.displayItem = Utils.itemStackFromString((String) data.get("display-item"));
this.victoryEffectType = Utils.getEnumValueFromString(VictoryEffectType.class, (String) data.get("effect"));
Preconditions.checkNotNull(displayItem, "Material " + data.get("display-item") + " not found!");
Preconditions.checkNotNull(displayItem, "Effect " + data.get("effect") + " not found!");
}
@Override
public ItemStack getDisplayItem() {
return displayItem;
}
public void display(IPlayer player) {
victoryEffectType.getVictoryEffect().display(player);
}
}
| 1,195 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
VictoryEffectType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/VictoryEffectType.java | package me.patothebest.gamecore.cosmetics.victoryeffects;
import com.google.inject.Injector;
import me.patothebest.gamecore.cosmetics.victoryeffects.types.DayCycleVictoryEffect;
import me.patothebest.gamecore.cosmetics.victoryeffects.types.FireworkVictoryEffect;
import me.patothebest.gamecore.cosmetics.victoryeffects.types.LavaPopVictoryEffect;
import me.patothebest.gamecore.cosmetics.victoryeffects.types.RainDiscoVictoryEffect;
import me.patothebest.gamecore.cosmetics.victoryeffects.types.RainWoolVictoryEffect;
public enum VictoryEffectType {
FIREWORK(FireworkVictoryEffect.class),
LAVA_POP(LavaPopVictoryEffect.class),
RAIN_DISCO(RainDiscoVictoryEffect.class),
RAIN_WOOL(RainWoolVictoryEffect.class),
DAY_CYCLE(DayCycleVictoryEffect.class);
private final Class<? extends IVictoryEffect> iVictoryEffectClass;
private IVictoryEffect iVictoryEffect;
VictoryEffectType(Class<? extends IVictoryEffect> iVictoryEffectClass) {
this.iVictoryEffectClass = iVictoryEffectClass;
}
public IVictoryEffect getVictoryEffect() {
return iVictoryEffect;
}
public static void init(Injector injector) {
for (VictoryEffectType value : values()) {
value.iVictoryEffect = injector.getInstance(value.iVictoryEffectClass);
}
}
}
| 1,315 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
VictoryManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/VictoryManager.java | package me.patothebest.gamecore.cosmetics.victoryeffects;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import me.patothebest.gamecore.cosmetics.shop.AbstractShopManager;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.player.PlayerManager;
@Singleton
@ModuleName("Victory Effects")
public class VictoryManager extends AbstractShopManager<VictoryEffectItem> {
private final EventRegistry eventRegistry;
private final Provider<Injector> injectorProvider;
@Inject private VictoryManager(CorePlugin plugin, PlayerManager playerManager, EventRegistry eventRegistry, Provider<Injector> injectorProvider) {
super(plugin, playerManager);
this.eventRegistry = eventRegistry;
this.injectorProvider = injectorProvider;
shopItemTypeObjectProvider = VictoryEffectItem::new;
}
@Override
public void onPreEnable() {
VictoryEffectType.init(injectorProvider.get());
super.onPreEnable();
}
@Override
public void onEnable() {
for (VictoryEffectType value : VictoryEffectType.values()) {
eventRegistry.registerListener(value.getVictoryEffect());
}
}
@Override
public void onDisable() {
for (VictoryEffectType value : VictoryEffectType.values()) {
eventRegistry.unRegisterListener(value.getVictoryEffect());
}
}
@Override
public ILang getTitle() {
return CoreLang.SHOP_WIN_EFFECTS_TITLE;
}
@Override
public ILang getName() {
return CoreLang.SHOP_WIN_EFFECTS_TRAIL_NAME;
}
@Override
public String getShopName() {
return "victory-effects";
}
}
| 1,970 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
DayCycleVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/types/DayCycleVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects.types;
import me.patothebest.gamecore.cosmetics.victoryeffects.RepeatingVictoryEffect;
import me.patothebest.gamecore.player.IPlayer;
import org.bukkit.World;
public class DayCycleVictoryEffect extends RepeatingVictoryEffect {
@Override
public void displayEffect(IPlayer player) {
World world = player.getCurrentArena().getWorld();
world.setTime(world.getTime() + 100L);
}
@Override
public long getPeriod() {
return 1;
}
}
| 532 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RainDiscoVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/types/RainDiscoVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects.types;
import com.google.inject.Inject;
import com.google.inject.Provider;
import me.patothebest.gamecore.cosmetics.victoryeffects.RepeatingVictoryEffect;
import me.patothebest.gamecore.itemstack.StainedClay;
import me.patothebest.gamecore.nms.NMS;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.util.Sounds;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.Location;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class RainDiscoVictoryEffect extends RepeatingVictoryEffect {
private final List<FallingBlock> blocks = new ArrayList<>();
@Inject private Provider<NMS> nmsProvider;
@EventHandler
public void onEntityChangeBlock(final EntityChangeBlockEvent e) {
if (!(e.getEntity() instanceof FallingBlock)) {
return;
}
if (this.blocks.contains(e.getEntity())) {
e.setCancelled(true);
}
}
@Override
public void displayEffect(IPlayer player) {
final Location loc = player.getLocation().add(0.5, 1.5, 0.5);
for (int i = 0; i < 15; ++i) {
final FallingBlock block = nmsProvider.get().spawnFallingBlock(loc, StainedClay.getRandomMaterial());
block.setDropItem(false);
block.setVelocity(new Vector(Utils.randDouble(-0.5, 0.5), Utils.getRandom().nextDouble() + 0.5, Utils.randDouble(-0.5, 0.5)));
player.playSound(Sounds.ENTITY_ITEM_PICKUP);
this.blocks.add(block);
}
}
@Override
public long getPeriod() {
return 10;
}
}
| 1,788 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
LavaPopVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/types/LavaPopVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects.types;
import fr.mrmicky.fastparticle.FastParticle;
import fr.mrmicky.fastparticle.ParticleType;
import me.patothebest.gamecore.cosmetics.victoryeffects.RepeatingVictoryEffect;
import me.patothebest.gamecore.player.IPlayer;
public class LavaPopVictoryEffect extends RepeatingVictoryEffect {
@Override
public void displayEffect(IPlayer player) {
for (int i = 0; i < 30; ++i) {
FastParticle.spawnParticle(player.getPlayer().getWorld(), ParticleType.LAVA, player.getLocation(), 1);
}
}
@Override
public long getPeriod() {
return 20;
}
}
| 655 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RainWoolVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/types/RainWoolVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects.types;
import com.google.inject.Inject;
import com.google.inject.Provider;
import me.patothebest.gamecore.cosmetics.victoryeffects.RepeatingVictoryEffect;
import me.patothebest.gamecore.itemstack.ColoredWool;
import me.patothebest.gamecore.nms.NMS;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.util.Sounds;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.Location;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class RainWoolVictoryEffect extends RepeatingVictoryEffect {
private final List<FallingBlock> blocks = new ArrayList<>();
@Inject private Provider<NMS> nmsProvider;
@EventHandler
public void onEntityChangeBlock(final EntityChangeBlockEvent e) {
if (!(e.getEntity() instanceof FallingBlock)) {
return;
}
if (this.blocks.contains(e.getEntity())) {
e.setCancelled(true);
}
}
@Override
public void displayEffect(IPlayer player) {
final Location loc = player.getLocation().add(0.5, 1.5, 0.5);
for (int i = 0; i < 15; ++i) {
final FallingBlock block = nmsProvider.get().spawnFallingBlock(loc, ColoredWool.getRandomMaterial());
block.setDropItem(false);
block.setVelocity(new Vector(Utils.randDouble(-0.5, 0.5), Utils.getRandom().nextDouble() + 0.5, Utils.randDouble(-0.5, 0.5)));
player.playSound(Sounds.ENTITY_ITEM_PICKUP);
this.blocks.add(block);
}
}
@Override
public long getPeriod() {
return 10;
}
}
| 1,786 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
FireworkVictoryEffect.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/cosmetics/victoryeffects/types/FireworkVictoryEffect.java | package me.patothebest.gamecore.cosmetics.victoryeffects.types;
import me.patothebest.gamecore.cosmetics.victoryeffects.RepeatingVictoryEffect;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.meta.FireworkMeta;
public class FireworkVictoryEffect extends RepeatingVictoryEffect {
@Override
public void displayEffect(IPlayer player) {
Firework firework = (Firework) player.getPlayer().getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK);
FireworkMeta fireworkMeta = firework.getFireworkMeta();
fireworkMeta.addEffect(Utils.getRandomEffect());
firework.setFireworkMeta(fireworkMeta);
}
@Override
public long getPeriod() {
return 20;
}
}
| 858 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CoreLocaleManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/CoreLocaleManager.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.ChatColor;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.TreeMap;
public abstract class CoreLocaleManager {
private static final Map<String, Locale> LOCALES = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
public static Locale DEFAULT_LOCALE;
protected final CorePlugin plugin;
private final ILang[] pluginLangValues;
public CoreLocaleManager(CorePlugin plugin, ILang[] pluginLangValues) {
this.plugin = plugin;
this.pluginLangValues = pluginLangValues;
DEFAULT_LOCALE = getOrCreateLocale("en");
loadLocales(new File(Utils.PLUGIN_DIR, "l10n"));
}
public void loadLocales(File localeDirectory) {
try {
String[] locales = Utils.getResourceListing(plugin.getClass(), "locale/");
for (String locale : locales) {
if (locale.isEmpty()) {
continue;
}
getOrCreateLocale(locale.replace(".yml", ""));
}
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
if (localeDirectory.listFiles() != null) {
for (File file : localeDirectory.listFiles()) {
try {
getOrCreateLocale(file.getName().replace(".yml", ""));
} catch (Throwable t) {
plugin.log(ChatColor.RED + "Could not load locale " + file.getName() + "!");
t.printStackTrace();
}
}
}
}
public Locale getOrCreateLocale(String localeName) {
if (LOCALES.containsKey(localeName)) {
return LOCALES.get(localeName);
}
Locale locale = new Locale(localeName);
LOCALES.put(localeName, locale);
plugin.log(ChatColor.YELLOW + "loading locale " + locale.getName());
initializeLangFile(locale);
plugin.log("Loaded locale " + locale.getName());
return locale;
}
public static Locale getLocale(String locale) {
return LOCALES.get(locale);
}
public static Locale getOrDefault(String locale, Locale defaultLocale) {
return LOCALES.getOrDefault(locale, defaultLocale);
}
protected void initializeLangFile(Locale locale) {
File file = new File(Utils.PLUGIN_DIR, "l10n/" + locale.getName() + ".yml");
new LocaleFile(plugin, locale, file, Utils.concatenateArray(CoreLang.values(), pluginLangValues, ILang.class));
}
public static Map<String, Locale> getLocales() {
return LOCALES;
}
}
| 2,822 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CoreComments.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/CoreComments.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.lang.interfaces.IComment;
public enum CoreComments implements IComment {
COMMAND_DESCRIPTIONS(false, "Command Descriptions"),
USER_COMMANDS(true, "", "User Commands"),
ERRORS_IN_CMD_ARGS(false, "", "Errors in command arguments"),
SUCCESSFUL_EXECUTION(false, "", "Successful Messages"),
SETUP_COMMANDS(true, "", "Setup Commands"),
ERRORS(true, "", "Errors"),
SETUP_ERRORS(false, "Setup errors"),
GUI_MESSAGES(true, "", "Graphical User Interface Messages"),
GUI_GENERAL_MESSAGES(false, "General GUI messages"),
GUI_MAIN(false, "", "Main menu messages"),
GUI_CHOOSE_ARENA(false, "", "Choose arena menu messages"),
GUI_CHOOSE_KIT(false, "", "Choose kit menu messages"),
GUI_EDIT_KIT_LAYOUT(false, "", "Edit kit layout menu messages"),
GUI_USER_CHOOSE_TEAM(false, "", "Choose team menu messages"),
GUI_CHOOSE_LOCALE(false, "", "Locale menu messages"),
GUI_EDIT_ARENA(false, "", "Edit arena menu messages"),
GUI_CHOOSE_TEAM(false, "", "Choose team menu messages"),
GUI_EDIT_TEAM(false, "", "Edit team menu messages"),
GUI_CHOOSE_POINT_AREA(false, "", "Choose point area menu messages"),
GUI_EDIT_POINT_AREA(false, "", "Edit point area menu messages"),
GUI_CHOOSE_DROPPER(false, "", "Choose dropper menu messages"),
GUI_EDIT_DROPPER(false, "", "Edit dropper menu messages"),
GUI_EDIT_INTERVAL(false, "", "Edit interval menu messages"),
GUI_EDIT_PLAYERS(false, "", "Edit players menu messages"),
GUI_EDIT_ITEM(false, "", "Edit item menu messages"),
GUI_CHANGE_AMOUNT(false, "", "Change item amount menu messages"),
GUI_CHANGE_DATA(false, "", "Change item data menu messages"),
GUI_CHOOSE_KIT_TO_EDIT(false, "", "Choose kit to edit menu messages"),
GUI_CHOOSE_POTION_EFFECT(false, "", "Choose potion effects menu messages"),
GUI_EDIT_KIT(false, "", "Edit kit menu messages"),
GUI_EDIT_PRICE(false, "", "Edit price menu messages"),
GUI_PREVIEW_KIT(false, "", "Preview kit menu messages"),
GUI_KIT_EDIT_POTION_EFFECT(false, "", "Edit potion effect menu messages"),
GUI_DESCRIPTION_EDITOR(false, "", "Description editor line menu messages"),
GUI_DESCRIPTION_EDITOR_MAIN(false, "", "Description editor main page menu messages"),
GUI_ADMIN(false, "", "Admin menu messages");
private final boolean header;
private final String[] lines;
CoreComments(boolean header, String... lines) {
this.header = header;
this.lines = lines;
}
public boolean isHeader() {
return header;
}
public String[] getLines() {
return lines;
}
}
| 2,692 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
LocaleFile.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/LocaleFile.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.lang.interfaces.IComment;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.chat.ChatColorEscaper;
import me.patothebest.gamecore.file.FlatFile;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class LocaleFile extends FlatFile {
private final CorePlugin plugin;
private final Locale locale;
private final ILang[] lang;
public LocaleFile(CorePlugin plugin, Locale locale, File file, ILang... iLangs) {
super(file);
this.plugin = plugin;
this.lang = iLangs;
this.header = "Locale File";
this.locale = locale;
load();
}
@Override
public void load() {
super.load();
try (InputStream coreLocaleStream = plugin.getResource("corelocale/" + locale.getName() + ".yml");
InputStream localeStream = plugin.getResource("locale/" + locale.getName() + ".yml")){
if (coreLocaleStream == null || localeStream == null) {
boolean regenerate = false;
for(ILang message : lang) {
if(message.isComment()) {
continue;
}
if(getString(message.getPath()) == null) {
regenerate = true;
message.setMessage(locale, message.getDefaultMessage());
continue;
}
message.setMessage(locale, getString(message.getPath()));
}
if(regenerate) {
delete();
generateFile();
}
return;
}
YamlConfiguration resourceFile = new YamlConfiguration();
resourceFile.loadFromString(fileToYAML(coreLocaleStream));
resourceFile.loadFromString(fileToYAML(localeStream));
boolean regenerate = false;
for (ILang message : lang) {
if(message.isComment()) {
continue;
}
String resourceMessage = resourceFile.getString(message.getPath());
String fileMessage = getString(message.getPath());
String defaultMessage = message.getDefaultMessage();
if(resourceMessage == null) {
if (fileMessage == null) {
message.setMessage(locale, defaultMessage);
regenerate = true;
} else {
message.setMessage(locale, fileMessage);
}
continue;
}
if (fileMessage == null) {
message.setMessage(locale, ChatColorEscaper.toColorCodes(resourceMessage));
regenerate = true;
} else {
if (fileMessage.equalsIgnoreCase(message.getDefaultMessage()) &&
!fileMessage.equalsIgnoreCase(ChatColorEscaper.toColorCodes(resourceMessage))) {
message.setMessage(locale, ChatColorEscaper.toColorCodes(resourceMessage));
regenerate = true;
} else {
message.setMessage(locale, fileMessage);
}
}
}
if(regenerate) {
System.out.println("Regenerating file!");
delete();
generateFile();
}
} catch (InvalidConfigurationException | IOException e) {
e.printStackTrace();
}
}
@Override
public void writeFile(BufferedWriter writer) throws IOException {
for (ILang lang : lang) {
if(lang.isComment()) {
IComment comment = lang.getComment();
for (String s : comment.getLines()) {
if(s.isEmpty()) {
writer.write("\n\n");
continue;
}
if(lang.getComment().isHeader()) {
writer.write(getHeader(s));
} else {
writer.write("# " + s + "\n");
}
}
} else {
writer.write(lang.getPath() + ": " + "\"" + (lang.getRawMessage(locale) == null ? lang.getDefaultMessage() : lang.getRawMessage(locale)) + "\"\n");
}
}
}
}
| 4,737 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CoreLang.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/CoreLang.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.PluginConfig;
import me.patothebest.gamecore.chat.ChatColorEscaper;
import me.patothebest.gamecore.lang.interfaces.IComment;
import me.patothebest.gamecore.lang.interfaces.ILang;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;
public enum CoreLang implements ILang {
// -----------------------------------
// General Messages
// -----------------------------------
HEADER(CommentType.HEADER, "Game Core Messages"),
GENERAL(CommentType.SUBHEADER_NOT_SPACED, "General Messages"),
NAME("English"),
SKIN("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNGNhYzk3NzRkYTEyMTcyNDg1MzJjZTE0N2Y3ODMxZjY3YTEyZmRjY2ExY2YwY2I0YjM4NDhkZTZiYzk0YjQifX19"),
PREFIX("&8[&c%plugin_prefix%&8]: &7", "plugin_prefix"),
PAGE("(Page %page% of %pages%)", "page", "pages"),
INVALID_PAGRE("&cInvalid Page! (Page %page% of %pages%)", "page", "pages"),
NO_PERMISSION("&cYou do not have permission to perform this command!"),
COMMAND_CORRECTION("&7Did you mean &6%correction%&7?", "correction"),
TOO_FEW_ARGUMENTS("&cToo few arguments"),
TOO_MANY_ARGUMENTS("&cToo many arguments"),
USAGE("&cUsage: %usage%", "usage"),
UNKNOWN_FLAG("&cUnknown flag %flag%", "flag"),
NOT_A_NUMBER("&c'%string%' is not a number!", "string"),
OUT_OF_BOUNDS("Out of bounds!"),
NO_RESULTS("&cThere are no results."),
CONFIRM(true, "Type &6/%base_command% confirm &7to confirm."),
CONFIRM_DESC("Confirms an action"),
NO_CONFIRMATION("No action to be confirmed."),
MONEY_GIVEN("&6+%amount% coins", "amount"),
SPECTATOR("Spectator"),
LOADING("Loading..."),
DATABASE_REQUIREMENT("This requires a running database!"),
LINE_SEPARATOR("&a&m" + StringUtils.repeat(" ", 80)),
TIME_MONTHS("months"),
TIME_MONTH("month"),
TIME_WEEKS("weeks"),
TIME_WEEK("week"),
TIME_DAYS("days"),
TIME_DAY("day"),
TIME_HOURS("hours"),
TIME_HOUR("hour"),
TIME_MINUTES("minutes"),
TIME_MINUTE("minute"),
TIME_SECONDS("seconds"),
TIME_SECOND("second"),
// -----------------------------------
// User Commands
// -----------------------------------
// Command descriptions
USER_HEADER(CoreComments.USER_COMMANDS),
USER_COMMAND_DESCRIPTIONS(CoreComments.COMMAND_DESCRIPTIONS),
JOIN_ARENA("Join an arena"),
SPEC_ARENA("Spectate an arena"),
LEAVE_ARENA("Leave an arena"),
LIST_ARENAS("List all the arenas"),
KIT_COMMAND("Opens the menu to choose a kit"),
KIT_COMMAND_DESCRIPTION("Command for kits"),
LOCALE_COMMAND("Opens the menu to change your language"),
// Errors in command arguments
USER_COMMAND_ERRORS(CoreComments.ERRORS_IN_CMD_ARGS),
ARENA_IS_NOT_PLAYABLE(true, "&cThe arena you are trying to play is not available."),
ARENA_IS_RESTARTING(true, "&cThe arena is restarting. Please try again later."),
ARENA_HAS_STARTED(true, "&cThe arena has already started."),
ALREADY_IN_ARENA(true, "&cYou are already in an arena!"),
NOT_IN_AN_ARENA(true, "&cYou are not in an arena!"),
ARENA_IS_FULL(true, "&cThe arena you are trying to join is currently full"),
NO_ARENAS(true, "&cThere are no arenas to play."),
// Successful messages
USER_SUCCESSFUL_EXECUTION(CoreComments.SUCCESSFUL_EXECUTION),
ARENA_ENABLED_SHORT("enabled"),
ARENA_DISABLED_SHORT("disabled"),
ARENAS(true, "Arenas: "),
// -----------------------------------
// Arena Setup Commands
// -----------------------------------
// Command descriptions
SETUP_HEADER(CommentType.HEADER, "Arena Setup Commands"),
SETUP_COMMAND_DESCRIPTIONS(CoreComments.COMMAND_DESCRIPTIONS),
SETUP_COMMAND_DESCRIPTION("Command for setup"),
TEAMS_COMMAND_DESCRIPTION("Command for teams"),
NEW_ARENA("Creates a new arena"),
IMPORT_ARENA("Imports an arena world"),
NEW_TEAM("Creates a new team for the arena"),
NEW_DROPPER("Creates item spawner on your location"),
NEW_TEAM_SPAWN("Sets the team spawn for the specified team"),
PROTECTED_AREAS_LIST("Protects an area on the arena"),
PROTECT_AREA("Lists all the protected areas"),
SET_LOBBY_LOCATION("Sets the arena lobby location"),
SET_SPECTATOR_LOCATION("Sets the arena spectator location"),
ENABLE_ARENA("Enables an arena to be playable"),
DISABLE_ARENA("Disables an arena to allow it to be modified"),
TELEPORT_TO_ARENA("Teleports to the arena"),
CHECK_ARENA("Checks to see whether or not an arena can be enabled"),
SET_ARENA_AREA("Sets the arena's playable area"),
SET_LOBBY_AREA("Sets the lobby's area"),
SHOW_ARENA_AREA("Shows the arena's area"),
HIDE_ARENA_AREA("Hides the arena's area"),
SET_MAIN_LOBBY("Sets the main lobby"),
TP_MAIN_LOBBY("Teleports you to the main lobby"),
SET_MIN_PLAYERS("Sets the minimum amount of players for the arena"),
SET_MAX_PLAYERS("Sets the maximum amount of players for the arena"),
OPEN_GUI("Opens the graphical user interface"),
DELETE_ARENA("Deletes an arena"),
CLEAR_ARENA("Clears an arena's configuration"),
// Errors in command arguments
SETUP_COMMAND_ERRORS(CoreComments.ERRORS_IN_CMD_ARGS),
TEAM_COLOR_NOT_FOUND(true, "&cTeam color not found."),
NO_PERMISSION_ARENA(true, "&cYou do not have permission to join this arena!"),
TEAM_COLOR_ALREADY_EXIST(true, "&cTeam color already exist!"),
TEAM_COLOR_DOES_NOT_EXIST(true, "&cTeam color doesn't exist!"),
TEAM_DOES_NOT_EXIST(true, "&cTeam doesn't exist"),
ARENA_ALREADY_DISABLED(true, "&cThe arena is already disabled!"),
ARENA_ALREADY_ENABLED(true, "&cThe arena is already enabled!"),
DISABLE_ARENA_FIRST(true, "&cTo modify an arena you must disable it first using /%base_command% setup disablearena <arena>"),
ENABLE_ARENA_FIRST(true, "&cTo use this command you need to enable the arena first"),
WRONG_ITEMSTACK_FORMAT(true, "&cThe item could not be parsed. %newline%Please use the format material:data,amount (wool:14,32 = 32 red wool"),
ARENA_ALREADY_EXIST(true, "&cArena already exist!"),
ARENA_DOES_NOT_EXIST(true, "&cArena doesn't exist!"),
FOLDER_DOESNT_EXIST(true, "&cA world with that name doesn't exist! Please verify the world name."),
ARENA_IS_FILE(true, "&cThere's no world folder with that arena name"),
SOMETHING_WENT_WRONG_IMPORTING(true, "&cSomething went wrong while importing world. Couldn't rename directory."),
AREA_DOES_NOT_EXIST(true, "&cArea doesn't exist!"),
// Successful messages
SETUP_SUCCESSFUL_EXECUTION(CoreComments.SUCCESSFUL_EXECUTION),
TEAM_CREATED(true, "&aTeam successfully created!"),
TEAM_SPAWN_SET(true, "&aTeam spawn has been set!"),
TEAM_POINT_AREA_SET(true, "&aTeam point area has been added!"),
AREA_PROTECTED(true, "&aArea protected!"),
AREA_REMOVED(true, "&aArea removed!"),
MAIN_LOBBY_TP(true, "&aYou have been teleported to the main lobby!"),
SPAWN_TP(true, "&eSince the main lobby isn't set you have been teleported to the main world's spawn. Consider setting the main lobby using &6/%base_command% setup setmainlobby"),
LOBBY_LOCATION_SET(true, "&aLobby location has been set!"),
SPECTATOR_LOCATION_SET(true, "&aSpectator location has been set!"),
DROPPER_ADDED(true, "&aDropper has been added!"),
MIN_PLAYERS_SET(true, "&aMinimum amount of players have been set!"),
MAX_PLAYERS_SET(true, "&aMaximum amount of players have been set!"),
ARENA_ENABLED(true, "&aArena has been enabled!"),
ARENA_DISABLED(true, "&aArena has been disabled!"),
ARENA_AREA_SET(true, "&aArena's area has been set!"),
ARENA_LOBBY_AREA_SET(true, "&aArena's lobby area has been set!"),
TELEPORTED_TO_ARENA(true, "&aYou have been teleported to the arena."),
READY_ARENA(true, "&aThe arena is ready to be enabled."),
ARENA_CREATED(true, "&aArena successfully created!"),
ARENA_IMPORTED(true, "&aArena successfully imported!"),
NO_AREA_SET(true, "&cNo area has been established!"),
AREA_SHOWN(true, "&aArena's area has been shown!"),
AREA_HIDE(true, "&aArena's area has been hidden!"),
POINT1_SELECTED(true, "&bFirst position set to (%location%).", "location"),
POINT2_SELECTED(true, "&bSecond position set to (%location%).", "location"),
MAIN_LOBBY_SET(true, "&aMain Lobby has been set!"),
LIST_HEADER("&9Protected Areas of %arena%", "arena"),
ARENA_DELETED("&cArena has been deleted!"),
ARENA_CLEARED("&cArena has been cleared!"),
// -------------------------------------------- //
// Setup Commands
// -------------------------------------------- //
SETUP_COMMANDS(CommentType.HEADER, "Setup Commands"),
TREASURE_COMMADNS(CommentType.SUBHEADER_NOT_SPACED, "Treasure commands"),
TREASURE_ADD_DESC("Adds a treasure chest by right clicking a chest"),
YOU_MUST_RIGHT_CLICK_CHEST(true, "&cYou must right click a chest!"),
TREASURE_ADD(true, "Right click a chest to make it a treasure chest"),
TREASURE_ADDED(true, "&aA Treasure Chest has been created!"),
ARENA_GROUP_NOT_FOUND("&cThe arena group doesn't exist!"),
SIGN_COMMADNS(CommentType.SUBHEADER_SPACED, "Sign commands"),
SIGN_COMMAND_DESC("Command for signs"),
CREATE_SIGN("Creates a sign"),
LIST_SIGNS("List all the signs"),
SIGN_ADD_COMMAND_OVERRIDE("&cTo force add a sign for an arena that does not exist type &6/%base_command% signs add %arena% -c", "arena"),
SELECT_SIGN(true, "&aSelect a sign"),
SIGN_CREATED(true, "&aSign created!"),
SIGN_REMOVED(true, "&cSign removed!"),
KIT_COMMAND_HEADER(CommentType.SUBHEADER_SPACED, "Kit commands"),
KIT_CREATE("Create a kit"),
KIT_GUI("Opens the menu to edit kits"),
KIT_ALREADY_EXISTS("&cKit already exists!"),
NO_PERMISSION_KIT("&cYou do not have permission to choose this kit!"),
KIT_CREATED("&aKit successfully created!"),
KIT_DELETE("&cDelete"),
OPTION_COMMAND(CommentType.SUBHEADER_SPACED, "Option commands"),
OPTION_COMMAND_DESC("Modify all the additional arena options"),
OPTION_ENABLE_COMMAND("Enable an option for the specified arena"),
OPTION_DISABLE_COMMAND("Disable an option for the specified arena"),
OPTION_LIST_COMMAND("List all the available options for the arena"),
OPTION_SETTIME_COMMAND("Set the arena time of the day"),
OPTION_SETENVIRONMENT_COMMAND("Set the arena environment"),
OPTION_CANT_BE_ENABLED("This option cannot be enabled or disabled."),
OPTION_NOT_FOUND("&cThis option is not found! &7Use &6/%base_command% setup options list"),
OPTION_ENABLED("&6%option% &7has been &aenabled &7for arena &6%arena%", "option", "arena"),
OPTION_DISABLED("&6%option% &7has been &cdisabled &7for arena &6%arena%", "option", "arena"),
OPTION_TIME_CHANGED("&aTime has been set to: &6%time%", "time"),
OPTION_TIME("&b&lTime Option &6| &aCurrently: &e%time%","time"),
OPTION_TIME_DESC("&eChanges the time of the day the arena will be in"),
OPTION_TIME_CURRENT_TIME("&7The current time of the arena is: &6%time%", "time"),
OPTION_TIME_COMMAND("&7To change the time use &6/%base_command% setup options settime <arena> <time>"),
OPTION_TIME_LIST("&eAvailable time of day: &6Sunrise, Day, Noon, Sunset, Night, Midnight"),
OPTION_ENVIRONMENT_CHANGING("&6Changing environment, please wait..."),
OPTION_ENVIRONMENT_CHANGED("&aEnvironment has been set to: &6%environment%", "environment"),
OPTION_ENVIRONMENT("&b&lEnvironment Option &6| &aCurrently: &e%environment%","environment"),
OPTION_ENVIRONMENT_DESC("&eChanges the arena environment"),
OPTION_ENVIRONMENT_COMMAND("&7To change the environment use &6/%base_command% setup options setenvironment <arena> <environment>"),
OPTION_ENVIRONMENT_LIST("&eAvailable environments: &6Normal, Nether, End"),
OPTION_ENABLEABLE("&b&l%option% Option &6| &aCurrently: &e%status%", "option", "status"),
OPTION_ENABLEABLE_COMMAND("&7To enable or disable use &6/%base_command% setup options <enable|disable> <arena> %option%", "option"),
OPTION_TNT_EXPLOSIONS("Enable or disable tnt explosion block damage in the arena"),
OPTION_TIME_INVALID("The specified time is invalid!"),
// -------------------------------------------- //
// Admin commands
// -------------------------------------------- //
ADMIN_COMMANDS(CommentType.HEADER, "Admin Commands"),
ADMIN_COMMAND_DESC("Command for administrative commands"),
RELOAD_COMMANDS(CommentType.SUBHEADER_NOT_SPACED, "Reload commands"),
RELOAD_COMMAND_DESC("Reloads a module or various modules of the plugin"),
VERSION_COMMAND_DESC("Prints out the version of the plugin"),
FORCE_START("Force start an arena"),
FORCE_END("Force end an arena"),
RELOADABLE_MODULES("&aReloadable modules are:"),
RELOADED_MODULE("&a%module% reloaded in %time%ms", "module", "time"),
RELOADED_MODULE_FAIL("&cFailed to reload %module%! Please check console.", "module"),
RELOAD_UNKNOWN("&cUnknown module", "module"),
ARENA_ALREADY_STARTED("&cThe arena has already been started!"),
ARENA_NOT_STARTED("&cThe arena is not in-game!"),
ARENA_FORCE_STARTED("&aThe arena has been forced to start!"),
ARENA_FORCE_ENDED("&aThe arena has been forced to end!"),
CAGE_COMMANDS(CommentType.SUBHEADER_SPACED, "Cage commands"),
GIVE_CAGE_COMMAND("Gives a cage to a player"),
GIVE_ALL_CAGES_COMMAND("Gives all cage sto a player"),
REMOVE_CAGE_COMMAND("Removes a cage from a player"),
REMOVE_ALL_CAGES_COMMAND("Removes all cages from a player"),
INVALID_CAGE("&cCage is invalid!"),
PLAYER_OWNS_CAGE("&cPlayer owns cage!"),
CAGE_GIVEN("&aCage successfully given"),
CAGES_GIVEN("&aAll cages have been given"),
PLAYER_DOESNT_OWNS_CAGE("&cPlayer doesn't own cage!"),
CAGE_REMOVE("&aCage successfully removed"),
CAGES_REMOVED("&aAll cages have been removed"),
TREASURE_CHESTS_COMMANDS(CommentType.SUBHEADER_SPACED, "Treasure Chest commands"),
TREASURE_CHESTS_COMMAND_DESCRIPTION("Command for treasure chests"),
GIVE_TREASURE_CHESTS_COMMAND("Gives a treasure chest to a player (value can be negative to take)"),
GIVE_ALL_TREASURE_CHESTS_COMMAND("Gives all treasure chest types to a player"),
SET_TREASURE_CHEST_COMMAND("Sets the treasure chests amount of a type of a player"),
SET_ALL_TREASURE_CHEST_COMMAND("Sets the treasure chests amount of a player for all types"),
INVALID_TREASURE_CHEST("&Treasure chest is invalid!"),
TREASURE_CHESTS_GIVEN(true, "&6%player% &7now has &6%amount% &7chests for type &6%type%", "player", "amount", "type"),
STORAGE_COMMANDS(CommentType.SUBHEADER_SPACED, "Storage commands"),
CONVERT_COMMAND("Converts the storage"),
STORAGE_CANNOT_BE_SAME("Storage types must not be the same"),
STORAGE_CAN_ONLY_BE("Storage can only be either MySQL or FlatFile"),
STORAGE_TYPE("Type can only be Player or Kits"),
BUNGEE_COMMANDS(CommentType.SUBHEADER_SPACED, "Bungee commands"),
BUNGEE_COMMANDS_DESC("Bungee mode commands"),
CHANGE_ARENA("Change arena map"),
RESTART_SERVER("Stops the server when there are no players left"),
INVALID_ARENA("&cInvalid Arena!"),
NOT_IN_BUNGEE_MODE("&cPlugin is not in bungee mode!"),
ADD_PLAYER("Adds player to which arena he'll join when he joins the server"),
ARENA_CHANGED("&aArena changed!"),
// -----------------------------------
// Errors
// -----------------------------------
// Setup errors
ERROR_HEADER(CoreComments.ERRORS),
SETUP_ERRORS(CoreComments.SETUP_ERRORS),
SETUP_ERROR_SET_AREA("&cMissing area! Use &e/%base_command% setup setarenaarea &cto set it"),
SETUP_ERROR_LOBBY_LOCATION("&cMissing lobby location! Use &e/%base_command% setup setlobby"),
SETUP_ERROR_SPECTATOR_LOCATION("&cMissing spectator location! Use &e/%base_command% setup setspec"),
SETUP_ERROR_TEAM_MIN("&cMinimum amount of teams for a game is 2"),
SETUP_ERROR_TEAM_SPAWN_NULL("%teamcolor%%teamname% &cspawn is missing!"),
SETUP_ERROR_TEAM_POINT_AREA_NULL("%teamcolor%%teamname% &cmust have at least 1 point area!"),
SETUP_ERROR_MIN_PLAYERS("&cMinimum amount of players must be set to 2 or higher!"),
SETUP_ERROR_MIN_MAX("&cMinimum amount of players is set higher than the maximum amount of players!"),
// -------------------------------------------- //
// OTHER MESSAGES
// -------------------------------------------- //
CUBOID_TO_STRING("&7* &6%index%. &e%name% &6Cords: %cords%", "index", "name", "cords"),
SELECT_AN_AREA(true, "&cPlease select a cuboid area using a bone"),
SELECT_AN_AREA_WORLDEDIT("&cPlease select a cuboid area using worldedit selection"),
PLAYER_JOINED(true, "%player% &ejoined the game (&d%players%&e/&d%max_players%&e)", "player", "players", "max_players"),
CANNOT_PLACE_CHEST_ADJACENT(true, "&cYou cannot place a chest directly besides a map chest."),
RETURN_PLAYABLE_AREA("&4&lWARNING: &cReturn to playable area"),
YOU_HAVE_REACHED_PET_LIMIT("&cYou have reached the maximum amount of allowed pets."),
LOCATION_TO_INFO("&6World: %world% &eCoords: %coords%", "world", "coords"),
LOCATION_TO_COORDS("&eCoords: %coords%", "coords"),
// -------------------------------------------- //
// DEBUG
// -------------------------------------------- //
DEBUG_MODE("Toggle debug mode"),
DEBUG_MODE_TOGGLE(true, "&7Debug mode %status%", "status"),
EVENT_STATE_CHANGED(true, "&6%event% &7state changed to &6%state% &7by &6%plugin%", "event", "state", "plugin"),
// -------------------------------------------- //
// GAME MESSAGES
// -------------------------------------------- //
GAME(CommentType.HEADER, "Game messages"),
WINNERS("&eWinners &7- &7%winners%", "winners"),
FIRST_KILLER("&e1st Killer &7- &7%killer% &7- %kills%", "killer", "kills"),
SECOND_KILLER("&62nd Killer &7- &7%killer% &7- %kills%", "killer", "kills"),
THIRD_KILLER("&c3rd Killer &7- &7%killer% &7- %kills%", "killer", "kills"),
YOU_KILLED_ACTION_BAR("&e⚔ You killed %player% ⚔", "player"),
GAME_STARTING_TITLE("&c%game_title%", "seconds", "secondlang"),
GAME_STARTING_SUBTITLE("&7Starting in &6%seconds% &7%secondlang%.", "seconds", "secondlang"),
GAME_STARTING_CHAT(true, "&eThe game will start in &c%seconds% &e%secondlang%.", "seconds", "secondlang"),
TEAM_CAGE_RELEASING_TITLE("&cPrepare", "seconds", "secondlang"),
TEAM_CAGE_RELEASING_SUBTITLE("&7You will be released in &6%seconds% &7%secondlang%.", "seconds", "secondlang"),
TEAM_CAGE_RELEASING_CHAT(true, "&eYou will be released in &c%seconds% &e%secondlang%.", "seconds", "secondlang"),
SOLO_CAGE_RELEASING_TITLE("&f▶ %seconds% &f◀", "seconds", "secondlang"),
SOLO_CAGE_RELEASING_SUBTITLE("&e⚠ &cTeaming in SOLO is bannable &e⚠", "seconds", "secondlang"),
SOLO_CAGE_RELEASING_CHAT(true, "&eYou will be released in &c%seconds% &e%secondlang%.", "seconds", "secondlang"),
SECONDS("seconds"),
SECOND("second"),
YOU_CANNOT_EXECUTE_COMMANDS("&cYou cannot this execute command in-game!"),
COMPASS_TRACKER("&f&lNearest Player: &e%player% &f&lDistance: &e%distance%", "player", "distance"),
STARTING_MESSAGE("&a%arena% is starting! &eWant to join?", "arena"),
STARTING_MESSAGE_CLICK("&b&lClick Here!"),
STARTING_MESSAGE_HOVER("&aClick to join %arena%", "arena"),
BORDER_SHRINK_SOON_CHAT("&4&lWARNING: &c&lBorder will start shrinking in 30 seconds!"),
BORDER_SHRINK_SOON_SUBTITLE("&6Border will shrink soon!"),
BORDER_SHRINKING("&4&lWARNING: &c&lBorder is shrinking!"),
BORDER_SHRINKING_SUBTITLE("&6Border is shrinking!"),
CHESTS_REFILLED("&eChests refilled!"),
GRACE_PERIOD_ENDING("&eGrace period ending in &c%time% &e%secondlang%!", "time", "secondlang"),
GRACE_PERIOD_ENDED("&cGrace period ended!"),
DEATHMATCH_STARTING("&eDeathmatch starting in &c%time% &e%secondlang%", "time", "secondlang"),
DEATHMATCH_STARTED("&cDeathmatch started!"),
DEATHMATCH_YOU_CANNOT_THROW_TNT("&cYou cannot throw tnt while deathmatch is starting"),
WINNER_TITLE("&6Victory!"),
WINNER_SUBTITLE("&7You were the last man standing"),
DEATH_TITLE("&cYou died!"),
DEATH_SUBTITLE("&7You are now a spectator"),
DEATH_MESSAGE("&c&lYou died! &aWant to play again?"),
DEATH_MESSAGE_HOVER("&aClick to join a random arena"),
DEATH_MESSAGE_CLICK("&b&lClick Here!"),
LOSER_TITLE("&cGame Over"),
LOSER_SUBTITLE("&7You weren't victorious"),
LOBBY_CHOOSE_KIT("&6Choose kit"),
LOBBY_CHOOSE_TEAM("&6Choose team"),
LOBBY_CAGE_MENU("&fChange cage"),
LOBBY_PROJECTILE_TRAIL_MENU("&fChange projectile trail"),
LOBBY_WALK_TRAIL_MENU("&fChange walk trail"),
LOBBY_ADMIN_MENU("&cAdmin menu"),
LOBBY_LEAVE("&cLeave"),
LOBBY_GAME_OPTIONS("&7Game Options"),
// Admin main page
GUI_ADMIN(CoreComments.GUI_ADMIN),
GUI_ADMIN_TITLE("Arena admin menu"),
GUI_ADMIN_START_COUNTDOWN("&aStart countdown"),
GUI_ADMIN_STOP_COUNTDOWN("&cStop countdown"),
// -------------------------------------------- //
// SHOP messages
// -------------------------------------------- //
// General shop messages
SHOP_MESSAGES(CommentType.HEADER, "Shop messages") ,
GUI_SHOP_MESSAGES(CommentType.SUBHEADER_NOT_SPACED, "General shop messages"),
GUI_SHOP_PRICE("&7Price: &a%price%", "price"),
GUI_SHOP_FREE("free"),
GUI_SHOP_CURRENCY("Dollars"),
GUI_SHOP_WILL_BE_DEDUCTED("%amount%%currency% will be deducted from your account.", "amount", "currency"),
GUI_SHOP_NOT_ENOUGH_MONEY("&cYou do not have enough money to buy this item."),
GUI_SHOP_SELECTED("&aSelected"),
GUI_SHOP_CLICK_TO_SELECT("&aClick to select"),
GUI_SHOP_CLICK_TO_BUY("&aClick to buy"),
GUI_SHOP_LEFT_CLICK_SELECT("&aLeft-click to select"),
GUI_SHOP_RIGHT_CLICK("&aRight-click to buy uses"),
GUI_SHOP_USES_LORE("&aUses: &a%uses%", "uses"),
GUI_SHOP_YOU_BOUGHT("&aYou purchased %item%", "item"),
GUI_SHOP_YOU_SELECTED("&aYou selected %item%", "item"),
GUI_SHOP_NO_PERMISSION("&cYou need group %group%!", "group"),
GUI_SHOP_NO_PERMISSION_STRING("&cYou don't have permission!"),
GUI_SHOP_PURCHASED_USES("&aYou purchased %uses% use(s) for %item%", "uses", "item"),
// Kit Shop
GUI_USER_KIT_SHOP(CommentType.SUBHEADER_SPACED, "Kit Shop"),
GUI_KIT_SHOP_TITLE("Kit shop"),
GUI_KIT_SHOP_ALREADY_SELECTED("&cYou have already selected this kit as your default kit!"),
GUI_KIT_SHOP_ALREADY_SELECTED_KIT("&cYou have already selected this kit!"),
GUI_KIT_SHOP_YOU_PURCHASED_PERMANENT_KIT("&aYou purchased kit %kit%", "kit"),
GUI_KIT_SHOP_PURCHASED_KIT_USES("&aYou purchased %uses% use(s) for kit %kit%", "uses", "kit"),
GUI_KIT_SHOP_YOU_CHOSE_KIT_DEFAULT("&aYou selected kit %kit% as your default kit", "kit"),
GUI_KIT_SHOP_YOU_CHOSE_KIT("&aYou selected kit %kit%", "kit"),
GUI_KIT_SHOP_ECONOMY_PLUGIN_ERROR("&cThe kit is not free but there is nothing you can use to pay for it. Please contact the server administrator."),
GUI_KIT_SHOP_NOT_ENOUGH_MONEY("&cYou do not have enough money to buy this kit."),
GUI_KIT_SHOP_ERROR_OCCURRED("&cAn error has occurred while purchasing this kit."),
GUI_KIT_SHOP_LEFT_CLICK("&aLeft-click to select as your default kit"),
GUI_KIT_SHOP_LEFT_CLICK_SELECT("&aLeft-click to select"),
GUI_KIT_SHOP_RIGHT_CLICK_OPTIONS("&aRight-click to show more options"),
GUI_KIT_SHOP_CLICK_DEFAULT("&aClick to select as your default kit"),
GUI_KIT_SHOP_CLICK_SELECT("&aClick to select"),
GUI_KIT_SHOP_CLICK_BUY("&aClick to buy kit uses"),
GUI_KIT_SHOP_CLICK_BUY_PERMANENT("&aClick to buy"),
GUI_KIT_SHOP_KIT_USES("&7Kit uses: &a%uses%", "uses"),
GUI_KIT_SHOP_OPTIONS_TITLE("&aOptions for %kit%", "kit"),
GUI_KIT_OPTIONS_LAYOUT("&6Click to change the kit layout"),
GUI_KIT_OPTIONS_PREVIEW("&6Click to preview kit"),
// Shop commands
SHOP_COMMANDS(CommentType.SUBHEADER_SPACED, "Shop commands"),
SHOP_COMMANDS_DESC("Command for shop commands"),
SHOP_NOT_FOUND("Shop does not exist"),
SHOP_ITEM_NOT_FOUND("Shop item does not exist"),
SHOP_ITEM_IS_PERMANENT("&cShop item is permanent"),
SHOP_ITEMS_GIVE_COMMAND("Gives a specific shop item to player"),
SHOP_ITEMS_GIVE_ALL_COMMAND("Gives all shop items to player (can be uses, permanents or both)"),
SHOP_ITEMS_REMOVE_COMMAND("Removes a specific shop item to player"),
SHOP_ITEMS_REMOVE_ALL_COMMAND("Removes all shop items from player"),
SHOP_ITEMS_SET_COMMAND("Sets a specific shop item amount a player has"),
SHOP_ITEMS_GIVE_MUST_BE_POSITIVE("&cAmount must be a positive number! use &6/%base_command% shop take &cif you want to remove items."),
SHOP_ITEMS_TAKE_MUST_BE_POSITIVE("&cAmount must be a positive number!"),
SHOP_ITEMS_GIVEN("&7You gave %player% %amount% %item% %shop%", "player", "amount", "item", "shop"),
SHOP_ITEMS_GIVEN_PERMANENT("&7You gave %player% %item% %shop%", "player", "item", "shop"),
SHOP_ITEMS_REMOVED("&7You removed %player% %amount% %item% %shop%", "player", "amount", "item", "shop"),
SHOP_ITEMS_REMOVED_PERMANENT("&7You removed %player% %item% %shop%", "player", "item", "shop"),
// Other shop messages
OTHER_SHOP_MESSAGES(CommentType.SUBHEADER_SPACED, "Other shop messages"),
SHOP_CAGE_TITLE("Choose a cage"),
SHOP_CAGE_NAME("Cage"),
SHOP_CAGE_COMMAND("Command for cages"),
SHOP_PROJECTILE_TRAIL_TITLE("Choose a projectile trail"),
SHOP_PROJECTILE_TRAIL_NAME("Projectile Trail"),
SHOP_PROJECTILE_TRAIL_COMMAND("Command to choose projectile trails"),
SHOP_WALK_TRAILS_TITLE("Choose a walk trail"),
SHOP_WALK_TRAILS_NAME("Walk Trail"),
SHOP_WALK_TRAILS_COMMAND("Command to choose walk trails"),
SHOP_WIN_EFFECTS_TITLE("Choose a projectile trail"),
SHOP_WIN_EFFECTS_TRAIL_NAME("Projectile Trail"),
SHOP_WIN_EFFECTS_TRAIL_COMMAND("Command to choose projectile trails"),
MENU_COMMANDS(CommentType.SUBHEADER_SPACED, "Menu commands"),
MENU_COMMAND_DESC("Command for menus"),
MENU_COMMAND_OPEN("Open a menu"),
MENU_NOT_FOUND("That menu does not exist!"),
STATS_COMMAND("Shows the stats for the player"),
STATS_WEEK("&6Stats for this week:"),
STATS_WEEK_PLAYER("&e%player% &6stats for this week:", "player"),
STATS_WEEK_DISPLAY("&6%stat_name% &e%stat%", "stat_name", "stat"),
STATS_ALL("&6Stats for all time:"),
STATS_ALL_PLAYER("&e%player% &6stats for all time:", "player"),
STATS_ALL_DISPLAY("&6%stat_name% &e%stat%", "stat_name", "stat"),
// -----------------------------------
// Leaderboard Messages
// -----------------------------------
LEADERBOARD_COMMANDS(CommentType.SUBHEADER_SPACED, "Leaderboard commands"),
LEADERBOARD_COMMAND_DESC("Command for leaderboard related stuff"),
LEADERBOARD_LIST("List all tracked statistics"),
LEADERBOARD_MAX_PLACE("&cMax place is 10"),
LEADERBOARD_STATISTIC_NOT_FOUND("&cStatistic does not exist!"),
LEADERBOARD_PERIOD_NOT_FOUND("&cPeriod not found! &7Available periods: week, month, all"),
LEADERBOARD_HOLOGRAM_DESC("Command for hologram leaderboards"),
LEADERBOARD_HOLOGRAM_CREATE("Creates a new hologram"),
LEADERBOARD_HOLOGRAM_NOT_FOUND("&cThe hologram &4%hologram% &cdoes not exist.", "hologram"),
LEADERBOARD_HOLOGRAM_ALREADY_EXISTS("&cThe hologram already exists!"),
LEADERBOARD_HOLOGRAM_CREATED("&aHologram Created!"),
LEADERBOARD_HOLOGRAM_MOVE("Moves the hologram to your location"),
LEADERBOARD_HOLOGRAM_MOVED("The hologram has been moved to your location"),
LEADERBOARD_HOLOGRAM_LIST("List all the holograms"),
LEADERBOARD_HOLOGRAM_LIST_TITLE("Holograms"),
LEADERBOARD_HOLOGRAM_SETSIZE("Sets the amount of entries to display (max 10)"),
LEADERBOARD_HOLOGRAM_SETSIZE_SUCCESS("Hologram will not display %size% entries", "size"),
LEADERBOARD_HOLOGRAM_ADD("Add a stat to the hologram"),
LEADERBOARD_HOLOGRAM_ADDED("&7Stat &6%stat_name% &7has been added to &7%hologram%", "stat_name", "hologram"),
LEADERBOARD_HOLOGRAM_REMOVE("Removes a stat from the hologram"),
LEADERBOARD_HOLOGRAM_REMOVE_INDEX("&cIndex out of bounds! &7Use &6%base_command% holo list <hologram> &7to display the indices."),
LEADERBOARD_HOLOGRAM_REMOVED("&7Stat &6%stat_name% %period% &7has been removed from &7%hologram%", "stat_name", "hologram", "period"),
LEADERBOARD_HOLOGRAM_DELETE("Deletes a hologram"),
LEADERBOARD_HOLOGRAM_DELETE_CONFIRM("&7Type &6/%base_command% holo delete %hologram% -c &7to confirm the permanent deletion.", "hologram"),
LEADERBOARD_HOLOGRAM_DELETED("&7The hologram has been deleted"),
LEADERBOARD_SIGNS_DESC("Command for leaderboard signs"),
LEADERBOARD_SIGNS_ADD("Adds a sign with the stat (need to right click sign)"),
LEADERBOARD_SIGNS_CLICK_TO_ADD("&aRight-click a sign to add."),
LEADERBOARD_SIGNS_ADDED("&aLeader sign has been created!"),
LEADERBOARD_SIGNS_LIST("List all the signs"),
LEADERBOARD_ATTACHMENTS_DESC("Command for sign attachments"),
LEADERBOARD_ATTACHMENTS_ADD("Creates a new attachment (need to right click sign)"),
LEADERBOARD_ATTACHMENTS_NOT_FOUND("&cAttachment not found!"),
LEADERBOARD_ATTACHMENTS_NOT_USABLE("&cThis attachment is missing the following dependency: %dependency%", "dependency"),
LEADERBOARD_ATTACHMENTS_RIGHT_CLICK("&aRight-click a leaderboard sign"),
LEADERBOARD_ATTACHMENTS_ALREADY_ATTACHED("&cThe sign already had this attachment!"),
LEADERBOARD_ATTACHMENTS_ADDED("&aAttachment added!"),
LEADERBOARD_ATTACHMENTS_COULD_NOT_ADD("&cCould not find a suitable place for this attachment."),
// -------------------------------------------- //
// EXPERIENCE AND LEVELS
// -------------------------------------------- //
EXPERIENCE_SYSTEM(CommentType.SUBHEADER_SPACED, "Experience/Levels"),
EXPERIENCE_COMMAND_DESC("Command for experience"),
EXPERIENCE_POPULATE_DESC("Create and populate experience table from stats."),
EXPERIENCE_POPULATE_TABLE_EXISTS("Table already exists! Please drop the table before continuing"),
EXPERIENCE_POPULATE_DONE("&aDone populating!"),
EXPERIENCE_POPULATE_CONFIRM("&cYou are about to populate the database with experience. Please confirm the following settings from the config are correct then run &6/%base_command% experience populate -c"),
EXPERIENCE_POPULATE_CONFIG("&e&l%element%: &b%value%", "element", "value"),
EXPERIENCE_EARNED("&b+%amount% experience", "amount"),
EXPERIENCE_LEVEL_UP("&b&lLEVEL UP!"),
EXPERIENCE_LEVEL_UP_INFO("&eYou have leveled up from &b%oldlevel% &eto &b%newlevel%", "oldlevel", "newlevel"),
EXPERIENCE_ADD_DESC("Adds experience to a player"),
EXPERIENCE_SET("&6%player%'s &7experience has been set to &6%amount% &7(&6level %level%&7)", "player", "amount", "level"),
EXPERIENCE_SET_DESC("Sets experience to a player"),
EXPERIENCE_ADD("&6%amount% &7experience has been added to &6%player%. &7They now have &6%total% &7experience (&6level %level%&7)", "player", "amount", "total", "level"),
EXPERIENCE_REMOVED_DESC("Removes experience to a player"),
EXPERIENCE_REMOVE("&6%amount% &7experience has been removed from &6%player%. &7They now have &6%total% &7experience (&6level %level%&7)", "player", "amount", "total", "level"),
// -----------------------------------
// Quests Messages
// -----------------------------------
QUESTS_HEADER(CommentType.SUBHEADER_SPACED, "Quests"),
QUEST_COMPLETED("&aQuest %quest% completed!", "quest"),
QUESTS_COMMAND("Opens the quest menu"),
GUI_QUEST_TITLE("&7Choose a quest"),
GUI_QUEST_ITEM_NAME("&aQuest %quest%", "quest"),
GUI_QUEST_STARTED("&aStarted Quest: &6%quest%", "quest"),
GUI_QUEST_STATUS_START("&aClick to start quest!"),
GUI_QUEST_STATUS_STARTED("&aStarted"),
GUI_QUEST_STATUS_PROGRESS("&bProgress &7(&6%amount%&7/&6%goal%&7)", "amount", "goal"),
GUI_QUEST_STATUS_DEADLINE("&7Deadline: &6%time%", "time"),
GUI_QUEST_STATUS_COMPLETED("&aYou have completed this quest!"),
GUI_QUEST_STATUS_COOLDOWN("&cThis quest is on cooldown!"),
GUI_QUEST_STATUS_COOLDOWN_2("&cYou can start it again in %time%", "time"),
GUI_QUEST_STATUS_EXP("&b+%amount% experience", "amount"),
GUI_QUEST_STATUS_COINS("&6+%amount% coins", "amount"),
// -----------------------------------
// GUI messages
// -----------------------------------
// General Messages
GUI_HEADER(CoreComments.GUI_MESSAGES),
GENERAL_GUI(CoreComments.GUI_GENERAL_MESSAGES),
GUI_ERROR_INIT("&cError initializing page"),
GUI_NEXT_PAGE("&eClick to go to the next page (page %pagenumber%)", "pagenumber"),
GUI_PREVIOUS_PAGE("&eClick to go to the previous page (page %pagenumber%)", "pagenumber"),
GUI_YOU_ARE_ON("&eYou are on page %pagenumber%", "pagenumber"),
GUI_ENABLED("&aenabled"),
GUI_DISABLED("&cdisabled"),
GUI_BACK("&cBack"),
// Choose kit menu
GUI_USER_CHOOSE_KIT(CoreComments.GUI_CHOOSE_KIT),
GUI_USER_CHOOSE_TITLE("Choose kit"),
GUI_USER_CHOOSE_ALREADY_BOUGHT("&cYou have already selected this kit!"),
GUI_USER_CHOOSE_YOU_PURCHASED_PERMANENT_KIT("&aYou purchased kit %kit%", "kit"),
GUI_USER_CHOOSE_YOU_PURCHASED_KIT_USES("&aYou purchased %uses% use(s) for kit %kit%", "uses", "kit"),
GUI_USER_CHOOSE_YOU_CHOSE_KIT("&aYou chose kit %kit%", "kit"),
GUI_USER_CHOOSE_ECONOMY_PLUGIN_ERROR("&cThe kit is not free but there is nothing you can use to pay for it. Please contact the server administrator."),
GUI_USER_CHOOSE_NOT_ENOUGH_MONEY("&cYou do not have enough money to buy this kit."),
GUI_USER_CHOOSE_ERROR_OCCURRED("&cAn error has occurred while purchasing this kit."),
// Edit Layout menu
GUI_USER_EDIT_KIT_LAYOUT(CoreComments.GUI_EDIT_KIT_LAYOUT),
GUI_USER_EDIT_KIT_LAYOUT_TITLE("Edit layout for kit %kit%", "kit"),
GUI_USER_EDIT_KIT_LAYOUT_SAVED("&aLayout saved for kit %kit%", "kit"),
GUI_USER_EDIT_KIT_LAYOUT_SAVE("&aSave Kit"),
// Choose arena menu
GUI_CHOOSE_LOCALE(CoreComments.GUI_CHOOSE_LOCALE),
GUI_CHOOSE_LOCALE_TITLE("Choose a language"),
GUI_CHOOSE_LOCALE_SELECTED("&aSelected"),
GUI_CHOOSE_LOCALE_CHANGED(true, "&aLanguage changed!"),
GUI_CHOOSE_LOCALE_NOT_CHANGED(true, "&cYou already selected this language!"),
GUI_USER_JOIN_ARENA(CoreComments.GUI_USER_CHOOSE_TEAM),
GUI_USER_JOIN_ARENA_TITLE("Arenas"),
GUI_USER_JOIN_ARENA_CLICK_TO_SPECTATE("&aClick to spectate!"),
GUI_USER_JOIN_ARENA_CLICK_TO_JOIN("&aClick to join!"),
GUI_USER_JOIN_ARENA_ARENA_FULL("&cThe arena is full!"),
// Choose team menu
GUI_USER_CHOOSE_TEAM(CoreComments.GUI_USER_CHOOSE_TEAM),
GUI_USER_CHOOSE_TEAM_TITLE("Choose Team"),
GUI_USER_CHOOSE_TEAM_YOU_ARE_ALREADY_IN("&cYou are already in %teamcolor%%teamname%", "teamcolor", "teamname"),
GUI_USER_CHOOSE_TEAM_YOU_JOINED("&aYou joined %teamcolor%%teamname%", "teamcolor", "teamname"),
GUI_USER_CHOOSE_TEAM_FULL("%teamcolor%%teamname% &cis full!", "teamcolor", "teamname"),
GUI_USER_CHOOSE_TEAM_NO_PERMISSION("You must purchase a rank to open the team selector"),
// Item main page
GUI_EDIT_ITEM(CoreComments.GUI_EDIT_ITEM),
GUI_EDIT_ITEM_TITLE("Edit item"),
GUI_EDIT_ITEM_CHANGE_ITEM("&aChange item"),
GUI_EDIT_ITEM_CHANGE_DATA("&aChange data"),
GUI_EDIT_ITEM_CHANGE_AMOUNT("&aChange amount"),
GUI_EDIT_ITEM_FILTER("&6Filter"),
// Change amount
GUI_CHANGE_AMOUNT(CoreComments.GUI_CHANGE_AMOUNT),
GUI_CHANGE_AMOUNT_TITLE("Change item amount"),
GUI_CHANGE_AMOUNT_RESET("&cReset data"),
// Choose kit to edit
GUI_CHOOSE_KIT(CoreComments.GUI_CHOOSE_KIT_TO_EDIT),
GUI_CHOOSE_KIT_TITLE("Choose kit to edit"),
GUI_CHOOSE_KIT_EDIT_ITEM("&aEdit kit %kit%", "kit"),
GUI_CHOOSE_KIT_CREATE_ITEM("&aCreate kit"),
// Choose Potion Effect
GUI_CHOOSE_POTION_EFFECT(CoreComments.GUI_CHOOSE_POTION_EFFECT),
GUI_CHOOSE_POTION_EFFECT_TITLE("Choose a potion effect"),
GUI_CHOOSE_POTION_EFFECT_ADD("&aClick to add"),
GUI_CHOOSE_POTION_EFFECT_LORE("&7Duration: &f%duration%%newline%&7Amplifier: &f%amplifier%", "duration", "amplifier"),
// Edit Kit UI
GUI_EDIT_KIT(CoreComments.GUI_EDIT_KIT),
GUI_EDIT_KIT_TITLE("Edit kit %kit%", "kit"),
GUI_EDIT_KIT_RENAME("&6Rename"),
GUI_EDIT_KIT_PRICE("&aPrice"),
GUI_EDIT_KIT_PREVIEW("&6Preview"),
GUI_EDIT_KIT_CHANGE_ITEMS("&bChange items"),
GUI_EDIT_KIT_POTION_EFFECTS("&dPotion effects"),
GUI_EDIT_KIT_DESCRIPTION("&7Description"),
GUI_EDIT_KIT_DISPLAY_ITEM("&6Change display item"),
GUI_EDIT_KIT_DELETE("&cDelete kit"),
GUI_EDIT_KIT_SET_PERMISSION("&eSet Permission"),
GUI_EDIT_KIT_ONE_TIME("&fOne-time kit"),
GUI_EDIT_KIT_ITEMS_UPDATED("&aKit items updated!"),
GUI_EDIT_KIT_KIT_DELETED("&cKit deleted!"),
GUI_EDIT_KIT_KIT_RENAMED("&aKit renamed!"),
// Edit Price UI
GUI_EDIT_PRICE(CoreComments.GUI_EDIT_PRICE),
GUI_EDIT_PRICE_TITLE("Edit kit price"),
GUI_EDIT_PRICE_KIT_ITEM("Kit %kit%", "kit"),
GUI_EDIT_PRICE_LORE("&7Price: &f%price%", "price"),
GUI_EDIT_PRICE_RESET("&cReset price to 0 (free)"),
// Kit Preview
GUI_PREVIEW_KIT(CoreComments.GUI_PREVIEW_KIT),
GUI_PREVIEW_KIT_TITLE("%kit% preview", "kit"),
GUI_PREVIEW_KIT_COPY("&aReceive kit"),
// Potion Effect UI
GUI_EDIT_POTION_EFFECT(CoreComments.GUI_KIT_EDIT_POTION_EFFECT),
GUI_EDIT_POTION_EFFECT_TITLE("Edit potion effect"),
GUI_EDIT_POTION_EFFECT_AMPLIFIER_ITEM("&aChange amplifier"),
GUI_EDIT_POTION_EFFECT_AMPLIFIER_LORE("&7Amplifier: &f%amplifier%", "amplifier"),
GUI_EDIT_POTION_EFFECT_DURATION_ITEM("&aChange duration"),
GUI_EDIT_POTION_EFFECT_DURATION_LORE("&7Duration: &f%duration%", "duration"),
// Description editor line
GUI_DESCRIPTION_EDITOR(CoreComments.GUI_DESCRIPTION_EDITOR),
GUI_DESCRIPTION_EDITOR_TITLE("Edit line"),
GUI_DESCRIPTION_EDITOR_RENAME("&aRename"),
GUI_DESCRIPTION_EDITOR_DELETE("&cDelete line"),
// Description editor main page
GUI_DESCRIPTION_EDITOR_MAIN(CoreComments.GUI_DESCRIPTION_EDITOR_MAIN),
GUI_DESCRIPTION_EDITOR_MAIN_TITLE("Edit description"),
GUI_DESCRIPTION_EDITOR_MAIN_NEW("&aAdd new line"),
// Treasure Chest UI
GUI_TREASURE_CHEST(CommentType.SUBHEADER_SPACED, "Treasure chests"),
GUI_TREASURE_CHEST_TITLE("Open a chest"),
GUI_TREASURE_CHEST_ITEM_NAME("&a%currency%", "currency"),
GUI_TREASURE_CHEST_ITEM_LORE("&aYou have %amount% %currency%%newline%Purchase", "amount", "currency"),
// Buy Treasure Chest UI
GUI_BUY_TREASURE_CHEST(CommentType.SUBHEADER_SPACED, "Treasure chests"),
GUI_BUY_TREASURE_CHEST_TITLE("Buy Treasure Chests"),
GUI_BUY_TREASURE_CHEST_YOU_PURCHASED("&aYou purchased %amount% chest(s) for chest %chest%", "amount", "chest"),
GUI_BUY_TREASURE_CHEST_ECONOMY_PLUGIN_ERROR("&cThe item is not free but there is nothing you can use to pay for it. Please contact the server administrator."),
GUI_BUY_TREASURE_CHEST_NOT_ENOUGH_MONEY("&cYou do not have enough money to buy this treasure chest."),
GUI_BUY_TREASURE_CHEST_ERROR_OCCURRED("&cAn error has occurred while purchasing this treasure chest."),
// Weather Vote UI
GUI_WEATHER_VOTE(CommentType.SUBHEADER_SPACED, "Weather Vote UI"),
GUI_WEATHER_VOTE_TITLE("Vote for the weather"),
GUI_WEATHER_VOTE_SUN("&eSun"),
GUI_WEATHER_VOTE_RAIN("&bRain"),
GUI_WEATHER_VOTE_VOTED("You voted for &6%weather%", "weather"),
GUI_WEATHER_ITEM("&6Weather"),
GUI_WEATHER_NO_PERMISSION("&cYou do not have permission to open the weather menu"),
// Time Vote UI
GUI_TIME_VOTE(CommentType.SUBHEADER_SPACED, "Time Vote UI"),
GUI_TIME_VOTE_TITLE("Vote for the time"),
GUI_TIME_VOTE_MORNING("&eMorning"),
GUI_TIME_VOTE_NOON("&6Noon"),
GUI_TIME_VOTE_SUNSET("&7Sunset"),
GUI_TIME_VOTE_MIDNIGHT("&8Midnight"),
GUI_TIME_VOTE_VOTED("You voted for &6%time%", "time"),
GUI_TIME_ITEM("&6Time"),
GUI_TIME_NO_PERMISSION("&cYou do not have permission to open the time menu"),
// Weather Vote UI
GUI_GAME_OPTIONS(CommentType.SUBHEADER_SPACED, "Game Options UI"),
GUI_GAME_OPTIONS_TITLE("Game Options"),
// Random arena Mode
CHOOSE_MAP_UI(CommentType.SUBHEADER_SPACED, "Choose Map UI"),
CHOOSE_MAP_UI_TITLE("Choose a map"),
CHOOSE_GROUP("Choose a group"),
CHOOSE_MAP_BUTTON_NAME("&6%map%", "map"),
CHOOSE_GROUP_BUTTON_NAME("&6%group%", "group"),
CHOOSE_MAP_BUTTON_JOIN_DESC("&aClick to join"),
CHOOSE_MAP_BUTTON_SELECT_DESC("&aClick to create an arena for this map"),
CHOOSE_MAP_ARENA_CREATED("&aAn arena has been created for you with your map!"),
CHOOSE_MAP_ARENA_QUEUED("&aPlease be patient while we create an arena for you.%newline% This may take a few minutes while we wait for a game to end."),
PLAYER_QUEUED("&cYou cannot join an arena while you're in queue. To leave the queue, try to join again."),
PLAYER_QUEUE_LEAVE("&cYou have left the queue for the map %map%", "map"),
RANDOM_ARENA_MODE_COMMAND("Command for random arena mode"),
RANDOM_ARENA_MODE_CHOOSE_GROUP_COMMAND("Open the menu to choose an arena"),
RANDOM_ARENA_MODE_NOT_FOUND("&cGroup not found"),
// Private arenas
GUI_PRIVATE_ARENA(CommentType.SUBHEADER_SPACED, "Private arena"),
GUI_PRIVATE_ARENA_TITLE("Private arena options"),
GUI_PRIVATE_ARENA_HEAD("&a%player%'s private arena", "player"),
GUI_PRIVATE_ARENA_RENAME("&6Rename arena"),
GUI_PRIVATE_ARENA_MANAGE_TEAMS("&bManage Teams"),
GUI_PRIVATE_ARENA_START_COUNTDOWN("&aStart countdown"),
GUI_PRIVATE_ARENA_STOP_COUNTDOWN("&cStop countdown"),
GUI_PRIVATE_ARENA_ADD_CO_HOST("&aAdd a co-host"),
GUI_PRIVATE_ARENA_REMOVE_CO_HOST("&cRemove a Co-Host"),
GUI_PRIVATE_ARENA_KICK_PLAYERS("&cKick players"),
GUI_PRIVATE_ARENA_ADD_PLAYERS_TO_WHITELIST("&aAdds players to whitelist"),
GUI_PRIVATE_ARENA_REMOVE_PLAYERS_FROM_WHITELIST("&cRemove players from whitelist"),
GUI_PRIVATE_ARENA_PLAYERS("&cRemove a co-host from the private arena"),
GUI_PRIVATE_ARENA_CHANGE_MAP("&6Change map"),
GUI_PRIVATE_ARENA_OPTIONS("&eArena Options"),
GUI_PRIVATE_ARENA_CLOSE("&6Close the private arena"),
GUI_PRIVATE_ARENA_KICK("&cKick %player%", "player"),
GUI_PRIVATE_ARENA_KICKED("&c%player% has been kicked", "player"),
GUI_PRIVATE_ARENA_CANT_KICK("&cYou cannot kick this player because they're co-host or host."),
GUI_PRIVATE_ARENA_GIVE_CO_HOST("&aMake %player% Co-Host", "player"),
GUI_PRIVATE_ARENA_CO_HOST_MADE("&c%player% has been made Co-Host", "player"),
GUI_PRIVATE_ARENA_DEMOTE_CO_HOST("&cDemote %player% from Co-Host", "player"),
GUI_PRIVATE_ARENA_CO_HOST_REMOVED("&c%player% has been removed from Co-Host", "player"),
GUI_PRIVATE_ARENA_ADD_PLAYER_TO_WHITELIST("&aAdd %player% to whitelist", "player"),
GUI_PRIVATE_ARENA_PLAYER_ADDED_TO_WHITELIST("&a%player% has been added to the whitelist", "player"),
GUI_PRIVATE_ARENA_REMOVE_PLAYER_FROM_WHITELIST("&cRemove %player% from whitelist", "player"),
GUI_PRIVATE_ARENA_PLAYER_REMOVED_ROM_WHITELIST("&c%player% has been removed from the whitelist", "player"),
GUI_PRIVATE_ARENA_ADD_PLAYER_TO_WHITELIST_BY_NAME("&aAdd a player to the whitelist by name"),
GUI_PRIVATE_ARENA_COMMAND("Creates a private arena"),
GUI_PRIVATE_ARENA_LOBBY_MENU("&cHost menu"),
GUI_PRIVATE_ARENA_WHITELIST("&fWhitelist"),
GUI_PRIVATE_ARENA_PUBLIC_JOIN("&6Public Game"),
GUI_PRIVATE_ARENA_PUBLIC_SPECTATE("&6Anyone Can Spectate"),
GUI_PRIVATE_ARENA_TEAM_SELECTOR("&6Players can use team select"),
GUI_PRIVATE_ARENA_STATS("&aGame stats"),
GUI_PRIVATE_ARENA_NO_PERMISSION("&cYou do not have permission to change this option"),
GUI_PRIVATE_ARENA_TEAM_SELECTION_DISABLED("&cThe host has disabled team selection for this arena."),
GUI_PRIVATE_ARENA_SELECT_TEAM("Select a team to move players"),
GUI_PRIVATE_ARENA_CURRENT_TEAM("&7Currently in: %team%", "team"),
GUI_PRIVATE_ARENA_CURRENT_SPEC("&7Currently in: &7Spectators"),
GUI_PRIVATE_ARENA_NO_CURRENT_TEAM("&7Currently in: &fnone"),
GUI_PRIVATE_ARENA_CLICK_TO_REMOVE_TEAM("&eClick to remove from %team%", "team"),
GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_TEAM("&eClick to change to %team%", "team"),
GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_SPEC("&eClick to change to spectators"),
GUI_PRIVATE_ARENA_CLICK_TO_CHANGE_PLAYER("&eClick to change to player")
;
private String defaultMessage;
private Map<Locale, String> message;
private Map<Locale, String> rawMessage;
private boolean prefix;
private IComment comment;
private String[] arguments;
CoreLang(CoreComments CoreComments) {
this.comment = CoreComments;
}
CoreLang(CommentType commentType, String title) {
this.comment = new LangComment(commentType, title);
}
CoreLang(String defaultMessage, String... arguments) {
this(false, defaultMessage, arguments);
}
CoreLang(boolean prefix, String defaultMessage, String... arguments) {
this.defaultMessage = defaultMessage;
this.prefix = prefix;
this.message = new HashMap<>();
this.rawMessage = new HashMap<>();
this.arguments = arguments;
setMessage(CoreLocaleManager.getLocale("en"), defaultMessage);
}
public String getMessage(Locale locale) {
return (prefix ? CoreLang.PREFIX.getMessage(locale) : "") + message.get(locale);
}
@Override
public String getRawMessage(Locale locale) {
return rawMessage.get(locale);
}
@Override
public void setMessage(Locale locale, String message) {
this.message.put(locale, ChatColorEscaper.toColor(message)
.replace("%newline%", "\n")
.replace("%plugin_prefix%", PluginConfig.LANG_PREFIX)
.replace("%game_title%", PluginConfig.GAME_TITLE)
.replace("%base_command%", PluginConfig.BASE_COMMAND));
this.rawMessage.put(locale, message);
}
public void transferMessage(CoreLang lang) {
message = lang.message;
rawMessage = lang.rawMessage;
}
@Override
public String getDefaultMessage() {
return defaultMessage;
}
@Override
public boolean isComment() {
return comment != null;
}
@Override
public IComment getComment() {
return comment;
}
@Override
public String[] getArguments() {
return arguments;
}
}
| 46,780 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
LangComment.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/LangComment.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.lang.interfaces.IComment;
public class LangComment implements IComment {
private final String[] lines;
private final boolean isHeader;
public LangComment(CommentType commentType, String line) {
this.isHeader = commentType == CommentType.HEADER;
this.lines = commentType != CommentType.SUBHEADER_SPACED ? new String[]{line} : new String[]{"", line};
}
@Override
public String[] getLines() {
return lines;
}
@Override
public boolean isHeader() {
return isHeader;
}
}
| 612 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CommentType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/CommentType.java | package me.patothebest.gamecore.lang;
public enum CommentType {
HEADER,
SUBHEADER_SPACED,
SUBHEADER_NOT_SPACED
}
| 128 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
LocaleGenerator.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/LocaleGenerator.java | package me.patothebest.gamecore.lang;
import me.patothebest.gamecore.chat.ChatColorEscaper;
import me.patothebest.gamecore.lang.interfaces.ILang;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class LocaleGenerator {
public static void main(String[] args) {
if(args[1].contains("/Games.yml")) {
return;
}
try {
Class<? extends ILang> aClass = (Class<? extends ILang>) Class.forName(args[0]);
ILang[] enumConstants = aClass.getEnumConstants();
String filePath = args[1];
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
try (FileWriter writer = new FileWriter(file, false)){
for (ILang enumConstant : enumConstants) {
if (enumConstant.isComment()) {
continue;
}
writer.append(enumConstant.name().toLowerCase().replace("_", "-"))
.append(": \"")
.append(ChatColorEscaper.escapeColors(enumConstant.getDefaultMessage()))
.append("\"\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException(e);
}
}
} | 1,467 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Locale.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/Locale.java | package me.patothebest.gamecore.lang;
public class Locale {
private final String name;
public Locale(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| 219 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ILang.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/interfaces/ILang.java | package me.patothebest.gamecore.lang.interfaces;
import me.patothebest.gamecore.lang.CoreLocaleManager;
import me.patothebest.gamecore.lang.Locale;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.util.NameableObject;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
public interface ILang {
default String getMessage(@Nullable CommandSender commandSender) {
if (commandSender instanceof Player) {
return getMessage(PlayerManager.get().getPlayer((Player) commandSender));
}
return getMessage(CoreLocaleManager.DEFAULT_LOCALE);
}
default String getMessage(Player player) {
IPlayer player1 = PlayerManager.get().getPlayer(player);
if (player == null || player1 == null) {
System.err.println(name() + " - Error while getting messages, player is null!");
return getMessage(CoreLocaleManager.DEFAULT_LOCALE);
}
return getMessage(player1);
}
default String getPath() {
return name().toLowerCase().replace("_", "-");
}
default String getMessage(IPlayer player) {
return getMessage(player.getLocale());
}
default void sendMessage(CommandSender commandSender) {
commandSender.sendMessage(getMessage(commandSender));
}
default void sendMessage(IPlayer corePlayer) {
corePlayer.sendMessage(getMessage(corePlayer));
}
default void replaceAndSend(CommandSender commandSender, Object... args) {
if (commandSender instanceof Player) {
replaceAndSend(PlayerManager.get().getPlayer((Player) commandSender), args);
return;
}
commandSender.sendMessage(replace(CoreLocaleManager.DEFAULT_LOCALE, args));
}
default void replaceAndSend(Player player, Object... args) {
replaceAndSend(PlayerManager.get().getPlayer(player), args);
}
default void replaceAndSend(IPlayer player, Object... args) {
player.sendMessage(replace(player.getLocale(), args));
}
default String replace(@Nullable CommandSender commandSender, Object... args) {
if (commandSender instanceof Player) {
return replace(PlayerManager.get().getPlayer((Player) commandSender), args);
}
return replace(CoreLocaleManager.DEFAULT_LOCALE, args);
}
default String replace(Player player, Object... args) {
return replace(PlayerManager.get().getPlayer(player), args);
}
default String replace(IPlayer player, Object... args) {
return replace(player.getLocale(), args);
}
default String replace(Locale locale, Object... args) {
if (args.length != getArguments().length) {
throw new IllegalArgumentException("Wrong arguments for Lang " + name() + ": entered " + args.length + ", expected " + getArguments().length);
}
String message = getMessage(locale);
for (int i = 0; i < args.length; i++) {
String replacement;
if (args[i] instanceof String) {
replacement = (String) args[i];
} else if(args[i] instanceof ILang) {
replacement = ((ILang)args[i]).getMessage(locale);
} else if(args[i] instanceof NameableObject) {
replacement = ((NameableObject)args[i]).getName();
} else {
replacement = String.valueOf(args[i]);
}
message = message.replace("%" + getArguments()[i] + "%", replacement);
}
return ChatColor.translateAlternateColorCodes('&', message);
}
String getMessage(Locale locale);
String name();
boolean isComment();
IComment getComment();
String getRawMessage(Locale locale);
String getDefaultMessage();
void setMessage(Locale locale, String defaultMessage);
String[] getArguments();
}
| 4,015 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
IComment.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/lang/interfaces/IComment.java | package me.patothebest.gamecore.lang.interfaces;
public interface IComment {
String[] getLines();
boolean isHeader();
}
| 132 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaState.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/ArenaState.java | package me.patothebest.gamecore.arena;
import me.patothebest.gamecore.command.ChatColor;
import org.bukkit.DyeColor;
public enum ArenaState {
WAITING("Waiting", ChatColor.GREEN, DyeColor.LIME),
STARTING("Starting", ChatColor.GREEN, DyeColor.LIME),
IN_GAME("In-Game", ChatColor.GOLD, DyeColor.ORANGE),
ENDING("Ending", ChatColor.RED, DyeColor.RED),
RESTARTING("Restarting", ChatColor.RED, DyeColor.RED),
OTHER("Other", ChatColor.RED, DyeColor.RED),
ERROR("Error", ChatColor.RED, DyeColor.RED)
;
private final String name;
private ChatColor color;
private DyeColor data;
ArenaState(String name, ChatColor color, DyeColor data) {
this.name = name;
this.color = color;
this.data = data;
}
public String getName() {
return name;
}
public ChatColor getColor() {
return color;
}
public DyeColor getData() {
return data;
}
public static void configureInGameJoinable() {
ArenaState.IN_GAME.color = ChatColor.GREEN;
ArenaState.IN_GAME.data = DyeColor.LIME;
}
}
| 1,109 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaFile.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/ArenaFile.java | package me.patothebest.gamecore.arena;
import me.patothebest.gamecore.file.FlatFile;
import java.io.File;
public class ArenaFile extends FlatFile {
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final AbstractArena arena;
// -------------------------------------------- //
// CONSTRUCTOR
// -------------------------------------------- //
public ArenaFile(AbstractArena arena) {
super("arenas" + File.separatorChar + arena.getName());
this.header = "Arena " + arena.getName() + " data";
this.arena = arena;
// load the file to memory
load();
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public void save() {
// save the arena
set("data", arena.serialize());
// actually save the file
super.save();
}
@Override
public String toString() {
return "ArenaFile{" +
"arena=" + arena.getName() +
'}';
}
}
| 1,147 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaFactory.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/ArenaFactory.java | package me.patothebest.gamecore.arena;
import com.google.inject.assistedinject.Assisted;
public interface ArenaFactory {
AbstractArena create(@Assisted("name") String name, @Assisted("worldName") String worldName);
}
| 225 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AbstractGameTeam.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/AbstractGameTeam.java | package me.patothebest.gamecore.arena;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.modifiers.KitModifier;
import me.patothebest.gamecore.util.Utils;
import me.patothebest.gamecore.vector.ArenaLocation;
import me.patothebest.gamecore.util.NameableObject;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractGameTeam implements NameableObject, ConfigurationSerializable {
// temporary objects only for the game
protected final AbstractArena arena;
protected final List<Player> players = new ArrayList<>();
protected final String name;
protected final DyeColor color;
protected boolean teamChatPrefix = true;
// things that are going to be saved
protected ArenaLocation spawn;
public AbstractGameTeam(AbstractArena arena, String name, DyeColor color) {
this.arena = arena;
this.name = name;
this.color = color;
}
@SuppressWarnings("unchecked")
public AbstractGameTeam(AbstractArena arena, Map<String, Object> data) {
this.arena = arena;
name = (String) data.get("name");
color = Utils.getEnumValueFromString(DyeColor.class, (String) data.get("color"));
// get the spawn location if present
if(data.get("spawn") != null) {
spawn = ArenaLocation.deserialize((Map<String, Object>) data.get("spawn"), arena);
}
}
public void addPlayer(Player player) {
// add the player to the team
players.add(player);
IPlayer corePlayer = arena.getPlayerManager().getPlayer(player);
corePlayer.setGameTeam(this);
arena.addPlayerToLastTeam(this, player);
}
public void giveStuff(Player player) {
IPlayer corePlayer = arena.getPlayerManager().getPlayer(player);
if(corePlayer.getKit() != null && !corePlayer.isPermanentKit(corePlayer.getKit())) {
if(corePlayer.canUseKit(corePlayer.getKit())) {
corePlayer.addKitUses(corePlayer.getKit(), -1);
} else {
corePlayer.setKit(arena.getKitManager().getDefaultKit());
corePlayer.notifyObservers(KitModifier.SET_DEFAULT, corePlayer.getKit());
}
}
// give kit and kit potion effects
arena.getKitManager().applyKit(player, this);
arena.getKitManager().applyPotionEffects(player);
}
public void removePlayer(Player player) {
// remove the player
arena.getPlayerManager().getPlayer(player).setGameTeam(null);
players.remove(player);
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> objectMap = new HashMap<>();
objectMap.put("name", name);
objectMap.put("color", color.name());
if(spawn != null) {
objectMap.put("spawn", spawn.serialize());
}
return objectMap;
}
public DyeColor getColor() {
return color;
}
@Override
public String getName() {
return name;
}
public ArenaLocation getSpawn() {
return spawn;
}
public void setSpawn(Location spawn) {
this.spawn = new ArenaLocation(arena, spawn);
}
public List<Player> getPlayers() {
return players;
}
boolean hasPlayer(Player player) {
return players.contains(player);
}
public void setTeamChatPrefix(boolean teamChatPrefix) {
this.teamChatPrefix = teamChatPrefix;
}
public boolean hasTeamChatPrefix() {
return teamChatPrefix;
}
}
| 3,781 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaGroup.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/ArenaGroup.java | package me.patothebest.gamecore.arena;
public class ArenaGroup {
public final static ArenaGroup DEFAULT_GROUP = new ArenaGroup("none");
private final String name;
public ArenaGroup(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| 304 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AbstractArena.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/AbstractArena.java | package me.patothebest.gamecore.arena;
import com.google.inject.Injector;
import com.google.inject.Provider;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.actionbar.ActionBar;
import me.patothebest.gamecore.arena.modes.bungee.AdvancedBungeeMode;
import me.patothebest.gamecore.arena.option.ArenaOption;
import me.patothebest.gamecore.arena.option.options.EnvironmentOption;
import me.patothebest.gamecore.arena.option.options.TNTExplosionOption;
import me.patothebest.gamecore.arena.option.options.TimeOfDayOption;
import me.patothebest.gamecore.combat.CombatManager;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.event.arena.ArenaDisableEvent;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.arena.ArenaPrePhaseChangeEvent;
import me.patothebest.gamecore.event.arena.ArenaPreRegenEvent;
import me.patothebest.gamecore.event.arena.ArenaUnLoadEvent;
import me.patothebest.gamecore.event.player.ArenaLeaveEvent;
import me.patothebest.gamecore.event.player.ArenaLeaveMidGameEvent;
import me.patothebest.gamecore.event.player.ArenaPreJoinEvent;
import me.patothebest.gamecore.event.player.ArenaPreLeaveEvent;
import me.patothebest.gamecore.event.player.GameJoinEvent;
import me.patothebest.gamecore.event.player.PlayerLooseEvent;
import me.patothebest.gamecore.event.player.PlayerStateChangeEvent;
import me.patothebest.gamecore.event.player.SpectateEvent;
import me.patothebest.gamecore.feature.Feature;
import me.patothebest.gamecore.file.CoreConfig;
import me.patothebest.gamecore.ghost.GhostFactory;
import me.patothebest.gamecore.kit.KitManager;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.permission.GroupPermissible;
import me.patothebest.gamecore.permission.PermissionGroup;
import me.patothebest.gamecore.permission.PermissionGroupManager;
import me.patothebest.gamecore.phase.Phase;
import me.patothebest.gamecore.phase.phases.EndPhase;
import me.patothebest.gamecore.phase.phases.GamePhase;
import me.patothebest.gamecore.phase.phases.LobbyPhase;
import me.patothebest.gamecore.phase.phases.NullPhase;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.sign.SignManager;
import me.patothebest.gamecore.stats.StatsManager;
import me.patothebest.gamecore.title.TitleBuilder;
import me.patothebest.gamecore.util.DoubleCallback;
import me.patothebest.gamecore.util.MessageCallback;
import me.patothebest.gamecore.util.NameableObject;
import me.patothebest.gamecore.util.PlayerList;
import me.patothebest.gamecore.util.ServerVersion;
import me.patothebest.gamecore.util.Sounds;
import me.patothebest.gamecore.util.Utils;
import me.patothebest.gamecore.vector.ArenaLocation;
import me.patothebest.gamecore.vector.Cuboid;
import me.patothebest.gamecore.world.ArenaWorld;
import me.patothebest.gamecore.world.DefaultWorldHandler;
import me.patothebest.gamecore.world.WorldHandler;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
public abstract class AbstractArena implements GroupPermissible, ConfigurationSerializable, NameableObject {
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected final Map<AbstractGameTeam, List<Player>> teamPreferences;
// players will rejoin the team they were in if they left the arena mid-game
protected final Map<AbstractGameTeam, List<String>> lastTeams = new HashMap<>();
protected final List<ArenaOption> arenaOptions = new ArrayList<>();
protected final ArenaManager arenaManager;
protected final PlayerList players;
protected final PlayerList spectators;
protected final Map<String, Integer> topKillers;
protected final ArenaFile arenaFile;
protected final Injector injector;
protected final Provider<WorldHandler> worldHandler;
protected final CoreConfig config;
protected final CorePlugin plugin;
protected final PluginScheduler pluginScheduler;
protected final GhostFactory ghostFactory;
protected final EventRegistry eventRegistry;
protected final StatsManager statsManager;
protected final CombatManager combatManager;
private final SignManager signManager;
private final PlayerManager playerManager;
private final KitManager kitManager;
private final PermissionGroupManager permissionGroupManager;
private final String name;
protected ArenaWorld world;
protected ArenaGroup arenaGroup;
protected int minPlayers;
protected int maxPlayers;
protected boolean needsLobbyLocation = true;
protected boolean needsSpectatorLocation = true;
protected boolean needsArenaArea = true;
protected boolean publicJoinable = true;
protected boolean publicSpectable = true;
protected boolean privateArena = false;
protected boolean whitelist = false;
protected boolean teamSelector = true;
protected boolean disableSaving = false;
protected boolean disableStats = false;
protected final List<String> whitelistedPlayers = new ArrayList<>();
protected final String worldName;
protected String displayName;
protected Vector offset = new Vector(0, 0, 0);
protected ArenaLocation lobbyLocation;
protected Cuboid lobbyArea;
protected ArenaLocation spectatorLocation;
protected PermissionGroup permissionGroup;
protected final Map<String, AbstractGameTeam> teams;
protected Phase firstPhase;
protected Phase currentPhase;
// things that are going to be saved
protected volatile boolean enabled;
protected Cuboid area;
private long phaseTime;
// -------------------------------------------- //
// CONSTRUCTOR
// -------------------------------------------- //
public AbstractArena(String name, String worldName, Injector injector) {
this.name = name;
this.worldName = worldName;
this.arenaManager = injector.getInstance(ArenaManager.class);
this.injector = injector;
this.plugin = injector.getInstance(CorePlugin.class);
this.pluginScheduler = injector.getInstance(PluginScheduler.class);
this.playerManager = injector.getInstance(PlayerManager.class);
this.signManager = injector.getInstance(SignManager.class);
this.config = injector.getInstance(CoreConfig.class);
this.permissionGroupManager = injector.getInstance(PermissionGroupManager.class);
this.kitManager = injector.getInstance(KitManager.class);
this.ghostFactory = injector.getInstance(GhostFactory.class);
this.eventRegistry = injector.getInstance(EventRegistry.class);
this.statsManager = injector.getInstance(StatsManager.class);
this.worldHandler = injector.getProvider(WorldHandler.class);
this.combatManager = injector.getInstance(CombatManager.class);
world = new ArenaWorld(this);
players = new PlayerList();
spectators = new PlayerList();
arenaFile = new ArenaFile(this);
teams = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
teamPreferences = new HashMap<>();
topKillers = new HashMap<>();
minPlayers = 2;
maxPlayers = 24;
arenaOptions.add(new TimeOfDayOption());
arenaOptions.add(new TNTExplosionOption());
arenaOptions.add(new EnvironmentOption());
for (ArenaOption arenaOption : arenaOptions) {
arenaOption.setArena(this);
}
}
public void initializeData() {
// checks whether or not the arena has data saved on the file
if (arenaFile.get("data") == null) {
// if not, create the world
world.loadWorld(true);
permissionGroup = permissionGroupManager.getDefaultPermissionGroup();
} else {
// gets the configuration section as a map
Map<String, Object> map = arenaFile.getConfigurationSection("data").getValues(true);
parseData(map);
// check if the arena is valid
if (enabled && !canArenaBeEnabled(Bukkit.getConsoleSender())) {
// if is invalid and the arena is enabled, disable the arena
disableArena();
}
}
initializePhase();
if(enabled) {
currentPhase.start();
} else {
currentPhase = createPhase(NullPhase.class);
}
}
@SuppressWarnings("unchecked")
protected void parseData(Map<String, Object> map) {
enabled = (boolean) map.get("enabled");
minPlayers = (int) map.get("minplayers");
maxPlayers = (int) map.get("maxplayers");
if (map.containsKey("arenagroup")) {
arenaGroup = arenaManager.getGroup((String) map.get("arenagroup"));
}
for (ArenaOption arenaOption : arenaOptions) {
arenaOption.parse(map);
}
if (enabled) {
// unzip, load, and prepare the world
if (!map.containsKey("server-version") || !map.get("server-version").equals(ServerVersion.getVersion())) {
arenaManager.getLogger().log(Level.INFO, "Detected arena was saved with an older server version.");
arenaManager.getLogger().log(Level.INFO, "Starting arena upgrade...");
ArenaWorld conversion = new ArenaWorld(this, worldName + "-temp");
WorldHandler defaultWorldHandler = new DefaultWorldHandler();
// load world zip into temp world directory
if (!defaultWorldHandler.decompressWorld(this, world.getWorldZipFile(), conversion.getTempWorld())) {
arenaManager.getArenas().remove(name);
throw new RuntimeException("Could not unzip world for arena " + name + "!");
}
// convert
conversion.loadWorld(true, defaultWorldHandler);
conversion.unloadWorld(true);
// backup old world
String zipName = conversion.getWorldZipFile().getPath();
zipName = zipName.substring(0, zipName.lastIndexOf('.')); // strip file ext
zipName = zipName + "_backup_" + Utils.getCurrentTimeStamp("yyyy-MM-dd_HH-mm-ss") + ".zip";
conversion.getWorldZipFile().renameTo(new File(zipName));
// zip new world and delete old world
Utils.zipIt(conversion.getTempWorld(), conversion.getWorldZipFile());
Utils.deleteFolder(conversion.getTempWorld());
arenaManager.getLogger().log(Level.INFO, "Done upgrading");
}
if(!world.decompressWorld()) {
arenaManager.getArenas().remove(name);
throw new RuntimeException("Could not unzip world for arena " + name + "!");
}
world.loadWorld(false);
} else {
// load the world
world.loadWorld(true);
}
// get the lobby location if present (legacy)
if (map.get("lobbylocation") != null) {
lobbyLocation = ArenaLocation.deserialize(((MemorySection) map.get("lobbylocation")).getValues(true), this);
spectatorLocation = ArenaLocation.deserialize(((MemorySection) map.get("lobbylocation")).getValues(true), this);
}
// get the lobby location if present
if (map.get("lobby-location") != null) {
lobbyLocation = ArenaLocation.deserialize(((MemorySection) map.get("lobby-location")).getValues(true), this);
}
// get the spectator location if present
if (map.get("spectator-location") != null) {
spectatorLocation = ArenaLocation.deserialize(((MemorySection) map.get("spectator-location")).getValues(true), this);
}
// get the arena area if present
if (map.get("area") != null) {
area = new Cuboid(((MemorySection) map.get("area")).getValues(true), this);
}
// get the arena area if present
if (map.get("lobby-area") != null) {
lobbyArea = new Cuboid(((MemorySection) map.get("lobby-area")).getValues(true), this);
}
// get the arena's permission group
if (map.get("permission-group") != null) {
permissionGroup = permissionGroupManager.getOrCreatePermissionGroup((String) map.get("permission-group"));
} else {
permissionGroup = permissionGroupManager.getDefaultPermissionGroup();
}
// get the team list
if(map.get("teams") != null) {
List<Map<String, Object>> teamList = (List<Map<String, Object>>) map.get("teams");
teamList.forEach(team -> {
AbstractGameTeam gameTeam = createTeam(team);
teams.put(gameTeam.getName(), gameTeam);
});
}
}
public abstract void initializePhase();
// -------------------------------------------- //
// PHASE
// -------------------------------------------- //
public void startGame() {
nextPhase();
}
public void nextPhase() {
ArenaPrePhaseChangeEvent arenaPrePhaseChange = eventRegistry.callEvent(new ArenaPrePhaseChangeEvent(this, currentPhase, currentPhase.getNextPhase()));
if(arenaPrePhaseChange.isCancelled()) {
return;
}
if(!currentPhase.getNextPhase().isPreviousPhaseFeatures()) {
currentPhase.stop();
}
Phase oldPhase = currentPhase;
currentPhase = currentPhase.getNextPhase();
eventRegistry.callEvent(new ArenaPhaseChangeEvent(this, oldPhase, currentPhase));
currentPhase.start();
phaseTime = System.currentTimeMillis();
}
public void setPhase(Class<? extends Phase> phaseClass) {
Phase phase1 = firstPhase;
while (phase1.getClass() != phaseClass) {
phase1 = phase1.getNextPhase();
}
ArenaPrePhaseChangeEvent arenaPrePhaseChange = eventRegistry.callEvent(new ArenaPrePhaseChangeEvent(this, currentPhase, phase1));
if(arenaPrePhaseChange.isCancelled()) {
return;
}
Phase oldPhase = currentPhase;
currentPhase.stop();
currentPhase = phase1;
phaseTime = System.currentTimeMillis();
currentPhase.start();
eventRegistry.callEvent(new ArenaPhaseChangeEvent(this, oldPhase, currentPhase));
}
@SuppressWarnings("unchecked")
protected <T extends Phase> T createPhase(Class<T> phaseClass) {
T phase = injector.getInstance(phaseClass);
phase.setArena(this);
phase.configure();
return phase;
}
@SuppressWarnings("unchecked")
protected <T extends Phase> T addPhase(Class<T> phaseClass) {
T phase = injector.getInstance(phaseClass);
phase.setArena(this);
phase.configure();
return addPhase(phase);
}
@SuppressWarnings("unchecked")
protected <T extends Phase> T addPhase(T phase) {
if(firstPhase == null) {
firstPhase = phase;
currentPhase = phase;
} else {
Phase previousPhase = firstPhase;
while (previousPhase.getNextPhase() != null) {
previousPhase = previousPhase.getNextPhase();
}
previousPhase.setNextPhase(phase);
phase.setPreviousPhase(previousPhase);
if(phase.isPreviousPhaseFeatures()) {
phase.getFeatures().putAll(previousPhase.getFeatures());
}
}
return phase;
}
public Phase getPreviousPhase(Phase phase) {
Phase phase1 = firstPhase;
while (phase1.getNextPhase() != null && phase1.getNextPhase() != phase) {
phase1 = phase1.getNextPhase();
}
return phase1;
}
public Phase getNextPhase() {
return currentPhase.getNextPhase();
}
// -------------------------------------------- //
// FEATURE
// -------------------------------------------- //
public <T extends Feature> T createFeature(Class<T> featureClass) {
T feature = injector.getInstance(featureClass);
feature.setArena(this);
return feature;
}
@SuppressWarnings("unchecked")
public <T extends Feature> T getFeature(Class<T> featureClass) {
return (T) currentPhase.getFeatures().get(featureClass);
}
// -------------------------------------------- //
// GAME METHODS
// -------------------------------------------- //
public abstract void checkWin();
public void endArena(boolean regen) {
// check if the arena is enabled
if (!enabled) {
// this method shouldn't have been called
return;
}
ArenaPreRegenEvent arenaPreRegenEvent = plugin.callEvent(new ArenaPreRegenEvent(this));
if(arenaPreRegenEvent.isCancelled()) {
return;
}
// remove all the players
spectators.forEach(this::removePlayer);
players.forEach(this::removePlayer);
lastTeams.clear();
topKillers.clear();
if (currentPhase != null) {
currentPhase.stop();
}
updateSigns();
// if regen the arena...
if (regen) {
regenArena();
} else {
loadFirstPhase();
}
}
private void loadFirstPhase() {
currentPhase = firstPhase;
if(plugin.isEnabled() && currentPhase != null) {
currentPhase.start();
}
updateSigns();
}
public void removePlayer(Player player) {
removePlayer(player, false);
}
public void removePlayer(Player player, boolean offline) {
ArenaPreLeaveEvent arenaPreLeaveEvent = new ArenaPreLeaveEvent(player, this);
if(!offline) {
plugin.getServer().getPluginManager().callEvent(arenaPreLeaveEvent);
if(arenaPreLeaveEvent.isCancelled()) {
return;
}
}
IPlayer corePlayer = playerManager.getPlayer(player.getName());
// if the player is dead...
if (player.isDead()) {
try {
// ...try to respawn the player
player.spigot().respawn();
} catch (Throwable t) {
// can't respawn the player (bukkit) so we kick him
player.kickPlayer("Regenerating arena");
}
}
// gets the team the player is in
AbstractGameTeam gameTeam = getTeam(player);
if (gameTeam != null) {
gameTeam.removePlayer(player);
player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());
if(getArenaState() == ArenaState.IN_GAME && players.contains(player)) {
combatManager.killPlayer(player, false);
if(!currentPhase.canJoin()) { // check if player is not spectating
eventRegistry.callEvent(new PlayerLooseEvent(player, this));
topKillers.put(player.getName(), corePlayer.getGameKills());
plugin.getServer().getPluginManager().callEvent(new ArenaLeaveMidGameEvent(player, this, gameTeam));
}
}
}
// If the player has a team preference...
AbstractGameTeam preferenceTeam = getTeamPreference(player);
if (preferenceTeam != null) {
// ...remove the player from the preference list
teamPreferences.get(preferenceTeam).remove(player);
}
// reset arena related stuff for the player
corePlayer.getPlayerInventory().restoreInventory();
corePlayer.setCurrentArena(null);
corePlayer.setGameTeam(null);
// teleport the player to the main lobby
if (!arenaPreLeaveEvent.isCancelTeleport()) {
teleportToLobby(player);
}
// remove the player from the arena
players.remove(player);
if(spectators.contains(player)) {
spectators.remove(player);
ghostFactory.removePlayer(player);
}
// If there are no players left on the arena, we end it
if (getArenaState() == ArenaState.IN_GAME) {
// if the player quit the game...
if (offline && plugin.isEnabled()) { // isEnable check for players being kicked when server is shutting down
// ...we schedule a task to check if the arena needs ending so that the player entity
// is fully removed from the game
pluginScheduler.runTask(this::checkWin);
} else {
// ...we check if it needs ending
checkWin();
}
}
// update the signs to display the new amount of players
updateSigns();
// call player leave on the current phase
currentPhase.playerLeave(player);
// call the PlayerLeaveArenaEvent event
plugin.getServer().getPluginManager().callEvent(new ArenaLeaveEvent(player, this, gameTeam));
plugin.getServer().getPluginManager().callEvent(new PlayerStateChangeEvent(player, this, PlayerStateChangeEvent.PlayerState.NONE));
callLeaveEvent(player, gameTeam);
}
public void changeToSpectator(Player player, boolean shouldTeleport) {
// NoBorderTrespassingFeature calls this method again, so we check if it isn't called twice
if(spectators.contains(player)) {
if(shouldTeleport) {
// teleport the player and give items
player.teleport(getSpectatorLocation());
}
return;
}
IPlayer corePlayer = playerManager.getPlayer(player);
// clear inventory
corePlayer.getPlayerInventory().clearPlayer();
// set fly mode
pluginScheduler.runTaskLater(() -> {
player.setAllowFlight(true);
player.setFlying(true);
}, 1L);
// gets the team the player is in
AbstractGameTeam gameTeam = getTeam(player);
if (gameTeam != null) {
gameTeam.removePlayer(player);
if(!currentPhase.canJoin() && getArenaState() == ArenaState.IN_GAME) {
eventRegistry.callEvent(new PlayerLooseEvent(player, this));
topKillers.put(player.getName(), corePlayer.getGameKills());
}
}
// remove the player from the arena
players.remove(player);
spectators.add(player);
if(shouldTeleport) {
// teleport the player and give items
player.teleport(currentPhase instanceof LobbyPhase ? lobbyLocation : spectatorLocation);
}
ghostFactory.addPlayer(player);
plugin.getServer().getPluginManager().callEvent(new SpectateEvent(player, this));
plugin.getServer().getPluginManager().callEvent(new PlayerStateChangeEvent(player, this, PlayerStateChangeEvent.PlayerState.SPECTATOR));
// update the signs to display the new amount of players
updateSigns();
// call player leave on the current phase
currentPhase.playerLeave(player);
}
public void changeToPlayer(Player player) {
IPlayer corePlayer = playerManager.getPlayer(player);
// clear inventory
corePlayer.getPlayerInventory().clearPlayer();
// remove the player from the arena
spectators.remove(player);
players.add(player);
currentPhase.playerJoin(player);
ghostFactory.removePlayer(player);
plugin.getServer().getPluginManager().callEvent(new PlayerStateChangeEvent(player, this, PlayerStateChangeEvent.PlayerState.PLAYER));
// update the signs to display the new amount of players
updateSigns();
}
protected void teleportToLobby(Player player) {
if (config.isUseMainLobby() && config.getMainLobby() != null) {
player.teleport(config.getMainLobby());
return;
}
player.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
}
public void addPlayer(Player player) {
Validate.isTrue(!playerManager.getPlayer(player).isInArena(), "Player is already in an arena.");
ArenaPreJoinEvent arenaPreJoinEvent = eventRegistry.callEvent(new ArenaPreJoinEvent(player, this));
if (!arenaPreJoinEvent.isCancelled()) {
currentPhase.playerJoin(player);
}
}
public void addSpectator(Player player) {
spectators.add(player);
IPlayer iPlayer = playerManager.getPlayer(player);
// sets the arena of the player and saves the player state
iPlayer.setCurrentArena(this);
Location teleportLocation = currentPhase instanceof LobbyPhase ? lobbyLocation : spectatorLocation;
if(iPlayer.isFullyJoined()) {
// teleport the player and give items
player.teleport(teleportLocation);
} else {
iPlayer.setJoinLocation(teleportLocation);
}
iPlayer.executeWhenFullyLoaded(player1 -> {
iPlayer.getPlayerInventory().savePlayer();
// call events
plugin.getServer().getPluginManager().callEvent(new GameJoinEvent(player, this));
plugin.getServer().getPluginManager().callEvent(new SpectateEvent(player, this));
ghostFactory.addPlayer(player);
pluginScheduler.runTaskLater(() -> {
// set fly mode
player.setAllowFlight(true);
player.setFlying(true);
}, 3L);
});
// update signs
signManager.updateSigns();
}
public boolean isInGame() {
return currentPhase instanceof GamePhase;
}
/**
* Special method for TheTowersRemasteredAPI
* This allows the arena implementation to call the leave event
* from the api
*
* @param player the player
* @param team the team
*/
protected void callLeaveEvent(Player player, AbstractGameTeam team) { }
// -------------------------------------------- //
// SETUP METHODS
// -------------------------------------------- //
public void enableArena() {
// teleport the players on the world to the lobby
getWorld().getPlayers().forEach(this::teleportToLobby);
// save and unload the world
getWorld().save();
Bukkit.getServer().unloadWorld(getWorld(), true);
pluginScheduler.runTaskLaterAsynchronously(() -> {
// zip the world and delete the world folder
Utils.zipIt(world.getTempWorld(), world.getWorldZipFile());
Utils.deleteFolder(world.getTempWorld());
// unzip and load the world
unzipAndLoad(true, () -> {
currentPhase.stop();
currentPhase = firstPhase;
currentPhase.start();
updateSigns();
});
}, 20L);
enabled = true;
}
public void disableArena() {
// teleport the players on the world to the lobby
getWorld().getPlayers().forEach(this::teleportToLobby);
// end the game if there is one without regenerating
endArena(false);
// unload the world
world.unloadWorld(false);
pluginScheduler.runTaskLaterAsynchronously(() -> {
// delete thr world
world.deleteWorld();
// unzip the world and load a fresh one
unzipAndLoad(false, () -> {
// delete the world zip
world.getWorldZipFile().delete();
eventRegistry.callEvent(new ArenaDisableEvent(this));
});
}, 20L);
enabled = false;
if (currentPhase != null) {
currentPhase.stop();
}
currentPhase = createPhase(NullPhase.class);
updateSigns();
}
// -------------------------------------------- //
// ARENA WORLD STUFF
// -------------------------------------------- //
private boolean decompress() {
return world.decompressWorld();
}
private void regenArena() {
// If the plugin is disabled...
if (!plugin.isEnabled()) {
// ...only delete the world
world.unloadWorld(false);
world.deleteWorld();
} else {
// schedule a task to delete and load the world
world.unloadWorld(false);
pluginScheduler.runTaskLaterAsynchronously(() -> {
world.deleteWorld();
unzipAndLoad(true, this::loadFirstPhase);
}, 20L);
/*for (Chunk chunk : area.getChunks()) {
chunk.unload(false);
}
loadFirstPhase();*/
}
}
private void unzipAndLoad(boolean tempArena, Runnable onLoad) {
// do not regen if the plugin is disabled
if (!plugin.isEnabled()) {
return;
}
// if plugin failed to unzip...
boolean unzip;
if (tempArena) {
unzip = world.decompressWorld();
} else {
unzip = Utils.unZip(world.getWorldZipFile().getPath(), world.getTempWorld().getPath());
}
if (!unzip) {
System.err.println("Could not unzip world folder!");
// ...set the arena state to error and update signs
updateSigns();
return;
}
Runnable runnable = () -> {
// prepare the world
world.loadWorld(!tempArena);
pluginScheduler.runTask(() -> {
if (tempArena) {
// update state and signs
updateSigns();
}
onLoad.run();
});
};
if (worldHandler.get().hasAsyncSupport() && tempArena) {
pluginScheduler.runTaskAsynchronously(runnable);
} else {
pluginScheduler.runTask(runnable);
}
}
public void delete() {
arenaFile.delete();
destroy();
}
public void save() {
if (!disableSaving) {
arenaFile.save();
}
}
public void saveAndDestroy() {
save();
destroy();
}
public void destroy() {
players.forEach(this::removePlayer);
spectators.forEach(this::removePlayer);
if (enabled && !(currentPhase instanceof EndPhase)) {
world.unloadWorld(false);
world.deleteWorld();
} else if(!enabled) {
world.unloadWorld(true);
}
// unregisters all arena listeners
currentPhase.stop();
currentPhase = firstPhase;
while (currentPhase != null) {
currentPhase.destroy();
currentPhase = currentPhase.getNextPhase();
}
currentPhase = null;
arenaManager.getArenas().remove(getWorldName());
eventRegistry.callEvent(new ArenaUnLoadEvent(this));
}
@Override
public Map<String, Object> serialize() {
// map to store data
Map<String, Object> objectMap = new HashMap<>();
// serialize everything
objectMap.put("enabled", enabled);
if (lobbyLocation != null) {
objectMap.put("lobby-location", lobbyLocation.serialize());
}
if (spectatorLocation != null) {
objectMap.put("spectator-location", spectatorLocation.serialize());
}
if (area != null) {
objectMap.put("area", getArea().serialize());
}
if (lobbyArea != null) {
objectMap.put("lobby-area", lobbyArea.serialize());
}
List<Map<String, Object>> teams = serializeTeams();
if(teams != null) {
objectMap.put("teams", teams);
}
objectMap.put("permission-group", permissionGroup.getName());
objectMap.put("minplayers", minPlayers);
objectMap.put("maxplayers", getMaxPlayers());
objectMap.put("server-version", ServerVersion.getVersion());
for (ArenaOption arenaOption : arenaOptions) {
arenaOption.serialize(objectMap);
}
if (arenaGroup != null) {
objectMap.put("arenagroup", arenaGroup.getName());
}
return objectMap;
}
protected List<Map<String, Object>> serializeTeams() {
List<Map<String, Object>> teamList = new ArrayList<>();
teams.forEach((key, value) -> teamList.add(value.serialize()));
return teamList;
}
public boolean canArenaBeEnabled(CommandSender sender) {
boolean canBeEnabled = true;
// check if the arena area is set
if (area == null && needsArenaArea) {
canBeEnabled = false;
sender.sendMessage(CoreLang.SETUP_ERROR_SET_AREA.getMessage(sender));
}
// check if the lobby location is set
if (lobbyLocation == null && needsLobbyLocation) {
canBeEnabled = false;
sender.sendMessage(CoreLang.SETUP_ERROR_LOBBY_LOCATION.getMessage(sender));
}
// check if the spectator location is set
if (spectatorLocation == null && needsSpectatorLocation) {
canBeEnabled = false;
sender.sendMessage(CoreLang.SETUP_ERROR_SPECTATOR_LOCATION.getMessage(sender));
}
// check if the minimum amount of players is tw
if (minPlayers < 2) {
canBeEnabled = false;
sender.sendMessage(CoreLang.SETUP_ERROR_MIN_PLAYERS.getMessage(sender));
}
// check if the minimum amount of players does not surpass the maximum amount
if (getMaxPlayers() < minPlayers) {
canBeEnabled = false;
sender.sendMessage(CoreLang.SETUP_ERROR_MIN_MAX.getMessage(sender));
}
return canBeEnabled;
}
// -------------------------------------------- //
// MESSAGES
// -------------------------------------------- //
public void sendMessageToArena(MessageCallback<Player> locale) {
players.forEach(player -> {
playerManager.getPlayer(player).executeWhenFullyLoaded(player1 -> player.sendMessage(locale.call(player)));
});
spectators.forEach(spectator -> {
playerManager.getPlayer(spectator).executeWhenFullyLoaded(spectator1 -> spectator.sendMessage(locale.call(spectator)));
});
}
public void sendActionBarToArena(MessageCallback<Player> locale) {
players.forEach(player -> ActionBar.sendActionBar(player, locale.call(player)));
spectators.forEach(player -> ActionBar.sendActionBar(player, locale.call(player)));
}
public void sendTitleToArena(DoubleCallback<Player, TitleBuilder> locale) {
players.forEach(player -> {
TitleBuilder titleBuilder = TitleBuilder.newTitle();
locale.call(player, titleBuilder);
titleBuilder.build().send(player);
});
spectators.forEach(player -> {
TitleBuilder titleBuilder = TitleBuilder.newTitle();
locale.call(player, titleBuilder);
titleBuilder.build().send(player);
});
}
public void playSound(Sounds sound) {
for (Player player : players) {
sound.play(player);
}
for (Player spectator : spectators) {
sound.play(spectator);
}
}
// -------------------------------------------- //
// SIGNS
// -------------------------------------------- //
protected void updateSigns() {
signManager.updateSigns();
}
// -------------------------------------------- //
// TEAMS
// -------------------------------------------- //
private AbstractGameTeam getTeamPreference(Player player, AbstractGameTeam other) {
return teamPreferences.keySet().stream().filter(gameTeam -> teamPreferences.get(gameTeam).contains(player)).findFirst().orElse(other);
}
public AbstractGameTeam getTeamPreference(Player player) {
return getTeamPreference(player, null);
}
public AbstractGameTeam getTeam(Player player) {
return teams.values().stream().filter(gameTeam -> gameTeam.hasPlayer(player)).findFirst().orElse(null);
}
public AbstractGameTeam getTeam(DyeColor color) {
return teams.values().stream().filter(gameTeam -> gameTeam.getColor() == color).findFirst().orElse(null);
}
public AbstractGameTeam getNewTeamForPlayer(Player player) {
AbstractGameTeam teamPreference = getTeamPreference(player);
if (teamPreference != null) {
teamPreferences.get(teamPreference).remove(player);
return teamPreference;
}
for (Map.Entry<AbstractGameTeam, List<String>> teamListEntry : lastTeams.entrySet()) {
if (teamListEntry.getValue().contains(player.getName())) {
return teamListEntry.getKey();
}
}
return getTeamWithLowestPlayers();
}
public AbstractGameTeam getTeamWithLowestPlayers() {
return teams.values().stream().min(Comparator.comparingInt(o -> o.getPlayers().size())).orElseThrow(() -> new IllegalStateException("No teams found in arena " + name));
}
public void removeGameTeam(String name) {
teams.remove(name);
}
public Map<String, AbstractGameTeam> getTeams() {
return teams;
}
public boolean containsTeam(String name) {
return getTeam(name) != null;
}
public AbstractGameTeam getTeam(String name) {
return teams.get(name);
}
public void addTeam(AbstractGameTeam gameTeam) {
teams.put(gameTeam.getName(), gameTeam);
}
public Map<AbstractGameTeam, List<Player>> getTeamPreferences() {
return teamPreferences;
}
// -------------------------------------------- //
// ABSTRACT METHODS
// -------------------------------------------- //
public abstract AbstractGameTeam createTeam(String name, DyeColor color);
public abstract AbstractGameTeam createTeam(Map<String, Object> data);
public abstract int getMinimumRequiredPlayers();
// -------------------------------------------- //
// GETTERS AND SETTERS
// -------------------------------------------- //
@Override
public PermissionGroup getPermissionGroup() {
return permissionGroup;
}
@Override
public void setPermissionGroup(PermissionGroup permissionGroup) {
this.permissionGroup = permissionGroup;
}
public boolean isEnabled() {
return enabled;
}
public boolean canJoin(Player player) {
if (enabled && whitelist) {
return whitelistedPlayers.contains(player.getName());
}
return enabled && publicJoinable && permissionGroup.hasPermission(player);
}
public boolean canSpectate(Player player) {
if (enabled && whitelist) {
return whitelistedPlayers.contains(player.getName()) || publicSpectable;
}
return enabled && (publicJoinable || publicSpectable);
}
public boolean isFull() {
return players.size() >= getMaxPlayers();
}
public ArenaFile getArenaFile() {
return arenaFile;
}
public PlayerList getPlayers() {
return players;
}
public PlayerList getSpectators() {
return spectators;
}
public ArenaLocation getLobbyLocation() {
return lobbyLocation;
}
public ArenaLocation getSpectatorLocation() {
return spectatorLocation;
}
public Cuboid getArea() {
return area;
}
public int getMaxPlayers() {
return maxPlayers;
}
public void setArea(Cuboid area) {
this.area = area;
}
public void setMinPlayers(int minPlayers) {
this.minPlayers = minPlayers;
}
public void setMaxPlayers(int maxPlayers) {
this.maxPlayers = maxPlayers;
}
public int getMinPlayers() {
return minPlayers;
}
public String getName() {
return name;
}
public void setWhitelist(boolean whitelist) {
this.whitelist = whitelist;
}
public boolean isWhitelist() {
return whitelist;
}
public List<String> getWhitelistedPlayers() {
return whitelistedPlayers;
}
public boolean isDisableSaving() {
return disableSaving;
}
public void setDisableSaving(boolean disableSaving) {
this.disableSaving = disableSaving;
}
public void setPublicJoinable(boolean publicJoinable) {
this.publicJoinable = publicJoinable;
}
public boolean isPublicJoinable() {
return publicJoinable;
}
public boolean isPublicSpectable() {
return publicSpectable;
}
public void setPublicSpectable(boolean publicSpectable) {
this.publicSpectable = publicSpectable;
}
public boolean isTeamSelector() {
return teamSelector;
}
public void setTeamSelector(boolean teamSelector) {
this.teamSelector = teamSelector;
}
public boolean isPrivateArena() {
return privateArena;
}
public void setPrivateArena(boolean privateArena) {
this.privateArena = privateArena;
}
public ArenaGroup getArenaGroup() {
return arenaGroup;
}
public void setArenaGroup(ArenaGroup arenaGroup) {
this.arenaGroup = arenaGroup;
}
/**
* Will return the world name
* <p>
* WARNING: It <b>may</b> be different from the arena name. An example
* as to when it could be different would be when the arena is forced to
* have a different world name to have multiple arenas with the same map
* running concurrently.
* See {@link AdvancedBungeeMode}.
*
* @return the world name
*/
public String getWorldName() {
return worldName;
}
public String getDisplayName() {
return displayName == null ? worldName : displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public World getWorld() {
return world.getWorld();
}
public ArenaWorld getArenaWorld() {
return world;
}
public Phase getPhase() {
return currentPhase;
}
public void setLobbyLocation(Location lobbyLocation) {
this.lobbyLocation = new ArenaLocation(this, lobbyLocation);
}
public void setSpectatorLocation(Location spectatorLocation) {
this.spectatorLocation = new ArenaLocation(this, spectatorLocation);
}
public Cuboid getLobbyArea() {
return lobbyArea;
}
public void setLobbyArea(Cuboid lobbyArea) {
this.lobbyArea = lobbyArea;
}
public boolean isDisableStats() {
return disableStats;
}
public void setDisableStats(boolean disableStats) {
this.disableStats = disableStats;
}
public PlayerManager getPlayerManager() {
return playerManager;
}
public StatsManager getStatsManager() {
return statsManager;
}
/**
* Gets topKillers
*
* @return value of topKillers
*/
public Map<String, Integer> getTopKillers() {
return topKillers;
}
public boolean canJoinArena() {
switch (getArenaState()) {
case WAITING:
case STARTING:
case IN_GAME:
return true;
case ENDING:
case RESTARTING:
case OTHER:
case ERROR:
return false;
}
throw new IllegalStateException("Unhandled arena state " + getArenaState());
}
public ArenaState getArenaState() {
return currentPhase.getArenaState();
}
public KitManager getKitManager() {
return kitManager;
}
public long getPhaseTime() {
return phaseTime;
}
public long getTimePhaseHasBeenRunning() {
return System.currentTimeMillis() - phaseTime;
}
public EventRegistry getEventRegistry() {
return eventRegistry;
}
void addPlayerToLastTeam(AbstractGameTeam team, Player player) {
if (!lastTeams.containsKey(team)) {
lastTeams.put(team, new ArrayList<>());
}
lastTeams.get(team).add(player.getName());
}
public boolean hasLastTeam(Player player) {
for (Map.Entry<AbstractGameTeam, List<String>> teamListEntry : lastTeams.entrySet()) {
if (teamListEntry.getValue().contains(player.getName())) {
return true;
}
}
return false;
}
public <T extends ArenaOption> T getOption(Class<? extends T> arenaOptionClass) {
for (ArenaOption arenaOption : arenaOptions) {
if (arenaOption.getClass() == arenaOptionClass) {
return (T) arenaOption;
}
}
throw new IllegalArgumentException("Option " + arenaOptionClass.getName() + " is not registered!");
}
public List<ArenaOption> getArenaOptions() {
return arenaOptions;
}
public Provider<WorldHandler> getWorldHandler() {
return worldHandler;
}
public PluginScheduler getPluginScheduler() {
return pluginScheduler;
}
public Vector getOffset() {
return offset;
}
public void setOffset(Vector offset) {
this.offset = offset;
}
public void setArenaWorld(ArenaWorld arenaWorld) {
this.world = arenaWorld;
}
}
| 46,111 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/ArenaManager.java | package me.patothebest.gamecore.arena;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.event.arena.ArenaLoadEvent;
import me.patothebest.gamecore.logger.InjectLogger;
import me.patothebest.gamecore.logger.Logger;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.modules.ReloadableModule;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.sign.SignManager;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.stream.Collectors;
@Singleton
@ModuleName("Arena Manager")
public class ArenaManager implements ActivableModule, ReloadableModule {
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
public final static File ARENA_DIRECTORY = new File(Utils.PLUGIN_DIR, "arenas");
private final CorePlugin plugin;
private final PluginScheduler pluginScheduler;
private final ArenaFactory arenaFactory;
private final Map<String, AbstractArena> arenas;
private final Map<String, ArenaGroup> arenaGroups = new HashMap<>();
private boolean loadMaps = true;
@InjectLogger private Logger logger;
// Sorted by:
private final Comparator<AbstractArena> arenaComparator = (arena1, arena2) -> {
if (arena1.isPublicJoinable() != arena2.isPublicJoinable()) {
return Boolean.compare(arena2.isPublicJoinable(), arena1.isPublicJoinable());
} else if (arena1.canJoinArena() != arena2.canJoinArena()){
return Boolean.compare(arena2.canJoinArena(), arena1.canJoinArena());
} else if (arena1.getPhase().canJoin() != arena2.getPhase().canJoin()) {
return Boolean.compare(arena2.getPhase().canJoin(), arena1.getPhase().canJoin());
} else {
return Integer.compare(arena2.getPlayers().size(), arena1.getPlayers().size());
}
};
// -------------------------------------------- //
// CONSTRUCTOR
// -------------------------------------------- //
@Inject private ArenaManager(CorePlugin plugin, PluginScheduler pluginScheduler, ArenaFactory arenaFactory, Set<ArenaGroup> arenaGroups) {
this.plugin = plugin;
this.pluginScheduler = pluginScheduler;
this.arenaFactory = arenaFactory;
for (ArenaGroup arenaGroup : arenaGroups) {
this.arenaGroups.put(arenaGroup.getName().toUpperCase(), arenaGroup);
}
// case insensitive to avoid issues
this.arenas = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
// If the arena directory does not exist...
if (!ARENA_DIRECTORY.exists()) {
// ...create the directory
ARENA_DIRECTORY.mkdirs();
}
}
// -------------------------------------------- //
// PUBLIC METHODS
// -------------------------------------------- //
@Override
public void onPreEnable() {
arenaGroups.forEach((groupName, arenaGroup) -> {
logger.config("Registering group {0}", groupName);
});
}
@Override
public void onEnable() {
if (!loadMaps) {
return;
}
logger.info(ChatColor.YELLOW + "Loading arenas...");
// If there are no files on the folder...
if (ARENA_DIRECTORY.listFiles() == null) {
// ...return
return;
}
// iterate over every file
for (File file : ARENA_DIRECTORY.listFiles()) {
String name = file.getName().replace(".yml", "");
loadArena(name);
}
}
public AbstractArena reloadArena(AbstractArena arena) {
arena.saveAndDestroy();
arenas.remove(arena.getName());
return loadArena(arena.getName());
}
public AbstractArena loadArena(String name) {
return loadArena(name, name);
}
public AbstractArena loadArena(String name, String mapName) {
return loadArena(name, mapName, true);
}
public AbstractArena loadArena(String name, String mapName, boolean initialize) {
// try to load it
try {
logger.fine(ChatColor.YELLOW + "loading arena " + name);
// create and load the arena into memory
AbstractArena arena = createArena(name, mapName, initialize);
if (arenas.containsValue(arena)) {
pluginScheduler.ensureSync(() -> plugin.callEvent(new ArenaLoadEvent(arena)));
logger.config("Loaded arena " + arena.getName());
return arena;
}
} catch (Throwable t) {
logger.log(Level.SEVERE, ChatColor.RED + "Could not load arena " + name + "!", t);
}
return null;
}
@Override
public void onDisable() {
// stop and save arenas
arenas.values().forEach(arena -> {
// try to save them
try {
arena.saveAndDestroy();
} catch (Throwable t) {
logger.log(Level.SEVERE, ChatColor.RED + "Could not save arena " + arena.getName() + "!", t);
}
});
logger.info("Ended all arenas and saved them");
}
@Override
public void onReload() {
// stop arenas
arenas.values().forEach(arena -> {
try {
arena.destroy();
} catch (Throwable t) {
logger.log(Level.SEVERE, ChatColor.RED + "Could not destroy arena " + arena.getName() + "!", t);
}
});
arenas.clear();
onEnable();
plugin.getInjector().getInstance(SignManager.class).onReload();
}
@Override
public String getReloadName() {
return "arenas";
}
public AbstractArena createArena(String name) {
return createArena(name, name, true);
}
public AbstractArena createArena(String name, String mapName, boolean initialize) {
// create the object
AbstractArena arena = arenaFactory.create(name, mapName);
if (initialize) {
arena.initializeData();
}
// store it in the map
arenas.put(mapName, arena);
return arena;
}
public boolean arenaExists(String arena) {
return getArena(arena) != null;
}
public AbstractArena getArena(String arenaName) {
return arenas.get(arenaName);
}
public Map<String, AbstractArena> getArenas() {
return arenas;
}
public List<AbstractArena> getJoinableArenas(Player player) {
return getJoinableArenas(player, t -> true);
}
public List<AbstractArena> getJoinableArenas(Player player, Predicate<AbstractArena> filter) {
return arenas.values()
.stream()
.filter(arena -> arena.canJoin(player) && arena.getPhase().canJoin())
.filter(filter)
.sorted(arenaComparator)
.collect(Collectors.toList());
}
public List<AbstractArena> getAvailableArenas(Player player) {
return getAvailableArenas(player, t -> true);
}
public List<AbstractArena> getAvailableArenas(Player player, Predicate<AbstractArena> filter) {
return arenas.values()
.stream()
.filter(arena -> arena.canJoin(player) || arena.canSpectate(player))
.filter(filter)
.sorted(arenaComparator)
.collect(Collectors.toList());
}
public ArenaGroup getGroup(String name) {
return arenaGroups.get(name.toUpperCase());
}
public boolean usesArenaGroups() {
return arenaGroups.size() > 1;
}
public void setLoadMaps(boolean loadMaps) {
this.loadMaps = loadMaps;
}
public Logger getLogger() {
return logger;
}
}
| 8,241 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AdvancedBungeeModeCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/bungee/AdvancedBungeeModeCommand.java | package me.patothebest.gamecore.arena.modes.bungee;
import com.google.inject.Inject;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.chat.CommandPagination;
import me.patothebest.gamecore.command.BaseCommand;
import me.patothebest.gamecore.command.ChildOf;
import me.patothebest.gamecore.command.Command;
import me.patothebest.gamecore.command.CommandContext;
import me.patothebest.gamecore.command.CommandException;
import me.patothebest.gamecore.command.CommandPermissions;
import me.patothebest.gamecore.command.CommandsManager;
import me.patothebest.gamecore.command.LangDescription;
import me.patothebest.gamecore.command.NestedCommand;
import me.patothebest.gamecore.modules.ParentCommandModule;
import me.patothebest.gamecore.modules.RegisteredCommandModule;
import me.patothebest.gamecore.permission.Permission;
import me.patothebest.gamecore.util.CommandUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.List;
public class AdvancedBungeeModeCommand implements ParentCommandModule {
private final AdvancedBungeeMode bungeeMode;
@Inject private AdvancedBungeeModeCommand(AdvancedBungeeMode bungeeMode) {
this.bungeeMode = bungeeMode;
}
@ChildOf(BaseCommand.class)
public static class Parent implements RegisteredCommandModule {
private final CommandsManager<CommandSender> commandsManager;
@Inject
private Parent(CommandsManager<CommandSender> commandsManager) {
this.commandsManager = commandsManager;
}
@Command(
aliases = "bungee",
langDescription = @LangDescription(
langClass = CoreLang.class,
element = "BUNGEE_COMMANDS_DESC"
)
)
@CommandPermissions(permission = Permission.ADMIN)
@NestedCommand(value = AdvancedBungeeModeCommand.class)
public void signs(CommandContext args, CommandSender sender) throws CommandException {
new CommandPagination(commandsManager, args).display(sender);
}
}
@Command(
aliases = {"changemap"},
usage = "<world> <arena>",
min = 2,
max = 2,
langDescription = @LangDescription(
element = "CHANGE_ARENA",
langClass = CoreLang.class
)
)
public List<String> changeArena(CommandContext args, CommandSender sender) throws CommandException {
CommandUtils.validateTrue(bungeeMode.isEnabled(), CoreLang.NOT_IN_BUNGEE_MODE);
if(args.getSuggestionContext() != null) {
if(args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), bungeeMode.getArenas().keySet());
} else if(args.getSuggestionContext().getIndex() == 1) {
return CommandUtils.complete(args.getString(1), bungeeMode.getEnabledArenas());
}
return null;
}
String world = args.getString(0);
String arena = args.getString(1);
CommandUtils.validateTrue(bungeeMode.getArenas().containsKey(world), CoreLang.INVALID_ARENA);
CommandUtils.validateTrue(bungeeMode.getEnabledArenas().contains(arena), CoreLang.INVALID_ARENA);
bungeeMode.changeArena(world, arena);
return null;
}
@Command(
aliases = {"restart"},
langDescription = @LangDescription(
element = "RESTART_SERVER",
langClass = CoreLang.class
)
)
public void restartServer(CommandContext args, CommandSender sender) throws CommandException {
CommandUtils.validateTrue(bungeeMode.isEnabled(), CoreLang.NOT_IN_BUNGEE_MODE);
if(Bukkit.getOnlinePlayers().size() == 0) {
Bukkit.shutdown();
return;
}
bungeeMode.restartASAP();
}
@Command(
aliases = {"addplayer"},
langDescription = @LangDescription(
element = "ADD_PLAYER",
langClass = CoreLang.class
),
min = 2,
max = 2
)
public List<String> addplayer(CommandContext args, CommandSender sender) throws CommandException {
CommandUtils.validateTrue(bungeeMode.isEnabled(), CoreLang.NOT_IN_BUNGEE_MODE);
if (args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), bungeeMode.getArenas().keySet());
}
return null;
}
String world = args.getString(0);
CommandUtils.validateTrue(bungeeMode.getArenas().containsKey(world), CoreLang.INVALID_ARENA);
bungeeMode.getPlayerCache().put(args.getString(1), bungeeMode.getArenas().get(world));
return null;
}
} | 4,923 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
BungeeModeCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/bungee/BungeeModeCommand.java | package me.patothebest.gamecore.arena.modes.bungee;
import com.google.inject.Inject;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.command.ChildOf;
import me.patothebest.gamecore.command.Command;
import me.patothebest.gamecore.command.CommandContext;
import me.patothebest.gamecore.command.CommandException;
import me.patothebest.gamecore.command.LangDescription;
import me.patothebest.gamecore.commands.admin.AdminCommand;
import me.patothebest.gamecore.modules.ParentCommandModule;
import me.patothebest.gamecore.util.CommandUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.List;
@ChildOf(value = AdminCommand.class)
public class BungeeModeCommand implements ParentCommandModule {
private final BungeeMode bungeeMode;
@Inject private BungeeModeCommand(BungeeMode bungeeMode) {
this.bungeeMode = bungeeMode;
}
@Command(
aliases = {"changearena"},
usage = "<arena>",
min = 1,
max = 1,
langDescription = @LangDescription(
element = "CHANGE_ARENA",
langClass = CoreLang.class
)
)
public List<String> changeArena(CommandContext args, CommandSender sender) throws CommandException {
CommandUtils.validateTrue(bungeeMode.isEnabled(), CoreLang.NOT_IN_BUNGEE_MODE);
if(args.getSuggestionContext() != null) {
if(args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), bungeeMode.getEnabledArenas());
}
return null;
}
String arena = args.getString(0);
CommandUtils.validateTrue(bungeeMode.getEnabledArenas().contains(arena), CoreLang.INVALID_ARENA);
bungeeMode.changeArena(arena);
return null;
}
@Command(
aliases = {"restart"},
langDescription = @LangDescription(
element = "RESTART_SERVER",
langClass = CoreLang.class
)
)
public void restartServer(CommandContext args, CommandSender sender) throws CommandException {
CommandUtils.validateTrue(bungeeMode.isEnabled(), CoreLang.NOT_IN_BUNGEE_MODE);
if(Bukkit.getOnlinePlayers().size() == 0) {
Bukkit.shutdown();
return;
}
bungeeMode.restartASAP();
}
} | 2,420 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
BungeeHandler.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/bungee/BungeeHandler.java | package me.patothebest.gamecore.arena.modes.bungee;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.google.inject.Inject;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ModuleName;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ModuleName("Bungee Handler")
public class BungeeHandler implements ActivableModule {
private final CorePlugin corePlugin;
@Inject private BungeeHandler(CorePlugin corePlugin) {
this.corePlugin = corePlugin;
}
@Override
public void onEnable() {
Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(corePlugin, "BungeeCord");
}
public void sendPlayer(Player player, String server) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(server);
player.sendPluginMessage(corePlugin, "BungeeCord", out.toByteArray());
}
}
| 1,041 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
BungeeMode.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/bungee/BungeeMode.java | package me.patothebest.gamecore.arena.modes.bungee;
import com.google.inject.Inject;
import me.patothebest.gamecore.api.BungeeStateUpdate;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.arena.ArenaPreRegenEvent;
import me.patothebest.gamecore.event.player.ArenaPreLeaveEvent;
import me.patothebest.gamecore.event.player.PlayerLoginPrepareEvent;
import me.patothebest.gamecore.file.CoreConfig;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ListenerModule;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.phase.phases.EndPhase;
import me.patothebest.gamecore.placeholder.PlaceHolderManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.scoreboard.CoreScoreboardType;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.ServerListPingEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ModuleName("Bungee Mode")
public class BungeeMode implements ActivableModule, ListenerModule {
private final PluginScheduler pluginScheduler;
private final CoreConfig coreConfig;
private final ArenaManager arenaManager;
private final BungeeHandler bungeeHandler;
private final EventRegistry eventRegistry;
private final PlaceHolderManager placeHolderManager;
private final Map<String, String> motdStatus = new HashMap<>();
private final Map<String, AbstractArena> playerQueue = new ConcurrentHashMap<>();
private final Set<String> enabledArenas = new HashSet<>();
private final List<String> loadingPlayers = new ArrayList<>();
private String repo;
private boolean enabled;
private boolean changingArena;
private boolean restartASAP = false;
private int restartAfter;
private int arenasPlayed;
private AbstractArena abstractArena;
private String lobbyServer;
@Inject private BungeeMode(PluginScheduler pluginScheduler, CoreConfig coreConfig, ArenaManager arenaManager, BungeeHandler bungeeHandler, EventRegistry eventRegistry, PlaceHolderManager placeHolderManager) {
this.pluginScheduler = pluginScheduler;
this.coreConfig = coreConfig;
this.arenaManager = arenaManager;
this.bungeeHandler = bungeeHandler;
this.eventRegistry = eventRegistry;
this.placeHolderManager = placeHolderManager;
}
@SuppressWarnings("ConstantConditions")
@Override
public void onPreEnable() {
ConfigurationSection bungeeSection = coreConfig.getConfigurationSection("bungee-mode");
if(bungeeSection == null) {
return;
}
if(!bungeeSection.getBoolean("enabled")) {
return;
}
String arena = bungeeSection.getString("arena");
if(arena.equalsIgnoreCase("random")) {
if(ArenaManager.ARENA_DIRECTORY.listFiles() == null) {
Utils.printError("Could not find arena directory!");
return;
}
for (File file : ArenaManager.ARENA_DIRECTORY.listFiles()) {
enabledArenas.add(file.getName().replace(".yml", ""));
}
if(!loadRandomArena()) {
return;
}
} else {
abstractArena = arenaManager.loadArena(arena);
if(abstractArena == null) {
Utils.printError("Could not find arena " + arena + " for bungee-mode!");
return;
}
}
bungeeSection.getConfigurationSection("motd").getValues(true).forEach((status, motd) -> motdStatus.put(status, (String) motd));
lobbyServer = bungeeSection.getString("leave-server");
restartAfter = bungeeSection.getInt("restart-after");
repo = bungeeSection.getString("repo");
enabled = true;
arenaManager.setLoadMaps(false);
}
private boolean loadRandomArena() {
if(repo != null && !repo.isEmpty()) {
try {
String list = Utils.urlToString(new URL(repo), StandardCharsets.UTF_8);
String[] split = list.split("\n");
ArrayList<String> arenaList = new ArrayList<>(enabledArenas);
arenaList.retainAll(Arrays.asList(split));
return loadArena(Utils.getRandomElementFromCollection(arenaList));
} catch (IOException e) {
e.printStackTrace();
return loadArena(Utils.getRandomElementFromCollection(enabledArenas));
}
} else {
return loadArena(Utils.getRandomElementFromCollection(enabledArenas));
}
}
private boolean loadArena(String name) {
abstractArena = arenaManager.loadArena(name);
if(abstractArena == null) {
Utils.printError("Could not find an arena for bungee-mode!");
}
arenasPlayed++;
try {
Utils.setMaxPlayers(abstractArena.getMaxPlayers());
} catch (ReflectiveOperationException e) {
Utils.printError("Could not set max players!");
e.printStackTrace();
}
return abstractArena != null;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
if(!enabled) {
return;
}
if(event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
return;
}
if(abstractArena.canJoinArena()) {
if(abstractArena.getPhase().canJoin()) {
loadingPlayers.add(event.getName());
}
return;
}
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
event.setKickMessage(CoreLang.ARENA_IS_RESTARTING.getDefaultMessage());
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPreLogin2(AsyncPlayerPreLoginEvent event) {
if(!enabled) {
return;
}
if(event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
return;
}
if(loadingPlayers.contains(event.getName())) {
if(!abstractArena.getPhase().canJoin()) {
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
event.setKickMessage(CoreLang.ARENA_HAS_STARTED.getDefaultMessage());
}
loadingPlayers.remove(event.getName());
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerPrepare(PlayerLoginPrepareEvent event) {
if(!enabled) {
return;
}
event.getPlayer().setScoreboardToShow(CoreScoreboardType.NONE);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPrepare2(PlayerLoginPrepareEvent event) {
if(!enabled) {
return;
}
if(abstractArena.getPhase().canJoin()) {
abstractArena.addPlayer(event.getPlayer().getPlayer());
} else if(abstractArena.canJoinArena()){
abstractArena.addSpectator(event.getPlayer().getPlayer());
}
}
@EventHandler
public void onArenaPhaseChange(ArenaPhaseChangeEvent event) {
if(!enabled) {
return;
}
eventRegistry.callEvent(new BungeeStateUpdate(getMOTD()));
}
@EventHandler
public void onPing(ServerListPingEvent event) {
if(!enabled) {
return;
}
event.setMotd(getMOTD());
}
@EventHandler
public void onArenaLeave(ArenaPreLeaveEvent event) {
if(!enabled) {
return;
}
if(changingArena) {
return;
}
bungeeHandler.sendPlayer(event.getPlayer(), lobbyServer);
event.setCancelled(true);
}
@EventHandler
public void onPreRegen(ArenaPreRegenEvent event) {
if(!enabled) {
return;
}
if(changingArena) {
return;
}
event.setCancelled(true);
if(Bukkit.getOnlinePlayers().isEmpty()) {
scheduleRegen();
} else for (Player player : Bukkit.getOnlinePlayers()) {
bungeeHandler.sendPlayer(player, lobbyServer);
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
if(!enabled) {
return;
}
if(Bukkit.getOnlinePlayers().size() > 1) {
return;
}
if(restartASAP) {
Bukkit.shutdown();
return;
}
if(abstractArena.getPhase() instanceof EndPhase) {
scheduleRegen();
}
}
private void scheduleRegen() {
pluginScheduler.runTaskLater(() -> {
// unload the world
abstractArena.getArenaWorld().unloadWorld(false);
pluginScheduler.runTaskLater(() -> {
abstractArena.getArenaWorld().deleteWorld();
abstractArena.destroy();
if(restartAfter != -1 && arenasPlayed >= restartAfter) {
Bukkit.shutdown();
}
if(!loadRandomArena()) {
Bukkit.getServer().shutdown();
}
}, 10L);
}, 1L);
}
void changeArena(String arena) {
changingArena = true;
abstractArena.destroy();
loadArena(arena);
Bukkit.getOnlinePlayers().forEach(player -> abstractArena.addPlayer(player));
changingArena = false;
}
private String getMOTD() {
String motd = motdStatus.get(abstractArena.getArenaState().getName().toLowerCase());
if(motd == null || motd.isEmpty()) {
Utils.printError("Could not find MOTD for state " + abstractArena.getArenaState().getName().toLowerCase());
return null;
}
return placeHolderManager.replace(abstractArena, motd);
}
public Set<String> getEnabledArenas() {
return enabledArenas;
}
public boolean isEnabled() {
return enabled;
}
public void restartASAP() {
this.restartAfter = -1;
this.restartASAP = true;
}
public Map<String, AbstractArena> getPlayerQueue() {
return playerQueue;
}
} | 11,029 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AdvancedBungeeMode.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/bungee/AdvancedBungeeMode.java | package me.patothebest.gamecore.arena.modes.bungee;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.inject.Inject;
import me.patothebest.gamecore.api.BungeeStateUpdate;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.arena.ArenaPreRegenEvent;
import me.patothebest.gamecore.event.player.ArenaPreLeaveEvent;
import me.patothebest.gamecore.event.player.GameJoinEvent;
import me.patothebest.gamecore.event.player.LobbyJoinEvent;
import me.patothebest.gamecore.event.player.PlayerLoginPrepareEvent;
import me.patothebest.gamecore.file.CoreConfig;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ListenerModule;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.permission.Permission;
import me.patothebest.gamecore.phase.phases.EndPhase;
import me.patothebest.gamecore.placeholder.PlaceHolderManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.scoreboard.CoreScoreboardType;
import me.patothebest.gamecore.util.PlayerList;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.ServerListPingEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("Duplicates")
@ModuleName("Advance Bungee Mode")
public class AdvancedBungeeMode implements ActivableModule, ListenerModule {
private final PluginScheduler pluginScheduler;
private final CoreConfig coreConfig;
private final ArenaManager arenaManager;
private final BungeeHandler bungeeHandler;
private final EventRegistry eventRegistry;
private final PlaceHolderManager placeHolderManager;
private final Map<String, String> motdStatus = new HashMap<>();
private final Map<String, AbstractArena> playerArenaMap = new ConcurrentHashMap<>();
private final Cache<String, AbstractArena> playerCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build();
private final Cache<String, AbstractArena> playerCacheStep2 = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build();
private final Set<String> enabledArenas = new HashSet<>();
private final List<String> loadingPlayers = new ArrayList<>();
private final Map<String, AbstractArena> arenas = new HashMap<>();
private String repo;
private boolean enabled;
private boolean changingArena;
private boolean restartASAP = false;
private int restartAfter;
private int arenasPlayed;
private int concurrentArenas;
private String lobbyServer;
@Inject private AdvancedBungeeMode(PluginScheduler pluginScheduler, CoreConfig coreConfig, ArenaManager arenaManager, BungeeHandler bungeeHandler, EventRegistry eventRegistry, PlaceHolderManager placeHolderManager) {
this.pluginScheduler = pluginScheduler;
this.coreConfig = coreConfig;
this.arenaManager = arenaManager;
this.bungeeHandler = bungeeHandler;
this.eventRegistry = eventRegistry;
this.placeHolderManager = placeHolderManager;
}
@SuppressWarnings("ConstantConditions")
@Override
public void onPreEnable() {
ConfigurationSection bungeeSection = coreConfig.getConfigurationSection("advanced-bungee-mode");
if(bungeeSection == null) {
return;
}
if(!bungeeSection.getBoolean("enabled")) {
return;
}
concurrentArenas = bungeeSection.getInt("concurrent-arenas");
if(ArenaManager.ARENA_DIRECTORY.listFiles() == null) {
Utils.printError("Could not find arena directory!");
return;
}
for (File file : ArenaManager.ARENA_DIRECTORY.listFiles()) {
enabledArenas.add(file.getName().replace(".yml", ""));
}
for (int i = 0; i < concurrentArenas; i++) {
if(loadRandomArena() == null) {
return;
}
}
bungeeSection.getConfigurationSection("motd").getValues(true).forEach((status, motd) -> motdStatus.put(status, (String) motd));
lobbyServer = bungeeSection.getString("leave-server");
restartAfter = bungeeSection.getInt("restart-after");
repo = bungeeSection.getString("repo");
enabled = true;
arenaManager.setLoadMaps(false);
}
private AbstractArena loadRandomArena() {
if(repo != null && !repo.isEmpty()) {
try {
String list = Utils.urlToString(new URL(repo), StandardCharsets.UTF_8);
String[] split = list.split("\n");
ArrayList<String> arenaList = new ArrayList<>(enabledArenas);
arenaList.retainAll(Arrays.asList(split));
return loadArena(Utils.getRandomElementFromCollection(arenaList));
} catch (IOException e) {
e.printStackTrace();
return loadArena(Utils.getRandomElementFromCollection(enabledArenas));
}
} else {
return loadArena(Utils.getRandomElementFromCollection(enabledArenas));
}
}
private AbstractArena loadArena(String name) {
AbstractArena abstractArena = arenaManager.loadArena(name, name + "-" + arenasPlayed);
if(abstractArena == null) {
Utils.printError("Could not find an arena for bungee-mode!");
} else {
arenas.put(name + "-" + arenasPlayed, abstractArena);
}
arenasPlayed++;
return abstractArena;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
if(!enabled) {
return;
}
if(event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
return;
}
AbstractArena abstractArena = playerCache.getIfPresent(event.getName());
if(abstractArena == null) {
// event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
// event.setKickMessage(CoreLang.ARENA_DOES_NOT_EXIST.getDefaultMessage());
return;
}
playerCache.invalidate(event.getName());
playerCacheStep2.put(event.getName(), abstractArena);
if(abstractArena.canJoinArena()) {
if(abstractArena.getPhase().canJoin()) {
loadingPlayers.add(event.getName());
}
return;
}
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
event.setKickMessage(CoreLang.ARENA_IS_RESTARTING.getDefaultMessage());
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPreLogin2(AsyncPlayerPreLoginEvent event) {
if(!enabled) {
return;
}
if(event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
return;
}
AbstractArena abstractArena = playerCacheStep2.getIfPresent(event.getName());
if(abstractArena == null) {
// event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
// event.setKickMessage(CoreLang.ARENA_DOES_NOT_EXIST.getDefaultMessage());
return;
}
if(loadingPlayers.contains(event.getName())) {
if(!abstractArena.getPhase().canJoin()) {
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
event.setKickMessage(CoreLang.ARENA_HAS_STARTED.getDefaultMessage());
}
loadingPlayers.remove(event.getName());
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PlayerLoginEvent event) {
if(!enabled) {
return;
}
AbstractArena abstractArena = playerCacheStep2.getIfPresent(event.getPlayer().getName());
if(abstractArena != null) {
return;
}
if(!event.getPlayer().hasPermission(Permission.ADMIN.getBukkitPermission())) {
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
event.setKickMessage(CoreLang.ARENA_DOES_NOT_EXIST.getDefaultMessage());
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerPrepare(PlayerLoginPrepareEvent event) {
if(!enabled) {
return;
}
event.getPlayer().setScoreboardToShow(CoreScoreboardType.NONE);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPrepare2(PlayerLoginPrepareEvent event) {
if(!enabled) {
return;
}
AbstractArena abstractArena = playerCacheStep2.getIfPresent(event.getPlayer().getName());
playerCacheStep2.invalidate(event.getPlayer().getName());
if(abstractArena == null) {
return;
}
playerArenaMap.put(event.getPlayer().getName(), abstractArena);
if(abstractArena.getPhase().canJoin()) {
abstractArena.addPlayer(event.getPlayer().getPlayer());
} else if(abstractArena.canJoinArena()){
abstractArena.addSpectator(event.getPlayer().getPlayer());
}
}
@EventHandler
public void onArenaPhaseChange(ArenaPhaseChangeEvent event) {
if(!enabled) {
return;
}
eventRegistry.callEvent(new BungeeStateUpdate(getMOTD()));
}
@EventHandler
public void onPing(ServerListPingEvent event) {
if(!enabled) {
return;
}
event.setMotd(getMOTD());
}
@EventHandler
public void onArenaLeave(ArenaPreLeaveEvent event) {
if(!enabled) {
return;
}
if(changingArena) {
return;
}
bungeeHandler.sendPlayer(event.getPlayer(), lobbyServer);
event.setCancelled(true);
}
@EventHandler
public void onLobbyJoin(LobbyJoinEvent event) {
if(!enabled) {
return;
}
if(!playerArenaMap.containsKey(event.getPlayer().getName())) {
playerArenaMap.put(event.getPlayer().getName(), event.getArena());
}
}
@EventHandler
public void onGameJoin(GameJoinEvent event) {
if(!enabled) {
return;
}
if(!playerArenaMap.containsKey(event.getPlayer().getName())) {
playerArenaMap.put(event.getPlayer().getName(), event.getArena());
}
}
@EventHandler
public void onPreRegen(ArenaPreRegenEvent event) {
if(!enabled) {
return;
}
if(changingArena) {
return;
}
event.setCancelled(true);
if(event.getArena().getPlayers().isEmpty() && event.getArena().getSpectators().isEmpty()) {
scheduleRegen(event.getArena());
} else {
for (Player player : event.getArena().getPlayers()) {
bungeeHandler.sendPlayer(player, lobbyServer);
}
for (Player player : event.getArena().getSpectators()) {
bungeeHandler.sendPlayer(player, lobbyServer);
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
if(!enabled) {
return;
}
AbstractArena abstractArena = playerArenaMap.remove(event.getPlayer().getName());
if(abstractArena.getPlayers().size() > 1 || abstractArena.getSpectators().size() > 1) {
return;
}
if(restartASAP && Bukkit.getOnlinePlayers().size() <= 1) {
Bukkit.shutdown();
return;
}
if(abstractArena.getPhase() instanceof EndPhase) {
scheduleRegen(abstractArena);
}
}
private void scheduleRegen(AbstractArena abstractArena) {
pluginScheduler.runTaskLater(() -> {
// unload the world
abstractArena.getArenaWorld().unloadWorld(false);
pluginScheduler.runTaskLater(() -> {
abstractArena.getArenaWorld().deleteWorld();
abstractArena.destroy();
arenas.values().remove(abstractArena);
if((restartAfter != -1 && arenasPlayed >= restartAfter) || restartASAP) {
if(arenas.isEmpty()) {
Bukkit.shutdown();
}
return;
}
if(loadRandomArena() == null) {
Bukkit.getServer().shutdown();
}
}, 10L);
}, 1L);
}
void changeArena(String oldArenaName, String newArenaName) {
changingArena = true;
AbstractArena oldArena = arenas.get(oldArenaName);
PlayerList playersToMove = oldArena.getPlayers();
oldArena.destroy();
arenas.values().remove(oldArena);
AbstractArena newArena = loadArena(newArenaName);
playersToMove.forEach(newArena::addPlayer);
changingArena = false;
}
private String getMOTD() {
if(arenas.isEmpty()) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (AbstractArena abstractArena : arenas.values()) {
stringBuilder.append(getMOTD(abstractArena)).append("//");
}
return stringBuilder.substring(0, stringBuilder.length()-2);
}
private String getMOTD(AbstractArena abstractArena) {
String motd = motdStatus.get(abstractArena.getArenaState().getName().toLowerCase());
if(motd == null || motd.isEmpty()) {
Utils.printError("Could not find MOTD for state " + abstractArena.getArenaState().getName().toLowerCase());
return null;
}
return placeHolderManager.replace(abstractArena, motd);
}
public Set<String> getEnabledArenas() {
return enabledArenas;
}
public boolean isEnabled() {
return enabled;
}
public void restartASAP() {
this.restartAfter = -1;
this.restartASAP = true;
for (AbstractArena abstractArena : getArenas().values()) {
if(abstractArena.getPlayers().isEmpty()) {
scheduleRegen(abstractArena);
}
}
}
public Map<String, AbstractArena> getArenas() {
return arenas;
}
public Cache<String, AbstractArena> getPlayerCache() {
return playerCache;
}
} | 15,182 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
SlimeRandomArenaGroup.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/slimerandom/SlimeRandomArenaGroup.java | package me.patothebest.gamecore.arena.modes.slimerandom;
import com.google.inject.Provider;
import com.grinderwolf.swm.api.loaders.SlimeLoader;
import com.grinderwolf.swm.api.world.properties.SlimePropertyMap;
import com.grinderwolf.swm.internal.com.flowpowered.nbt.CompoundMap;
import com.grinderwolf.swm.internal.com.flowpowered.nbt.CompoundTag;
import com.grinderwolf.swm.nms.CraftSlimeWorld;
import com.grinderwolf.swm.plugin.SWMPlugin;
import me.patothebest.gamecore.arena.modes.random.RandomArenaGroup;
import me.patothebest.gamecore.pluginhooks.hooks.SlimeWorldManagerHook;
import me.patothebest.gamecore.PluginConfig;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.pluginhooks.PluginHookManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.sign.SignManager;
import me.patothebest.gamecore.world.WorldHandler;
import me.patothebest.gamecore.world.infinity.InfinityWorld;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;
public class SlimeRandomArenaGroup extends RandomArenaGroup {
private final String worldName;
private final World world;
private final SlimeWorldManagerHook hook;
private final SlimeLoader slimeLoader;
private final CraftSlimeWorld slimeWorld;
int chunkXDirection = 1;
int chunkZDirection = 0;
int segmentLength = 1;
int chunkX = 0;
int chunkZ = 0;
int segmentPassed = 0;
public SlimeRandomArenaGroup(String groupName, Logger logger, PluginHookManager pluginHookManager, PluginScheduler pluginScheduler, SignManager signManager, ConfigurationSection configurationSection, ArenaManager arenaManager, Provider<WorldHandler> worldHandlerProvider, PlayerManager playerManager) {
super(groupName, logger, pluginScheduler, signManager, configurationSection, arenaManager, worldHandlerProvider, playerManager);
hook = pluginHookManager.getHook(SlimeWorldManagerHook.class);
slimeLoader = hook.getSlimeLoader();
SlimePropertyMap defaultProperties = hook.createDefaultProperties(World.Environment.NORMAL);
worldName = (PluginConfig.WORLD_PREFIX + groupName).toLowerCase();
slimeWorld = new CraftSlimeWorld(slimeLoader, worldName, new HashMap<>(), new CompoundTag("",
new CompoundMap()), new ArrayList<>(), ((SWMPlugin) hook.getSlimePlugin()).getNms().getWorldVersion(),
defaultProperties, true, false);
hook.getSlimePlugin().generateWorld(slimeWorld);
world = Bukkit.getWorld(worldName);
world.setAutoSave(true);
world.setKeepSpawnInMemory(false);
}
@Override
protected AbstractArena loadArena(String arenaName, String worldName) {
AbstractArena arena = arenaManager.loadArena(arenaName, worldName, false);
int chunkXOffset = chunkX << 6;
int chunkZOffset = chunkZ << 6;
incrementChunks();
arena.setOffset(new Vector(chunkXOffset << 4, 0, chunkZOffset << 4));
arena.setArenaWorld(new InfinityWorld(arena, slimeLoader, slimeWorld, world));
arena.setDisableSaving(true);
arena.initializeData();
return arena;
}
private void incrementChunks() {
chunkX += chunkXDirection;
chunkZ += chunkZDirection;
++segmentPassed;
if (segmentPassed == segmentLength) {
segmentPassed = 0;
// 'rotate' directions
int buffer = chunkXDirection;
chunkXDirection = -chunkZDirection;
chunkZDirection = buffer;
// increase segment length if necessary
if (chunkZDirection == 0) {
++segmentLength;
}
}
}
@Override
public void destroy() {
super.destroy();
Bukkit.unloadWorld(world, false);
}
}
| 4,096 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ChooseGroup.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/ChooseGroup.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import me.patothebest.gamecore.gui.inventory.button.SimpleButton;
import me.patothebest.gamecore.gui.inventory.page.DynamicPaginatedUI;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.gui.inventory.GUIButton;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.itemstack.Material;
import org.bukkit.entity.Player;
public class ChooseGroup extends DynamicPaginatedUI<RandomArenaGroup> {
private final RandomArenaUIFactory randomArenaUIFactory;
@Inject private ChooseGroup(CorePlugin plugin, @Assisted Player player, RandomArenaMode randomArenaMode, RandomArenaUIFactory randomArenaUIFactory) {
super(plugin, player, CoreLang.CHOOSE_GROUP, randomArenaMode::getGroups);
this.randomArenaUIFactory = randomArenaUIFactory;
build();
}
@Override
protected GUIButton createButton(RandomArenaGroup randomArenaGroup) {
return new SimpleButton(new ItemStackBuilder()
.material(Material.MAP)
.name(CoreLang.CHOOSE_GROUP_BUTTON_NAME.replace(getPlayer(), randomArenaGroup.getGroupName())),
() -> randomArenaUIFactory.createChooseMapUI(player, randomArenaGroup));
}
}
| 1,406 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RandomArenaGroup.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/RandomArenaGroup.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.Provider;
import me.patothebest.gamecore.event.player.ArenaPreJoinEvent;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.event.arena.ArenaPhaseChangeEvent;
import me.patothebest.gamecore.event.arena.ArenaPreRegenEvent;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.sign.ArenaSign;
import me.patothebest.gamecore.sign.SignManager;
import me.patothebest.gamecore.util.NameableObject;
import me.patothebest.gamecore.util.PlayerList;
import me.patothebest.gamecore.util.Utils;
import me.patothebest.gamecore.world.WorldHandler;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RandomArenaGroup implements Listener, NameableObject, Runnable {
private final Logger logger;
private final String groupName;
private final PluginScheduler pluginScheduler;
private final SignManager signManager;
protected final ArenaManager arenaManager;
private final Provider<WorldHandler> worldHandlerProvider;
private final PlayerManager playerManager;
private final Set<String> enabledArenas = new HashSet<>();
private final Set<String> allArenas = new HashSet<>();
private final Queue<String> nextMaps = new ConcurrentLinkedQueue<>();
private final Map<String, List<Player>> playerQueue = new HashMap<>();
private final PlayerList playersList = new PlayerList();
private final PlayerList toRemoveList = new PlayerList();
private final Map<String, AbstractArena> arenas = new ConcurrentHashMap<>();
private final AtomicInteger loadingArenas = new AtomicInteger(0);
private int id = 0;
private int maxArenas;
private int concurrentArenas;
protected RandomArenaGroup(String groupName, Logger logger, PluginScheduler pluginScheduler, SignManager signManager, ConfigurationSection configurationSection, ArenaManager arenaManager, Provider<WorldHandler> worldHandlerProvider, PlayerManager playerManager) {
this.groupName = groupName;
this.logger = logger;
this.pluginScheduler = pluginScheduler;
this.signManager = signManager;
this.arenaManager = arenaManager;
this.worldHandlerProvider = worldHandlerProvider;
this.playerManager = playerManager;
List<String> arenas = configurationSection.getStringList("arenas");
List<String> temp = new ArrayList<>();
if (ArenaManager.ARENA_DIRECTORY.listFiles() == null) {
return;
}
for (File file : ArenaManager.ARENA_DIRECTORY.listFiles()) {
temp.add(file.getName().replace(".yml", ""));
}
for (String arena : arenas) {
if (temp.contains(arena)) {
enabledArenas.add(arena);
allArenas.add(arena);
logger.log(Level.CONFIG, "Using arena " + arena + " for random group " + groupName);
} else {
Utils.printError("Unknown arena " + arena + " in random-arena-mode");
}
}
concurrentArenas = configurationSection.getInt("concurrent-arenas");
maxArenas = configurationSection.getInt("max-arenas", concurrentArenas);
}
public void init() {
for (int i = 0; i < concurrentArenas; i++) {
if(loadRandomArena() == null) {
return;
}
}
}
@Override
public void run() {
if (loadingArenas.get() > 0) {
loadingArenas.decrementAndGet();
loadRandomArena();
}
}
private void queueLoadRandomArena() {
if (worldHandlerProvider.get().hasAsyncSupport()) {
loadingArenas.incrementAndGet();
} else {
pluginScheduler.ensureSync(this::loadRandomArena);
}
}
private AbstractArena loadRandomArena() {
if (!nextMaps.isEmpty()) {
return loadArena(nextMaps.poll());
}
return loadArena(Utils.getRandomElementFromCollection(enabledArenas));
}
private synchronized AbstractArena loadArena(String name) {
AbstractArena abstractArena = loadArena(name, name + "-" + ++id);
if(abstractArena == null) {
Utils.printError("Could not find an arena for random-mode!");
} else {
logger.log(Level.INFO, "Loading random arena '" + name + "' with world name '" + abstractArena.getWorldName() + "'");
enabledArenas.remove(name);
if (!abstractArena.isEnabled()) {
pluginScheduler.ensureSync(abstractArena::destroy);
return loadRandomArena();
}
arenas.put(name, abstractArena);
for (ArenaSign sign : signManager.getSigns()) {
if (sign.getCurrentArena().equalsIgnoreCase(groupName)) {
sign.setCurrentArena(abstractArena.getWorldName());
break;
}
}
if (playerQueue.containsKey(name)) {
pluginScheduler.ensureSync(() -> {
List<Player> players = playerQueue.remove(name);
for (Player player : players) {
playersList.remove(player);
toRemoveList.remove(player);
if (abstractArena.isFull()) {
continue;
}
if (playerManager.getPlayer(player).isInArena()) {
playerManager.getPlayer(player).getCurrentArena().removePlayer(player);
}
abstractArena.addPlayer(player);
}
});
}
signManager.updateSigns();
}
return abstractArena;
}
protected AbstractArena loadArena(String arenaName, String worldName) {
return arenaManager.loadArena(arenaName, worldName);
}
@EventHandler
public void onPhaseChange(ArenaPhaseChangeEvent event) {
if (needsAnotherArena()) {
queueLoadRandomArena();
}
}
@EventHandler
public void onPreRegen(ArenaPreRegenEvent event) {
if (!arenas.containsKey(event.getArena().getName())) {
return;
}
event.setCancelled(true);
destroyArena(event.getArena(), false);
}
@EventHandler
public void onArenaPreJoin(ArenaPreJoinEvent event) {
if (toRemoveList.contains(event.getPlayer())) {
CoreLang.PLAYER_QUEUE_LEAVE.replaceAndSend(event.getPlayer(), removePlayer(event.getPlayer()));
return;
}
if (playersList.contains(event.getPlayer())) {
toRemoveList.add(event.getPlayer());
CoreLang.PLAYER_QUEUED.sendMessage(event.getPlayer());
event.setCancelled(true);
}
}
private boolean needsAnotherArena() {
// count loading arenas as joinable arenas
// to account for arenas that are queued to
// be loaded and joinable
int joinableArenas = loadingArenas.get();
for (AbstractArena value : arenas.values()) {
if (value.getPhase().canJoin() && !value.isFull()) {
joinableArenas++;
}
}
return joinableArenas < concurrentArenas && arenas.size() < maxArenas;
}
@EventHandler
public void onLeave(PlayerQuitEvent event) {
removePlayer(event.getPlayer());
}
private String removePlayer(Player player) {
String s = "";
for (String map : playerQueue.keySet()) {
List<Player> players = playerQueue.get(map);
if (playerQueue.get(map).contains(player) ){
s = map;
players.remove(player);
if (players.isEmpty()) {
playerQueue.remove(map);
nextMaps.remove(map);
}
}
}
toRemoveList.remove(player);
playersList.remove(player);
return s;
}
public void destroyArena(AbstractArena arena, boolean loadAnotherOverride) {
logger.log(Level.INFO, "Destroying arena " + arena.getWorldName());
for (Player player : arena.getPlayers()) {
arena.removePlayer(player);
}
for (Player player : arena.getSpectators()) {
arena.removePlayer(player);
}
pluginScheduler.runTaskLater(() -> {
// unload the world
arena.getArenaWorld().unloadWorld(false);
pluginScheduler.runTaskLaterAsynchronously(() -> {
arena.getArenaWorld().deleteWorld();
pluginScheduler.ensureSync(arena::destroy);
arenas.values().remove(arena);
enabledArenas.add(arena.getName());
arenaManager.getArenas().remove(arena.getWorldName());
removeSign(arena);
if (loadAnotherOverride || needsAnotherArena()) {
queueLoadRandomArena();
}}, 10L);
}, 1L);
}
public void destroy() {
getArenas().values().forEach(arena -> {
arena.destroy();
removeSign(arena);
});
}
private void removeSign(AbstractArena arena) {
for (ArenaSign sign : signManager.getSigns()) {
if (!sign.getArena().equalsIgnoreCase(groupName)) {
continue;
}
if (sign.getCurrentArena().equalsIgnoreCase(arena.getWorldName())) {
sign.setCurrentArena(groupName);
}
}
signManager.updateSigns();
}
public Set<String> getEnabledArenas() {
return enabledArenas;
}
public Set<String> getAllArenas() {
return allArenas;
}
public Map<String, AbstractArena> getArenas() {
return arenas;
}
public boolean isQueued(Player player) {
return playersList.contains(player);
}
public void addPlayerToQueue(Player player, String arena) {
if (isQueued(player)) {
removePlayer(player);
}
if (!nextMaps.contains(arena)) {
nextMaps.add(arena);
playerQueue.put(arena, new ArrayList<>());
}
playerQueue.get(arena).add(player);
playersList.add(player);
}
public String getGroupName() {
return groupName;
}
@Override
public String getName() {
return groupName;
}
}
| 11,219 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RandomArenaMode.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/RandomArenaMode.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.Inject;
import com.google.inject.Provider;
import me.patothebest.gamecore.PluginConfig;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.file.CoreConfig;
import me.patothebest.gamecore.logger.InjectLogger;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ListenerModule;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.modules.ReloadPriority;
import me.patothebest.gamecore.modules.ReloadableModule;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.pluginhooks.PluginHookManager;
import me.patothebest.gamecore.scheduler.PluginScheduler;
import me.patothebest.gamecore.sign.SignManager;
import me.patothebest.gamecore.util.Priority;
import me.patothebest.gamecore.util.Utils;
import me.patothebest.gamecore.world.WorldHandler;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@ReloadPriority(priority = Priority.LOW)
@ModuleName("Random Arena Mode")
public class RandomArenaMode implements ActivableModule, ListenerModule, ReloadableModule, Runnable {
private boolean enabled;
private final CoreConfig coreConfig;
private final PluginScheduler pluginScheduler;
private final SignManager signManager;
private final EventRegistry eventRegistry;
private final ArenaManager arenaManager;
private final PlayerManager playerManager;
private final Provider<WorldHandler> worldHandlerProvider;
private final List<RandomArenaGroup> groups = new ArrayList<>();
private final PluginHookManager pluginHookManager;
@InjectLogger private Logger logger;
private volatile boolean asyncEnabled;
@Inject
private RandomArenaMode(CoreConfig coreConfig, PluginScheduler pluginScheduler, SignManager signManager, EventRegistry eventRegistry, ArenaManager arenaManager, PlayerManager playerManager, Provider<WorldHandler> worldHandlerProvider, PluginHookManager pluginHookManager) {
this.coreConfig = coreConfig;
this.pluginScheduler = pluginScheduler;
this.signManager = signManager;
this.eventRegistry = eventRegistry;
this.arenaManager = arenaManager;
this.playerManager = playerManager;
this.worldHandlerProvider = worldHandlerProvider;
this.pluginHookManager = pluginHookManager;
}
@Override
public void onPreEnable() {
File[] files = new File(".").listFiles();
if (files != null) {
for (File file : files) {
if (!file.isDirectory()) {
continue;
}
if (file.getName().contains(PluginConfig.WORLD_PREFIX + "rand_") ||
file.getName().contains(PluginConfig.WORLD_PREFIX.toLowerCase() + "rand_") ||
file.getName().startsWith("temp_" + PluginConfig.WORLD_PREFIX.toLowerCase() + "")) {
Utils.deleteFolder(file);
logger.log(Level.INFO, "Deleted old temp world " + file.getName());
}
}
}
enabled = false;
ConfigurationSection randomArenaSection = coreConfig.getConfigurationSection("random-arena-mode");
if (randomArenaSection == null) {
return;
}
if (!randomArenaSection.getBoolean("enabled")) {
return;
}
if (!randomArenaSection.isSet("arena-groups")) {
return;
}
enabled = true;
arenaManager.setLoadMaps(false);
}
@Override
public void onPostEnable() {
if (!enabled) {
return;
}
ConfigurationSection randomArenaSection = coreConfig.getConfigurationSection("random-arena-mode");
for (String groupName : randomArenaSection.getConfigurationSection("arena-groups").getKeys(false)) {
RandomArenaGroup group;
//if (pluginHookManager.isHookLoaded(SlimeWorldManagerHook.class)) {
// group = new SlimeRandomArenaGroup(groupName, logger, pluginHookManager, pluginScheduler, signManager, randomArenaSection.getConfigurationSection("arena-groups." + groupName), arenaManager, worldHandlerProvider, playerManager);
//} else {
group = new RandomArenaGroup(groupName, logger, pluginScheduler, signManager, randomArenaSection.getConfigurationSection("arena-groups." + groupName), arenaManager, worldHandlerProvider, playerManager);
//}
group.init();
eventRegistry.registerListener(group);
groups.add(group);
}
if (worldHandlerProvider.get().hasAsyncSupport()) {
asyncEnabled = true;
pluginScheduler.runTaskAsynchronously(this);
}
}
@Override
public void run() {
try {
while (asyncEnabled) {
for (RandomArenaGroup group : groups) {
try {
group.run();
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not run arena queue!", e);
}
}
Thread.sleep(250);
}
} catch (InterruptedException ignored) { }
}
@Override
public void onDisable() {
for (RandomArenaGroup group : groups) {
eventRegistry.unRegisterListener(group);
group.destroy();
}
groups.clear();
asyncEnabled = false;
}
@Override
public void onReload() {
onDisable();
onPreEnable();
onPostEnable();
}
@Override
public String getReloadName() {
return "random-mode";
}
public List<RandomArenaGroup> getGroups() {
return groups;
}
} | 6,031 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ChooseMap.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/ChooseMap.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import me.patothebest.gamecore.gui.inventory.button.SimpleButton;
import me.patothebest.gamecore.gui.inventory.page.DynamicPaginatedUI;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.gui.inventory.GUIButton;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.player.PlayerManager;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class ChooseMap extends DynamicPaginatedUI<String> {
private final RandomArenaGroup randomArenaGroup;
private final PlayerManager playerManager;
@Inject private ChooseMap(CorePlugin plugin, @Assisted Player player, @Assisted RandomArenaGroup randomArenaGroup, PlayerManager playerManager) {
super(plugin, player, CoreLang.CHOOSE_MAP_UI_TITLE, randomArenaGroup::getAllArenas);
this.randomArenaGroup = randomArenaGroup;
this.playerManager = playerManager;
build();
}
@Override
protected GUIButton createButton(String mapName) {
return new SimpleButton(new ItemStackBuilder()
.material(Material.MAP)
.name(CoreLang.CHOOSE_MAP_BUTTON_NAME.replace(getPlayer(), mapName))
.lore((!randomArenaGroup.getEnabledArenas().contains(mapName) ? CoreLang.CHOOSE_MAP_BUTTON_JOIN_DESC : CoreLang.CHOOSE_MAP_BUTTON_SELECT_DESC).getMessage(getPlayer())),
() -> {
if (randomArenaGroup.getArenas().containsKey(mapName)) {
AbstractArena arena = randomArenaGroup.getArenas().get(mapName);
if(playerManager.getPlayer(player.getName()).getCurrentArena() != null) {
player.sendMessage(CoreLang.ALREADY_IN_ARENA.getMessage(player));
return;
}
if(arena.getPhase().canJoin() && !arena.isFull()) {
arena.addPlayer(player);
return;
}
}
randomArenaGroup.addPlayerToQueue(player, mapName);
CoreLang.CHOOSE_MAP_ARENA_QUEUED.sendMessage(player);
for (AbstractArena value : randomArenaGroup.getArenas().values()) {
if (value.getPlayers().size() == 0) {
randomArenaGroup.destroyArena(value, true);
CoreLang.CHOOSE_MAP_ARENA_CREATED.sendMessage(player);
return;
}
}
});
}
}
| 2,823 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RandomArenaModeModule.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/RandomArenaModeModule.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.injector.AbstractBukkitModule;
public class RandomArenaModeModule extends AbstractBukkitModule<CorePlugin> {
public RandomArenaModeModule(CorePlugin plugin) {
super(plugin);
}
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(RandomArenaUIFactory.class));
registerModule(RandomArenaMode.class);
registerModule(RandomArenaModeCommand.Parent.class);
}
}
| 626 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RandomArenaUIFactory.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/RandomArenaUIFactory.java | package me.patothebest.gamecore.arena.modes.random;
import org.bukkit.entity.Player;
public interface RandomArenaUIFactory {
ChooseGroup createChooseGroupUI(Player player);
ChooseMap createChooseMapUI(Player player, RandomArenaGroup randomArenaGroup);
}
| 267 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
RandomArenaModeCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/modes/random/RandomArenaModeCommand.java | package me.patothebest.gamecore.arena.modes.random;
import com.google.inject.Inject;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.chat.CommandPagination;
import me.patothebest.gamecore.command.BaseCommand;
import me.patothebest.gamecore.command.ChildOf;
import me.patothebest.gamecore.command.Command;
import me.patothebest.gamecore.command.CommandContext;
import me.patothebest.gamecore.command.CommandException;
import me.patothebest.gamecore.command.CommandPermissions;
import me.patothebest.gamecore.command.CommandsManager;
import me.patothebest.gamecore.command.LangDescription;
import me.patothebest.gamecore.command.NestedCommand;
import me.patothebest.gamecore.modules.ParentCommandModule;
import me.patothebest.gamecore.permission.Permission;
import me.patothebest.gamecore.util.CommandUtils;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RandomArenaModeCommand implements ParentCommandModule {
private final RandomArenaMode randomArenaMode;
private final RandomArenaUIFactory randomArenaUIFactory;
@Inject private RandomArenaModeCommand(RandomArenaMode randomArenaMode, RandomArenaUIFactory randomArenaUIFactory) {
this.randomArenaMode = randomArenaMode;
this.randomArenaUIFactory = randomArenaUIFactory;
}
@Command(
aliases = {"ui"},
max = 0,
langDescription = @LangDescription(
element = "RANDOM_ARENA_MODE_CHOOSE_GROUP_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.CHOOSE_ARENA)
public List<String> openChooseGroup(CommandContext args, CommandSender sender) throws CommandException {
Player player = CommandUtils.getPlayer(sender);
randomArenaUIFactory.createChooseGroupUI(player);
return null;
}
@Command(
aliases = {"map"},
usage = "<group>",
min = 1,
max = 1,
langDescription = @LangDescription(
element = "RANDOM_ARENA_MODE_CHOOSE_GROUP_COMMAND",
langClass = CoreLang.class
)
)
@CommandPermissions(permission = Permission.CHOOSE_ARENA)
public List<String> openChooseMap(CommandContext args, CommandSender sender) throws CommandException {
Player player = CommandUtils.getPlayer(sender);
if (args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), Utils.toList(randomArenaMode.getGroups()));
}
return null;
}
String mode = args.getString(0);
RandomArenaGroup randomArenaGroup = null;
for (RandomArenaGroup group : randomArenaMode.getGroups()) {
if (group.getName().equalsIgnoreCase(mode)) {
randomArenaGroup = group;
}
}
CommandUtils.validateNotNull(randomArenaGroup, CoreLang.RANDOM_ARENA_MODE_NOT_FOUND);
randomArenaUIFactory.createChooseGroupUI(player);
return null;
}
@ChildOf(BaseCommand.class)
public static class Parent implements ParentCommandModule {
private final CommandsManager<CommandSender> commandsManager;
@Inject
private Parent(CommandsManager<CommandSender> commandsManager) {
this.commandsManager = commandsManager;
}
@Command(
aliases = "random-arena",
langDescription = @LangDescription(
langClass = CoreLang.class,
element = "RANDOM_ARENA_MODE_COMMAND"
)
)
@NestedCommand(value = {
RandomArenaModeCommand.class,
},
defaultToBody = true
)
public void oitc(CommandContext args, CommandSender sender) throws CommandException {
new CommandPagination(commandsManager, args).display(sender);
}
}
}
| 4,123 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ChestArena.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/types/ChestArena.java | package me.patothebest.gamecore.arena.types;
import me.patothebest.gamecore.feature.features.chests.refill.ChestLocation;
import me.patothebest.gamecore.vector.ArenaLocation;
import java.util.List;
public interface ChestArena {
List<ArenaLocation> getArenaChests(ChestLocation chestLocation);
}
| 304 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
CentrableArena.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/types/CentrableArena.java | package me.patothebest.gamecore.arena.types;
import org.bukkit.Location;
public interface CentrableArena {
Location getCenterLocation();
}
| 147 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
SpawneableArena.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/types/SpawneableArena.java | package me.patothebest.gamecore.arena.types;
import me.patothebest.gamecore.vector.ArenaLocation;
import java.util.List;
public interface SpawneableArena {
List<ArenaLocation> getSpawns();
int getSpawnHeight();
}
| 227 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ArenaOption.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/ArenaOption.java | package me.patothebest.gamecore.arena.option;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.feature.AbstractFeature;
import me.patothebest.gamecore.util.NameableObject;
import me.patothebest.gamecore.util.SerializableObject;
import org.bukkit.command.CommandSender;
import java.util.Map;
public abstract class ArenaOption extends AbstractFeature implements SerializableObject, NameableObject {
public abstract void parse(Map<String, Object> data);
public abstract String getName();
public abstract ILang getDescription();
public abstract void sendDescription(CommandSender sender);
}
| 646 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
OptionCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/OptionCommand.java | package me.patothebest.gamecore.arena.option;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.arena.AbstractArena;
import me.patothebest.gamecore.arena.ArenaManager;
import me.patothebest.gamecore.arena.option.options.EnableableOption;
import me.patothebest.gamecore.arena.option.options.EnvironmentOption;
import me.patothebest.gamecore.arena.option.options.TimeOfDayOption;
import me.patothebest.gamecore.chat.CommandPagination;
import me.patothebest.gamecore.command.ChildOf;
import me.patothebest.gamecore.command.Command;
import me.patothebest.gamecore.command.CommandContext;
import me.patothebest.gamecore.command.CommandException;
import me.patothebest.gamecore.command.CommandsManager;
import me.patothebest.gamecore.command.LangDescription;
import me.patothebest.gamecore.command.NestedCommand;
import me.patothebest.gamecore.commands.setup.SetupCommand;
import me.patothebest.gamecore.modules.RegisteredCommandModule;
import me.patothebest.gamecore.util.CommandUtils;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import java.util.List;
import java.util.stream.Collectors;
public class OptionCommand {
private final ArenaManager arenaManager;
@Inject private OptionCommand(ArenaManager arenaManager) {
this.arenaManager = arenaManager;
}
@ChildOf(SetupCommand.class)
public static class Parent implements RegisteredCommandModule {
private final CommandsManager<CommandSender> commandsManager;
@Inject
private Parent(CommandsManager<CommandSender> commandsManager) {
this.commandsManager = commandsManager;
}
@Command(
aliases = {"option", "options"},
langDescription = @LangDescription(
element = "OPTION_COMMAND_DESC",
langClass = CoreLang.class
)
)
@NestedCommand(value = OptionCommand.class)
public void shop(CommandContext args, CommandSender sender) throws CommandException {
new CommandPagination(commandsManager, args).display(sender);
}
}
@Command(
aliases = {"list"},
usage = "<arena>",
min = 1,
max = 1,
langDescription = @LangDescription(
element = "OPTION_LIST_COMMAND",
langClass = CoreLang.class
)
)
public List<String> list(CommandContext args, CommandSender sender) throws CommandException {
if(args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), arenaManager);
}
return null;
}
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
for (ArenaOption arenaOption : arena.getArenaOptions()) {
if (!(arenaOption instanceof EnableableOption)) {
sender.sendMessage("");
arenaOption.sendDescription(sender);
}
}
for (ArenaOption arenaOption : arena.getArenaOptions()) {
if (arenaOption instanceof EnableableOption) {
sender.sendMessage("");
arenaOption.sendDescription(sender);
}
}
return null;
}
@Command(
aliases = {"enable"},
usage = "<arena> <option>",
min = 2,
max = 2,
langDescription = @LangDescription(
element = "OPTION_ENABLE_COMMAND",
langClass = CoreLang.class
)
)
public List<String> enable(CommandContext args, CommandSender sender) throws CommandException {
if(args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), arenaManager);
} else if (args.getSuggestionContext().getIndex() == 1) {
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
return CommandUtils.complete(args.getString(1),
arena.getArenaOptions()
.stream()
.filter(arenaOption -> arenaOption instanceof EnableableOption)
.map(ArenaOption::getName)
.collect(Collectors.toList()));
}
return null;
}
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
String optionName = args.getString(1);
ArenaOption arenaOption = arena.getArenaOptions()
.stream()
.filter(arenaOptionL -> arenaOptionL.getName().equalsIgnoreCase(optionName))
.findFirst().orElse(null);
CommandUtils.validateNotNull(arenaOption, CoreLang.OPTION_NOT_FOUND);
CommandUtils.validateTrue(arenaOption instanceof EnableableOption, CoreLang.OPTION_CANT_BE_ENABLED);
((EnableableOption)arenaOption).setEnabled(true);
CoreLang.OPTION_ENABLED.replaceAndSend(sender, optionName, arena.getName());
return null;
}
@Command(
aliases = {"disable"},
usage = "<arena> <option>",
min = 2,
max = 2,
langDescription = @LangDescription(
element = "OPTION_DISABLE_COMMAND",
langClass = CoreLang.class
)
)
public List<String> disable(CommandContext args, CommandSender sender) throws CommandException {
if(args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), arenaManager);
} else if (args.getSuggestionContext().getIndex() == 1) {
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
return CommandUtils.complete(args.getString(1),
arena.getArenaOptions()
.stream()
.filter(arenaOption -> arenaOption instanceof EnableableOption)
.map(ArenaOption::getName)
.collect(Collectors.toList()));
}
return null;
}
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
String optionName = args.getString(1);
ArenaOption arenaOption = arena.getArenaOptions()
.stream()
.filter(arenaOptionL -> arenaOptionL.getName().equalsIgnoreCase(optionName))
.findFirst().orElse(null);
CommandUtils.validateNotNull(arenaOption, CoreLang.OPTION_NOT_FOUND);
CommandUtils.validateTrue(arenaOption instanceof EnableableOption, CoreLang.OPTION_CANT_BE_ENABLED);
((EnableableOption)arenaOption).setEnabled(false);
CoreLang.OPTION_DISABLED.replaceAndSend(sender, optionName, arena.getName());
return null;
}
@Command(
aliases = {"settime"},
usage = "<arena> <time>",
min = 2,
max = 2,
langDescription = @LangDescription(
element = "OPTION_SETTIME_COMMAND",
langClass = CoreLang.class
)
)
public List<String> settime(CommandContext args, CommandSender sender) throws CommandException {
if(args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), arenaManager);
} else if (args.getSuggestionContext().getIndex() == 1) {
return CommandUtils.complete(args.getString(1), TimeOfDayOption.Time.values());
}
return null;
}
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
TimeOfDayOption.Time time = CommandUtils.getEnumValueFromString(TimeOfDayOption.Time.class, args.getString(1), CoreLang.OPTION_TIME_INVALID);
arena.getOption(TimeOfDayOption.class).setTime(time);
arena.getWorld().setTime(time.getTick());
CoreLang.OPTION_TIME_CHANGED.replaceAndSend(sender, Utils.capitalizeFirstLetter(time.name()));
return null;
}
@Command(
aliases = {"setenvironment"},
usage = "<arena> <envirnonment>",
min = 2,
max = 2,
langDescription = @LangDescription(
element = "OPTION_SETENVIRONMENT_COMMAND",
langClass = CoreLang.class
)
)
public List<String> setenvironment(CommandContext args, CommandSender sender) throws CommandException {
if(args.getSuggestionContext() != null) {
if (args.getSuggestionContext().getIndex() == 0) {
return CommandUtils.complete(args.getString(0), arenaManager);
} else if (args.getSuggestionContext().getIndex() == 1) {
return CommandUtils.complete(args.getString(1), World.Environment.values());
}
return null;
}
AbstractArena arena = CommandUtils.getArena(args, 0, arenaManager);
World.Environment environment = CommandUtils.getEnumValueFromString(World.Environment.class, args.getString(1), CoreLang.OPTION_TIME_INVALID);
arena.getOption(EnvironmentOption.class).setEnvironment(environment);
CoreLang.OPTION_ENVIRONMENT_CHANGING.sendMessage(sender);
arenaManager.reloadArena(arena);
CoreLang.OPTION_ENVIRONMENT_CHANGED.replaceAndSend(sender, Utils.capitalizeFirstLetter(environment.name()));
return null;
}
}
| 9,848 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
TNTExplosionOption.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/options/TNTExplosionOption.java | package me.patothebest.gamecore.arena.option.options;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityExplodeEvent;
public class TNTExplosionOption extends EnableableOption {
public TNTExplosionOption() {
setEnabled(true);
}
@EventHandler
public void onExplode(EntityExplodeEvent event) {
if(isEnabled()) {
return;
}
if (event.getEntityType() != EntityType.PRIMED_TNT) {
return;
}
if (!isEventInArena(event)) {
return;
}
event.blockList().removeIf(block -> block.getType() != Material.TNT);
}
@Override
public String getName() {
return "tnt-explosions";
}
@Override
public ILang getDescription() {
return CoreLang.OPTION_TNT_EXPLOSIONS;
}
}
| 1,001 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
TimeOfDayOption.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/options/TimeOfDayOption.java | package me.patothebest.gamecore.arena.option.options;
import me.patothebest.gamecore.arena.option.ArenaOption;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.command.CommandSender;
import java.util.Map;
public class TimeOfDayOption extends ArenaOption {
private Time time = Time.NOON;
@Override
public void parse(Map<String, Object> data) {
if (data.containsKey("time")) {
time = Utils.getEnumValueFromString(Time.class, (String) data.get("time"), Time.NOON);
}
}
@Override
public String getName() {
return "time";
}
@Override
public ILang getDescription() {
return CoreLang.OPTION_TIME_DESC;
}
@Override
public void sendDescription(CommandSender sender) {
CoreLang.OPTION_TIME.replaceAndSend(sender, Utils.capitalizeFirstLetter(time.name()));
CoreLang.OPTION_TIME_DESC.sendMessage(sender);
CoreLang.OPTION_TIME_LIST.sendMessage(sender);
CoreLang.OPTION_TIME_COMMAND.sendMessage(sender);
}
@Override
public void serialize(Map<String, Object> data) {
data.put("time", time.name());
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
public enum Time {
SUNRISE(23000),
DAY(1000),
NOON(6000),
SUNSET(12000),
NIGHT(13000),
MIDNIGHT(18000);
private final int tick;
Time(int ticks) {
this.tick = ticks;
}
public int getTick() {
return tick;
}
}
}
| 1,714 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
EnableableOption.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/options/EnableableOption.java | package me.patothebest.gamecore.arena.option.options;
import me.patothebest.gamecore.arena.option.ArenaOption;
import me.patothebest.gamecore.lang.CoreLang;
import org.bukkit.command.CommandSender;
import java.util.Map;
public abstract class EnableableOption extends ArenaOption {
private boolean enabled;
public void parse(Map<String, Object> data) {
if (data.containsKey(getName())) {
enabled = (boolean) data.get(getName());
}
}
@Override
public void serialize(Map<String, Object> data) {
data.put(getName(), enabled);
}
@Override
public void sendDescription(CommandSender sender) {
CoreLang.OPTION_ENABLEABLE.replaceAndSend(sender, getName(), (enabled) ? CoreLang.GUI_ENABLED : CoreLang.GUI_DISABLED);
getDescription().sendMessage(sender);
CoreLang.OPTION_ENABLEABLE_COMMAND.replaceAndSend(sender, getName());
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
}
| 1,071 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
EnvironmentOption.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/arena/option/options/EnvironmentOption.java | package me.patothebest.gamecore.arena.option.options;
import me.patothebest.gamecore.arena.option.ArenaOption;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.lang.interfaces.ILang;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.util.Map;
public class EnvironmentOption extends ArenaOption {
private World.Environment environment = World.Environment.NORMAL;
@Override
public void parse(Map<String, Object> data) {
if (data.containsKey("environment")) {
environment = Utils.getEnumValueFromString(World.Environment.class, (String) data.get("environment"), World.Environment.NORMAL);
}
}
@Override
public String getName() {
return "environment";
}
@Override
public ILang getDescription() {
return CoreLang.OPTION_ENVIRONMENT_DESC;
}
@Override
public void sendDescription(CommandSender sender) {
CoreLang.OPTION_ENVIRONMENT.replaceAndSend(sender, Utils.capitalizeFirstLetter(environment.name()));
CoreLang.OPTION_ENVIRONMENT_DESC.sendMessage(sender);
CoreLang.OPTION_ENVIRONMENT_LIST.sendMessage(sender);
CoreLang.OPTION_ENVIRONMENT_COMMAND.sendMessage(sender);
}
@Override
public void serialize(Map<String, Object> data) {
data.put("environment", environment.name());
}
public World.Environment getEnvironment() {
return environment;
}
public void setEnvironment(World.Environment environment) {
this.environment = environment;
}
}
| 1,625 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestType.java | package me.patothebest.gamecore.quests;
import me.patothebest.gamecore.util.NameableObject;
import org.bukkit.event.Listener;
public interface QuestType extends NameableObject, Listener {
}
| 192 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsStatus.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestsStatus.java | package me.patothebest.gamecore.quests;
public enum QuestsStatus {
IN_PROGRESS(0),
COMPLETED(1),
FAILED(2);
private final int statusCode;
QuestsStatus(int statusCode) {
this.statusCode = statusCode;
}
public static QuestsStatus fromCode(int code) {
return values()[code];
}
public int getStatusCode() {
return statusCode;
}
}
| 396 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsCommand.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestsCommand.java | package me.patothebest.gamecore.quests;
import com.google.inject.Inject;
import me.patothebest.gamecore.command.*;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.modules.RegisteredCommandModule;
import me.patothebest.gamecore.quests.ui.QuestGUIFactory;
import me.patothebest.gamecore.util.CommandUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
@ChildOf(BaseCommand.class)
public class QuestsCommand implements RegisteredCommandModule {
private final QuestGUIFactory questGUIFactory;
@Inject private QuestsCommand(QuestGUIFactory questGUIFactory) {
this.questGUIFactory = questGUIFactory;
}
@Command(
aliases = {"quests"},
langDescription = @LangDescription(
element = "QUESTS_COMMAND",
langClass = CoreLang.class
)
)
public void quests(CommandContext args, CommandSender sender) throws CommandException {
Player player = CommandUtils.getPlayer(sender);
questGUIFactory.createQuestGUI(player);
}
}
| 1,119 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestFile.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestFile.java | package me.patothebest.gamecore.quests;
import com.google.inject.Inject;
import me.patothebest.gamecore.file.ReadOnlyFile;
import me.patothebest.gamecore.modules.Module;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.plugin.Plugin;
import java.io.BufferedWriter;
import java.io.IOException;
public class QuestFile extends ReadOnlyFile implements Module {
private final Plugin plugin;
@Inject private QuestFile(Plugin plugin) {
super("quests");
this.plugin = plugin;
this.header = "Quests File";
load();
}
@Override
protected void writeFile(BufferedWriter writer) throws IOException {
super.writeFile(writer);
Utils.writeFileToWriter(writer, plugin.getResource("quests.yml"));
}
}
| 773 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Quest.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/Quest.java | package me.patothebest.gamecore.quests;
import me.patothebest.gamecore.file.ParserException;
import me.patothebest.gamecore.util.Utils;
import java.util.Map;
public class Quest {
private final String name;
private final String displayName;
private final QuestType questType;
private final int goal;
private final long duration;
private final long cooldown;
// only two types of rewards
private final int xpReward;
private final int moneyReward;
public Quest(QuestManager questManager, String name, Map<String, Object> questData) {
this.name = name;
this.displayName = (String) questData.get("display-name");
this.goal = (int) questData.get("goal");
this.questType = questManager.getQuestType((String) questData.get("type"));
this.duration = Utils.dateStringToMillis((String) questData.get("duration"));
this.cooldown = Utils.dateStringToMillis((String) questData.get("cooldown"));
this.xpReward = (int) questData.getOrDefault("xp-reward", 0);
this.moneyReward = (int) questData.getOrDefault("money-reward", 0);
if (this.questType == null) {
throw new ParserException("Invalid quest-type: " + questData.get("type"));
}
}
public String getName() {
return name;
}
public QuestType getQuestType() {
return questType;
}
public int getGoal() {
return goal;
}
public long getDuration() {
return duration;
}
public long getCooldown() {
return cooldown;
}
public int getXpReward() {
return xpReward;
}
public int getMoneyReward() {
return moneyReward;
}
public String getDisplayName() {
return displayName;
}
}
| 1,781 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestManager.java | package me.patothebest.gamecore.quests;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.file.ParserException;
import me.patothebest.gamecore.logger.InjectLogger;
import me.patothebest.gamecore.logger.Logger;
import me.patothebest.gamecore.modules.ActivableModule;
import me.patothebest.gamecore.modules.ModuleName;
import me.patothebest.gamecore.modules.ReloadableModule;
import org.bukkit.configuration.ConfigurationSection;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@Singleton
@ModuleName("Quest Manager")
public class QuestManager implements ActivableModule, ReloadableModule {
private final Map<String, Quest> questMap = new HashMap<>();
private final QuestFile questFile;
private final Set<QuestType> questTypes;
private final EventRegistry eventRegistry;
@InjectLogger private Logger logger;
@Inject private QuestManager(QuestFile questFile, Set<QuestType> questTypes, EventRegistry eventRegistry) {
this.questFile = questFile;
this.questTypes = questTypes;
this.eventRegistry = eventRegistry;
}
@Override
public void onPostEnable() {
questMap.clear();
ConfigurationSection questSection = questFile.getConfigurationSection("quests");
if (questSection == null) {
logger.severe("Quest configurations section is null!");
return;
}
Set<String> questKeys = questSection.getKeys(false);
for (String questConfigName : questKeys) {
try {
Map<String, Object> data = Objects.requireNonNull(questSection.getConfigurationSection(questConfigName)).getValues(true);
Quest quest = new Quest(this, questConfigName, data);
this.questMap.put(questConfigName, quest);
logger.config("Loaded quest {0} ({1})", quest.getDisplayName(), questConfigName);
} catch (ParserException e) {
logger.severe("Could not parse quest " + questConfigName);
logger.severe(e.getMessage());
}
}
for (QuestType questType : questTypes) {
logger.config("Registering quest type {0}", questType.getName());
eventRegistry.registerListener(questType);
}
}
@Override
public void onDisable() {
for (QuestType questType : questTypes) {
eventRegistry.unRegisterListener(questType);
}
}
@Override
public void onReload() {
onDisable();
onPostEnable();
}
@Override
public String getReloadName() {
return "quest-manager";
}
public @Nullable Quest getQuest(String name) {
return questMap.get(name);
}
public @Nullable QuestType getQuestType(String name) {
for (QuestType questType : questTypes) {
if (questType.getName().equalsIgnoreCase(name)) {
return questType;
}
}
return null;
}
public Map<String, Quest> getQuestMap() {
return questMap;
}
}
| 3,213 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
AbstractQuestType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/AbstractQuestType.java | package me.patothebest.gamecore.quests;
import com.google.inject.Inject;
import me.patothebest.gamecore.event.EventRegistry;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.PlayerManager;
import java.util.Set;
public abstract class AbstractQuestType implements QuestType {
@Inject protected PlayerManager playerManager;
@Inject protected EventRegistry eventRegistry;
protected void updateProgress(CorePlayer player, int amount) {
Set<ActiveQuest> activeQuests = player.getActiveQuests(this);
for (ActiveQuest activeQuest : activeQuests) {
if (activeQuest.getQuestsStatus() == QuestsStatus.IN_PROGRESS) {
activeQuest.addProgress(amount);
if (activeQuest.getProgress() >= activeQuest.getQuest().getGoal()) {
CoreLang.LINE_SEPARATOR.sendMessage(player);
player.sendMessage("");
CoreLang.QUEST_COMPLETED.replaceAndSend(player, activeQuest.getQuest().getDisplayName());
player.sendMessage("");
player.addExperience(activeQuest.getQuest().getXpReward());
player.giveMoney(activeQuest.getQuest().getMoneyReward());
activeQuest.setCompleted();
player.sendMessage("");
CoreLang.LINE_SEPARATOR.sendMessage(player);
}
}
}
}
}
| 1,498 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
ActiveQuest.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/ActiveQuest.java | package me.patothebest.gamecore.quests;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.modifiers.QuestModifier;
public class ActiveQuest {
private final IPlayer player;
private final Quest quest;
private final long startDate;
private int entryId;
private int progress;
private QuestsStatus questsStatus;
public ActiveQuest(IPlayer player, Quest quest, int entryId, long startDate, int progress, QuestsStatus questsStatus) {
this.player = player;
this.quest = quest;
this.entryId = entryId;
this.startDate = startDate;
this.progress = progress;
this.questsStatus = questsStatus;
}
public void setEntryId(int entryId) {
this.entryId = entryId;
}
public IPlayer getPlayer() {
return player;
}
public Quest getQuest() {
return quest;
}
public long getStartDate() {
return startDate;
}
public int getProgress() {
return progress;
}
public QuestsStatus getQuestsStatus() {
return questsStatus;
}
public int getEntryId() {
return entryId;
}
public void addProgress(int progress) {
this.progress += progress;
player.notifyObservers(QuestModifier.UPDATE_PROGRESS, this, progress);
}
public void setCompleted() {
this.questsStatus = QuestsStatus.COMPLETED;
player.notifyObservers(QuestModifier.UPDATE_STATUS, this);
}
public void setFailed() {
this.questsStatus = QuestsStatus.FAILED;
player.notifyObservers(QuestModifier.UPDATE_STATUS, this);
}
public long getDeadline() {
return this.startDate + quest.getCooldown();
}
public boolean hasExpired() {
return getDeadline() <= System.currentTimeMillis();
}
@Override
public String toString() {
return "ActiveQuest{" +
"player=" + player +
", quest=" + quest +
", startDate=" + startDate +
", entryId=" + entryId +
", progress=" + progress +
", questsStatus=" + questsStatus +
'}';
}
}
| 2,206 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsModule.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/QuestsModule.java | package me.patothebest.gamecore.quests;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.multibindings.Multibinder;
import me.patothebest.gamecore.CorePlugin;
import me.patothebest.gamecore.quests.entities.QuestsFlatFileEntity;
import me.patothebest.gamecore.quests.entities.QuestsSQLEntity;
import me.patothebest.gamecore.quests.types.KillPlayersQuestType;
import me.patothebest.gamecore.quests.types.WinGameQuestType;
import me.patothebest.gamecore.quests.ui.QuestGUIFactory;
import me.patothebest.gamecore.storage.StorageModule;
import me.patothebest.gamecore.storage.flatfile.FlatFileEntity;
import me.patothebest.gamecore.storage.mysql.MySQLEntity;
public class QuestsModule extends StorageModule {
public QuestsModule(CorePlugin plugin) {
super(plugin);
}
@Override
protected void configure() {
super.configure();
registerModule(QuestManager.class);
registerModule(QuestsCommand.class);
Multibinder<QuestType> questTypeMultibinder = Multibinder.newSetBinder(binder(), QuestType.class);
questTypeMultibinder.addBinding().to(KillPlayersQuestType.class);
questTypeMultibinder.addBinding().to(WinGameQuestType.class);
install(new FactoryModuleBuilder().build(QuestGUIFactory.class));
}
@Override
protected Class<? extends FlatFileEntity> getFlatFileEntity() {
return QuestsFlatFileEntity.class;
}
@Override
protected Class<? extends MySQLEntity> getSQLEntity() {
return QuestsSQLEntity.class;
}
}
| 1,570 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsSQLEntity.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/entities/QuestsSQLEntity.java | package me.patothebest.gamecore.quests.entities;
import com.google.inject.Inject;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.modifiers.PlayerModifier;
import me.patothebest.gamecore.player.modifiers.QuestModifier;
import me.patothebest.gamecore.quests.ActiveQuest;
import me.patothebest.gamecore.quests.Quest;
import me.patothebest.gamecore.quests.QuestManager;
import me.patothebest.gamecore.quests.QuestsStatus;
import me.patothebest.gamecore.storage.mysql.MySQLEntity;
import me.patothebest.gamecore.util.Utils;
import java.sql.*;
public class QuestsSQLEntity implements MySQLEntity {
private final QuestManager questManager;
@Inject private QuestsSQLEntity(QuestManager questManager) {
this.questManager = questManager;
}
/**
* Loads the player's quests
* <p>
* A record is inserted if the record doesn't
* exist.
*
* @param player the player loaded
* @param connection the database connection
*/
@Override
public void loadPlayer(CorePlayer player, Connection connection) throws SQLException {
PreparedStatement selectUser = connection.prepareStatement(QuestQueries.SELECT);
selectUser.setInt(1, player.getPlayerId());
ResultSet resultSet = selectUser.executeQuery();
while (resultSet.next()) {
String questName = resultSet.getString("quest_name");
Quest quest = questManager.getQuest(questName);
if (quest == null) {
Utils.printError(
"Warning: Quest does not exist! ",
"Quest: " + questName,
"While loading for player: " + player.getName()
);
continue;
}
int entryId = resultSet.getInt("entry_id");
long started = resultSet.getLong("started");
int status = resultSet.getInt("status");
int goalProgres = resultSet.getInt("goal_progress");
if (quest.getCooldown() + started < System.currentTimeMillis()) {
continue; // don't even bother parsing quests that already passed
}
ActiveQuest activeQuest = new ActiveQuest(player, quest, entryId, started, goalProgres, QuestsStatus.fromCode(status));
player.activateQuest(activeQuest);
}
resultSet.close();
selectUser.close();
}
/**
* Updates the player's quests in the database
*
* @param player the player to save
* @param connection the database connection
*/
@Override
public void savePlayer(CorePlayer player, Connection connection) throws SQLException { }
@Override
public void updatePlayer(CorePlayer player, Connection connection, PlayerModifier updatedType, Object... args) throws SQLException {
if (!(updatedType instanceof QuestModifier)) {
return;
}
QuestModifier modifier = (QuestModifier) updatedType;
ActiveQuest activeQuest = (ActiveQuest) args[0];
if (modifier == QuestModifier.START_QUEST) {
PreparedStatement statement = connection.prepareStatement(QuestQueries.INSERT_RECORD, Statement.RETURN_GENERATED_KEYS);
statement.setInt(1, player.getPlayerId());
statement.setString(2, activeQuest.getQuest().getName());
statement.setLong(3, activeQuest.getStartDate());
statement.setInt(4, activeQuest.getQuestsStatus().getStatusCode());
statement.setInt(5, activeQuest.getProgress());
statement.executeUpdate();
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()) {
activeQuest.setEntryId(rs.getInt(1));
} else {
throw new SQLException("Could not get the id of the newly inserted stat record!");
}
} else if (modifier == QuestModifier.UPDATE_PROGRESS){
PreparedStatement statement = connection.prepareStatement(QuestQueries.UPDATE_PROGRESS);
statement.setInt(1, (Integer) args[1]);
statement.setInt(2, activeQuest.getEntryId());
statement.executeUpdate();
} else if (modifier == QuestModifier.UPDATE_STATUS){
PreparedStatement statement = connection.prepareStatement(QuestQueries.UPDATE_STATUS);
statement.setInt(1, activeQuest.getQuestsStatus().getStatusCode());
statement.setInt(2, activeQuest.getEntryId());
statement.executeUpdate();
}
}
/**
* Gets all the statements needed to create the
* table(s) for the specific entity.
*
* @return the create table statements
*/
@Override
public String[] getCreateTableStatements() {
return new String[]{QuestQueries.CREATE_TABLE};
}
} | 4,849 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestQueries.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/entities/QuestQueries.java | package me.patothebest.gamecore.quests.entities;
import me.patothebest.gamecore.PluginConfig;
public class QuestQueries {
static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS `" + PluginConfig.SQL_PREFIX + "_quests` (\n" +
" `entry_id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `player_id` int(11) NOT NULL,\n" +
" `quest_name` varchar(30) NOT NULL,\n" +
" `started` bigint(11) NOT NULL,\n" +
" `goal_progress` int(11) NOT NULL,\n" +
" `status` int(11) NOT NULL,\n" +
" PRIMARY KEY (`entry_id`)\n" +
");\n";
final static String INSERT_RECORD = "INSERT INTO " + PluginConfig.SQL_PREFIX + "_quests VALUES (NULL, ?, ?, ?, ?, ?)";
final static String SELECT = "SELECT * FROM " + PluginConfig.SQL_PREFIX + "_quests WHERE player_id=?";
final static String DELETE = "DELETE FROM " + PluginConfig.SQL_PREFIX + "_quests WHERE entry_id=?";
final static String UPDATE_STATUS = "UPDATE " + PluginConfig.SQL_PREFIX + "_quests SET status=? WHERE entry_id=?;";
final static String UPDATE_PROGRESS = "UPDATE " + PluginConfig.SQL_PREFIX + "_quests SET goal_progress=goal_progress+? WHERE entry_id=?;";
}
| 1,304 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsFlatFileEntity.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/entities/QuestsFlatFileEntity.java | package me.patothebest.gamecore.quests.entities;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.storage.StorageException;
import me.patothebest.gamecore.storage.flatfile.FlatFileEntity;
import me.patothebest.gamecore.storage.flatfile.PlayerProfileFile;
public class QuestsFlatFileEntity implements FlatFileEntity {
/**
* Loads the player's quests
*
* @param player the player loaded
* @param file the player's profile file
*/
@Override
public void loadPlayer(CorePlayer player, PlayerProfileFile file) throws StorageException {
}
/**
* Saves the player's quests
*
* @param player the player being saved
* @param file the player's profile file
*/
@Override
public void savePlayer(CorePlayer player, PlayerProfileFile file) throws StorageException {
}
}
| 878 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
WinGameQuestType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/types/WinGameQuestType.java | package me.patothebest.gamecore.quests.types;
import me.patothebest.gamecore.event.arena.GameEndEvent;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.quests.AbstractQuestType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
public class WinGameQuestType extends AbstractQuestType {
@EventHandler
public void onWin(GameEndEvent event) {
for (Player winner : event.getWinners()) {
IPlayer player = playerManager.getPlayer(winner);
updateProgress((CorePlayer) player, 1);
}
}
@Override
public String getName() {
return "win_games";
}
}
| 713 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
KillPlayersQuestType.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/types/KillPlayersQuestType.java | package me.patothebest.gamecore.quests.types;
import me.patothebest.gamecore.combat.CombatDeathEvent;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.quests.AbstractQuestType;
import org.bukkit.event.EventHandler;
public class KillPlayersQuestType extends AbstractQuestType {
@EventHandler
public void onCombatDeath(CombatDeathEvent event) {
if (event.getKillerPlayer() == null) {
return;
}
IPlayer player = playerManager.getPlayer(event.getKillerPlayer());
updateProgress((CorePlayer) player, 1);
}
@Override
public String getName() {
return "kill_players";
}
}
| 724 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestGUIFactory.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/ui/QuestGUIFactory.java | package me.patothebest.gamecore.quests.ui;
import me.patothebest.gamecore.quests.ui.QuestsGUI;
import org.bukkit.entity.Player;
public interface QuestGUIFactory {
QuestsGUI createQuestGUI(Player player);
}
| 214 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
QuestsGUI.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/quests/ui/QuestsGUI.java | package me.patothebest.gamecore.quests.ui;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.patothebest.gamecore.gui.inventory.GUIPage;
import me.patothebest.gamecore.gui.inventory.button.SimpleButton;
import me.patothebest.gamecore.itemstack.ItemStackBuilder;
import me.patothebest.gamecore.itemstack.Material;
import me.patothebest.gamecore.lang.CoreLang;
import me.patothebest.gamecore.player.IPlayer;
import me.patothebest.gamecore.player.PlayerManager;
import me.patothebest.gamecore.quests.ActiveQuest;
import me.patothebest.gamecore.quests.QuestManager;
import me.patothebest.gamecore.quests.QuestsStatus;
import me.patothebest.gamecore.util.Utils;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class QuestsGUI extends GUIPage {
private final PlayerManager playerManager;
private final QuestManager questManager;
@AssistedInject QuestsGUI(Plugin plugin, @Assisted Player player, PlayerManager playerManager, QuestManager questManager) {
super(plugin, player, CoreLang.GUI_QUEST_TITLE, Utils.transformToInventorySize(questManager.getQuestMap().size()));
this.playerManager = playerManager;
this.questManager = questManager;
build();
}
@Override
protected void buildPage() {
IPlayer player = playerManager.getPlayer(this.player);
questManager.getQuestMap().forEach((s, quest) -> {
ActiveQuest activeQuest = player.getActiveQuest(quest);
ItemStackBuilder item = new ItemStackBuilder()
.name(CoreLang.GUI_QUEST_ITEM_NAME.replace(this.player, quest.getDisplayName()))
.material(Material.MAP);
if (activeQuest == null || activeQuest.hasExpired()) {
item.lore(CoreLang.GUI_QUEST_STATUS_START.getMessage(player));
} else if (activeQuest.getQuestsStatus() == QuestsStatus.IN_PROGRESS) {
String deadline = Utils.createTime(player.getPlayer(), activeQuest.getDeadline() - System.currentTimeMillis());
item.lore(CoreLang.GUI_QUEST_STATUS_STARTED.getMessage(player))
.blankLine()
.addLore(CoreLang.GUI_QUEST_STATUS_PROGRESS.replace(player, activeQuest.getProgress(), activeQuest.getQuest().getGoal()))
.blankLine()
.addLore(CoreLang.GUI_QUEST_STATUS_DEADLINE.replace(player, deadline));
} else {
String cooldown = Utils.createTime(player.getPlayer(), activeQuest.getDeadline() - System.currentTimeMillis());
item.lore(CoreLang.GUI_QUEST_STATUS_COMPLETED.getMessage(player))
.blankLine()
.addLore(CoreLang.GUI_QUEST_STATUS_COOLDOWN.getMessage(player))
.addLore(CoreLang.GUI_QUEST_STATUS_COOLDOWN_2.replace(player, cooldown));
}
item.blankLine()
.addLore(CoreLang.GUI_QUEST_STATUS_EXP.replace(player, quest.getXpReward()))
.addLore(CoreLang.GUI_QUEST_STATUS_COINS.replace(player, quest.getMoneyReward()));
addButton(new SimpleButton(item).action(() -> {
if (activeQuest == null || activeQuest.hasExpired()) {
ActiveQuest newQuest = new ActiveQuest(player, quest, -1, System.currentTimeMillis(), 0, QuestsStatus.IN_PROGRESS);
player.activateQuest(newQuest);
CoreLang.GUI_QUEST_STARTED.replaceAndSend(player, quest.getDisplayName());
refresh();
}
}));
});
}
}
| 3,683 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
EloManager.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/GameCore/src/main/java/me/patothebest/gamecore/elo/EloManager.java | package me.patothebest.gamecore.elo;
import me.patothebest.gamecore.modules.ActivableModule;
public class EloManager implements ActivableModule {
}
| 153 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.