res = new ArrayList<>();
+ final int d2 = distance * distance;
+ for (final Player p : Bukkit.getServer().getOnlinePlayers())
+ {
+ if (p.getWorld() == player.getWorld() && p.getLocation().distanceSquared(player.getLocation()) <= d2)
+ {
+ res.add(p);
+ }
+ }
+ return res;
+ }
+
+ public String getName()
+ {
+ return this.minigame;
+ }
+
+ public void setName(final String minigame)
+ {
+ this.minigame = minigame;
+ }
+
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java
index 728dbe97..cfde87a4 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaLogger.java
@@ -1,13 +1,691 @@
-package com.comze_instancelabs.minigamesapi;
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
-import org.bukkit.Bukkit;
+ 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 General Public License for more details.
-public class ArenaLogger {
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+package com.comze_instancelabs.minigamesapi;
- public static void debug(String msg) {
- if (MinigamesAPI.debug) {
- Bukkit.getConsoleSender().sendMessage("[" + System.currentTimeMillis() + " MGLIB-DBG] " + msg);
- }
- }
+import java.util.function.Supplier;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.bukkit.Bukkit;
+/**
+ * Logging helper for arenas.
+ *
+ * @author instancelabs
+ */
+public class ArenaLogger
+{
+
+ /** the plugin logger. */
+ private Logger pluginLogger;
+
+ /** the arena name to be used. */
+ private String arenaName;
+
+ /**
+ * The plugin logger to be used.
+ *
+ * @param logger
+ * logger to be used.
+ * @param arenaName
+ * arena name to use for logging.
+ */
+ public ArenaLogger(Logger logger, String arenaName)
+ {
+ this.pluginLogger = logger;
+ this.arenaName = arenaName;
+ }
+
+ /**
+ * Returns the arena prefix string.
+ *
+ * @return arena prefix string for logging.
+ */
+ private String getArenaPrefix()
+ {
+ return "[arena:" + this.arenaName + "] "; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ /**
+ * Log a SEVERE message.
+ *
+ * If the logger is currently enabled for the SEVERE message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void severe(String msg)
+ {
+ log(Level.SEVERE, msg);
+ }
+
+ /**
+ * Log a WARNING message.
+ *
+ * If the logger is currently enabled for the WARNING message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void warning(String msg)
+ {
+ log(Level.WARNING, msg);
+ }
+
+ /**
+ * Log an INFO message.
+ *
+ * If the logger is currently enabled for the INFO message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void info(String msg)
+ {
+ log(Level.INFO, msg);
+ }
+
+ /**
+ * Log a CONFIG message.
+ *
+ * If the logger is currently enabled for the CONFIG message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void config(String msg)
+ {
+ log(Level.CONFIG, msg);
+ }
+
+ /**
+ * Log a FINE message.
+ *
+ * If the logger is currently enabled for the FINE message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void fine(String msg)
+ {
+ log(Level.FINE, msg);
+ }
+
+ /**
+ * Log a FINER message.
+ *
+ * If the logger is currently enabled for the FINER message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void finer(String msg)
+ {
+ log(Level.FINER, msg);
+ }
+
+ /**
+ * Log a FINEST message.
+ *
+ * If the logger is currently enabled for the FINEST message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void finest(String msg)
+ {
+ log(Level.FINEST, msg);
+ }
+
+ /**
+ * Log a message, with no arguments.
+ *
+ * If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void log(Level level, String msg)
+ {
+ this.pluginLogger.log(level, getArenaPrefix() + msg);
+ }
+
+ /**
+ * Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ */
+ public void log(Level level, Supplier msgSupplier)
+ {
+ this.pluginLogger.log(level, () -> (getArenaPrefix() + msgSupplier.get()));
+ }
+
+ /**
+ * Log a message, with one object parameter.
+ *
+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param param1
+ * parameter to the message
+ */
+ public void log(Level level, String msg, Object param1)
+ {
+ this.pluginLogger.log(level, getArenaPrefix() + msg, param1);
+ }
+
+ /**
+ * Log a message, with an array of object arguments.
+ *
+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param params
+ * array of parameters to the message
+ */
+ public void log(Level level, String msg, Object params[])
+ {
+ this.pluginLogger.log(level, getArenaPrefix() + msg, params);
+ }
+
+ /**
+ * Log a message, with associated Throwable information.
+ *
+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers.
+ *
+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated
+ * as a formatting parameter to the LogRecord message property.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param thrown
+ * Throwable associated with log message.
+ */
+ public void log(Level level, String msg, Throwable thrown)
+ {
+ this.pluginLogger.log(level, getArenaPrefix() + msg, thrown);
+ }
+
+ /**
+ * Log a lazily constructed message, with associated Throwable information.
+ *
+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function. The message and the given {@link Throwable} are then
+ * stored in a {@link LogRecord} which is forwarded to all registered output handlers.
+ *
+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated
+ * as a formatting parameter to the LogRecord message property.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param thrown
+ * Throwable associated with log message.
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void log(Level level, Throwable thrown, Supplier msgSupplier)
+ {
+ this.pluginLogger.log(level, thrown, () -> (getArenaPrefix() + msgSupplier.get()));
+ }
+
+ /**
+ * Log a message, specifying source class and method, with no arguments.
+ *
+ * If the logger is currently enabled for the given message level then the given message is forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param msg
+ * The string message (or a key in the message catalog)
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, String msg)
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg);
+ }
+
+ /**
+ * Log a lazily constructed message, specifying source class and method, with no arguments.
+ *
+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier)
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, () -> (getArenaPrefix() + msgSupplier.get()));
+ }
+
+ /**
+ * Log a message, specifying source class and method, with a single object parameter to the log message.
+ *
+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param param1
+ * Parameter to the log message.
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1)
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, param1);
+ }
+
+ /**
+ * Log a message, specifying source class and method, with an array of object arguments.
+ *
+ * If the logger is currently enabled for the given message level then a corresponding LogRecord is created and forwarded to all the registered output Handler objects.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param params
+ * Array of parameters to the message
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[])
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, params);
+ }
+
+ /**
+ * Log a message, specifying source class and method, with associated Throwable information.
+ *
+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers.
+ *
+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated
+ * as a formatting parameter to the LogRecord message property.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param msg
+ * The string message (or a key in the message catalog)
+ * @param thrown
+ * Throwable associated with log message.
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown)
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, getArenaPrefix() + msg, thrown);
+ }
+
+ /**
+ * Log a lazily constructed message, specifying source class and method, with associated Throwable information.
+ *
+ * If the logger is currently enabled for the given message level then the message is constructed by invoking the provided supplier function. The message and the given {@link Throwable} are then
+ * stored in a {@link LogRecord} which is forwarded to all registered output handlers.
+ *
+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated
+ * as a formatting parameter to the LogRecord message property.
+ *
+ *
+ * @param level
+ * One of the message level identifiers, e.g., SEVERE
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that issued the logging request
+ * @param thrown
+ * Throwable associated with log message.
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier)
+ {
+ this.pluginLogger.logp(level, sourceClass, sourceMethod, thrown, () -> (getArenaPrefix() + msgSupplier.get()));
+ }
+
+ /**
+ * Log a method entry.
+ *
+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY", log level FINER, and the given sourceMethod and sourceClass is logged.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that is being entered
+ */
+ public void entering(String sourceClass, String sourceMethod)
+ {
+ this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "ENTRY"); //$NON-NLS-1$
+ }
+
+ /**
+ * Log a method entry, with one parameter.
+ *
+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY {0}", log level FINER, and the given sourceMethod, sourceClass, and parameter is logged.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that is being entered
+ * @param param1
+ * parameter to the method being entered
+ */
+ public void entering(String sourceClass, String sourceMethod, Object param1)
+ {
+ this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "ENTRY {0}", param1); //$NON-NLS-1$
+ }
+
+ /**
+ * Log a method entry, with an array of parameters.
+ *
+ * This is a convenience method that can be used to log entry to a method. A LogRecord with message "ENTRY" (followed by a format {N} indicator for each entry in the parameter array), log level
+ * FINER, and the given sourceMethod, sourceClass, and parameters is logged.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of method that is being entered
+ * @param params
+ * array of parameters to the method being entered
+ */
+ public void entering(String sourceClass, String sourceMethod, Object params[])
+ {
+ String msg = getArenaPrefix() + "ENTRY"; //$NON-NLS-1$
+ if (params == null)
+ {
+ logp(Level.FINER, sourceClass, sourceMethod, msg);
+ return;
+ }
+ if (!isLoggable(Level.FINER))
+ return;
+ for (int i = 0; i < params.length; i++)
+ {
+ msg = msg + " {" + i + "}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, msg, params);
+ }
+
+ /**
+ * Log a method return.
+ *
+ * This is a convenience method that can be used to log returning from a method. A LogRecord with message "RETURN", log level FINER, and the given sourceMethod and sourceClass is logged.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of the method
+ */
+ public void exiting(String sourceClass, String sourceMethod)
+ {
+ this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "RETURN"); //$NON-NLS-1$
+ }
+
+ /**
+ * Log a method return, with result object.
+ *
+ * This is a convenience method that can be used to log returning from a method. A LogRecord with message "RETURN {0}", log level FINER, and the gives sourceMethod, sourceClass, and result object
+ * is logged.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of the method
+ * @param result
+ * Object that is being returned
+ */
+ public void exiting(String sourceClass, String sourceMethod, Object result)
+ {
+ this.pluginLogger.logp(Level.FINER, sourceClass, sourceMethod, getArenaPrefix() + "RETURN {0}", result); //$NON-NLS-1$
+ }
+
+ /**
+ * Log throwing an exception.
+ *
+ * This is a convenience method to log that a method is terminating by throwing an exception. The logging is done using the FINER level.
+ *
+ * If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord which is forwarded to all registered output handlers. The LogRecord's message
+ * is set to "THROW".
+ *
+ * Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters property. Thus it is processed specially by output Formatters and is not treated
+ * as a formatting parameter to the LogRecord message property.
+ *
+ *
+ * @param sourceClass
+ * name of class that issued the logging request
+ * @param sourceMethod
+ * name of the method.
+ * @param thrown
+ * The Throwable that is being thrown.
+ */
+ public void throwing(String sourceClass, String sourceMethod, Throwable thrown)
+ {
+ if (!isLoggable(Level.FINER))
+ {
+ return;
+ }
+ LogRecord lr = new LogRecord(Level.FINER, getArenaPrefix() + "THROW"); //$NON-NLS-1$
+ lr.setSourceClassName(sourceClass);
+ lr.setSourceMethodName(sourceMethod);
+ lr.setThrown(thrown);
+ this.pluginLogger.log(lr);
+ }
+
+ /**
+ * Log a SEVERE message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the SEVERE message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void severe(Supplier msgSupplier)
+ {
+ log(Level.SEVERE, msgSupplier);
+ }
+
+ /**
+ * Log a WARNING message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the WARNING message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void warning(Supplier msgSupplier)
+ {
+ log(Level.WARNING, msgSupplier);
+ }
+
+ /**
+ * Log a INFO message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the INFO message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void info(Supplier msgSupplier)
+ {
+ log(Level.INFO, msgSupplier);
+ }
+
+ /**
+ * Log a CONFIG message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the CONFIG message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void config(Supplier msgSupplier)
+ {
+ log(Level.CONFIG, msgSupplier);
+ }
+
+ /**
+ * Log a FINE message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the FINE message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void fine(Supplier msgSupplier)
+ {
+ log(Level.FINE, msgSupplier);
+ }
+
+ /**
+ * Log a FINER message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the FINER message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void finer(Supplier msgSupplier)
+ {
+ log(Level.FINER, msgSupplier);
+ }
+
+ /**
+ * Log a FINEST message, which is only to be constructed if the logging level is such that the message will actually be logged.
+ *
+ * If the logger is currently enabled for the FINEST message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler
+ * objects.
+ *
+ *
+ * @param msgSupplier
+ * A function, which when called, produces the desired log message
+ * @since 1.8
+ */
+ public void finest(Supplier msgSupplier)
+ {
+ log(Level.FINEST, msgSupplier);
+ }
+
+ /**
+ * Get the log Level that has been specified for this Logger. The result may be null, which means that this logger's effective level will be inherited from its parent.
+ *
+ * @return this Logger's level
+ */
+ public Level getLevel()
+ {
+ return this.pluginLogger.getLevel();
+ }
+
+ /**
+ * Check if a message of the given level would actually be logged by this logger. This check is based on the Loggers effective level, which may be inherited from its parent.
+ *
+ * @param level
+ * a message logging level
+ * @return true if the given message level is currently being logged.
+ */
+ public boolean isLoggable(Level level)
+ {
+ return this.pluginLogger.isLoggable(level);
+ }
+
+ /**
+ * Debug some string.
+ *
+ * @param msg
+ * debug message.
+ */
+ public static void debug(final String msg)
+ {
+ if (MinigamesAPI.debug)
+ {
+ Bukkit.getConsoleSender().sendMessage("[" + System.currentTimeMillis() + " MGLIB-DBG] " + msg); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java
new file mode 100644
index 00000000..55640cf5
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaMessageStrings.java
@@ -0,0 +1,50 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+/**
+ * Strings for messages.
+ *
+ * @author mepeisen
+ */
+public interface ArenaMessageStrings
+{
+
+ /** ARENA replacement. */
+ String ARENA = ""; //$NON-NLS-1$
+
+ /** ACTION replacement. */
+ String ACTION = ""; //$NON-NLS-1$
+
+ /** AUTHOR replacement. */
+ String AUTHOR = ""; //$NON-NLS-1$
+
+ /** DESCRIPTION replacement. */
+ String DESCRIPTION = ""; //$NON-NLS-1$
+
+ /** PLAYER replacement. */
+ String PLAYER = ""; //$NON-NLS-1$
+
+ /** KILLER replacement. */
+ String KILLER = ""; //$NON-NLS-1$
+
+ /** COUNT replacement. */
+ String COUNT = ""; //$NON-NLS-1$
+
+ /** MAXCOUNT replacement. */
+ String MAXCOUNT = ""; //$NON-NLS-1$
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java
new file mode 100644
index 00000000..2fee7cad
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPermissionStrings.java
@@ -0,0 +1,32 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+/**
+ * Strings for arenas permissions.
+ *
+ * @author mepeisen
+ */
+public interface ArenaPermissionStrings
+{
+
+ /** arenas vip permission. */
+ String VIP = ".vip"; //$NON-NLS-1$
+
+ /** arena prefix for permission. */
+ String PREFIX = ".arenas."; //$NON-NLS-1$
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java
index d024654c..8dd03943 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaPlayer.java
@@ -1,3 +1,17 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.util.HashMap;
@@ -9,87 +23,217 @@
import com.comze_instancelabs.minigamesapi.util.AClass;
-public class ArenaPlayer {
-
- String playername;
- ItemStack[] inv;
- ItemStack[] armor_inv;
- GameMode original_gamemode = GameMode.SURVIVAL;
- int original_xplvl = 0;
- boolean noreward = false;
- Arena currentArena;
- AClass currentClass;
-
- private static HashMap players = new HashMap();
-
- public static ArenaPlayer getPlayerInstance(String playername) {
- if (!players.containsKey(playername)) {
- return new ArenaPlayer(playername);
- } else {
- return players.get(playername);
- }
- }
-
- public ArenaPlayer(String playername) {
- this.playername = playername;
- players.put(playername, this);
- }
-
- public Player getPlayer() {
- return Bukkit.getPlayer(playername);
- }
-
- public void setInventories(ItemStack[] inv, ItemStack[] armor_inv) {
- this.inv = inv;
- this.armor_inv = armor_inv;
- }
-
- public ItemStack[] getInventory() {
- return inv;
- }
-
- public ItemStack[] getArmorInventory() {
- return armor_inv;
- }
-
- public GameMode getOriginalGamemode() {
- return original_gamemode;
- }
-
- public void setOriginalGamemode(GameMode original_gamemode) {
- this.original_gamemode = original_gamemode;
- }
-
- public int getOriginalXplvl() {
- return original_xplvl;
- }
-
- public void setOriginalXplvl(int original_xplvl) {
- this.original_xplvl = original_xplvl;
- }
-
- public boolean isNoReward() {
- return noreward;
- }
-
- public void setNoReward(boolean noreward) {
- this.noreward = noreward;
- }
-
- public Arena getCurrentArena() {
- return currentArena;
- }
-
- public void setCurrentArena(Arena currentArena) {
- this.currentArena = currentArena;
- }
-
- public AClass getCurrentClass() {
- return currentClass;
- }
-
- public void setCurrentClass(AClass currentClass) {
- this.currentClass = currentClass;
- }
-
+/**
+ * Internal minigames representation of a player being present in any arena.
+ *
+ *
+ * TODO: Remove from hashmap players as soon as a player leaves the server.
+ *
+ *
+ *
+ * TODO: Clear inventories as soon as it was re set while leaving.
+ *
+ *
+ * @author instancelabs
+ */
+public class ArenaPlayer
+{
+
+ /** The players name. */
+ private String playername;
+ /** the inventory stack. */
+ private ItemStack[] inv;
+ /** the armor inventory stack. */
+ private ItemStack[] armor_inv;
+ /** the original game mode of the player. */
+ private GameMode original_gamemode = GameMode.SURVIVAL;
+ /** the original xp level of the player. */
+ private int original_xplvl = 0;
+ /** the no-reward flag. */
+ private boolean noreward = false;
+ /** the current arena. */
+ private Arena currentArena;
+ /** the current class. */
+ private AClass currentClass;
+
+ /** the map holding the known arena player instances. */
+ private static final HashMap players = new HashMap<>();
+
+ /**
+ * Returns the player instance for given player name; creates it on demand.
+ *
+ * @param playername
+ * name of the player.
+ * @return arena player instance.
+ */
+ public static ArenaPlayer getPlayerInstance(final String playername)
+ {
+ if (!ArenaPlayer.players.containsKey(playername))
+ {
+ return new ArenaPlayer(playername);
+ }
+ return ArenaPlayer.players.get(playername);
+ }
+
+ /**
+ * Constructor to create the arena player.
+ *
+ * @param playername
+ * players name.
+ */
+ public ArenaPlayer(final String playername)
+ {
+ this.playername = playername;
+ ArenaPlayer.players.put(playername, this);
+ }
+
+ /**
+ * Returns the bukkit player.
+ *
+ * @return bukkit player.
+ */
+ public Player getPlayer()
+ {
+ return Bukkit.getPlayer(this.playername);
+ }
+
+ /**
+ * Sets the inventories being present befor the player joins the lobby.
+ *
+ * @param inv
+ * inventory of the player.
+ * @param armor_inv
+ * armor inventory of the player.
+ */
+ public void setInventories(final ItemStack[] inv, final ItemStack[] armor_inv)
+ {
+ this.inv = inv;
+ this.armor_inv = armor_inv;
+ }
+
+ /**
+ * Returns the players inventory before joining the lobby.
+ *
+ * @return player inventory.
+ */
+ public ItemStack[] getInventory()
+ {
+ return this.inv;
+ }
+
+ /**
+ * Returns the players armor inventory before joining the lobby.
+ *
+ * @return players armo inventory.
+ */
+ public ItemStack[] getArmorInventory()
+ {
+ return this.armor_inv;
+ }
+
+ /**
+ * Returns the original game mode before joining the lobby.
+ *
+ * @return original game mode.
+ */
+ public GameMode getOriginalGamemode()
+ {
+ return this.original_gamemode;
+ }
+
+ /**
+ * Sets the original game mode before joining the lobby.
+ *
+ * @param original_gamemode
+ * the players original game mode.
+ */
+ public void setOriginalGamemode(final GameMode original_gamemode)
+ {
+ this.original_gamemode = original_gamemode;
+ }
+
+ /**
+ * Returns the original xp level before joining the lobby.
+ *
+ * @return original xp mode before joining the lobby.
+ */
+ public int getOriginalXplvl()
+ {
+ return this.original_xplvl;
+ }
+
+ /**
+ * Sets the original xp level of the player.
+ *
+ * @param original_xplvl
+ * cp level before joining the lobby.
+ */
+ public void setOriginalXplvl(final int original_xplvl)
+ {
+ this.original_xplvl = original_xplvl;
+ }
+
+ /**
+ * Returns the is no reward flag.
+ *
+ * @return {@code true} if the player does not receive rewards.
+ */
+ public boolean isNoReward()
+ {
+ return this.noreward;
+ }
+
+ /**
+ * Sets the no-reward flag.
+ *
+ * @param noreward
+ * {@code true} if the player does not receive rewards.
+ */
+ public void setNoReward(final boolean noreward)
+ {
+ this.noreward = noreward;
+ }
+
+ /**
+ * Returns the current arena the player is located in.
+ *
+ * @return current arena or {@code null} if the player is not in any arena.
+ */
+ public Arena getCurrentArena()
+ {
+ return this.currentArena;
+ }
+
+ /**
+ * Sets the current arena the player is located in.
+ *
+ * @param currentArena
+ * current arena.
+ */
+ public void setCurrentArena(final Arena currentArena)
+ {
+ this.currentArena = currentArena;
+ }
+
+ /**
+ * Returns the current player class.
+ *
+ * @return player class.
+ */
+ public AClass getCurrentClass()
+ {
+ return this.currentClass;
+ }
+
+ /**
+ * Sets the current player class.
+ *
+ * @param currentClass
+ * player class.
+ */
+ public void setCurrentClass(final AClass currentClass)
+ {
+ this.currentClass = currentClass;
+ }
+
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java
index bbff53fc..8db99d07 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaSetup.java
@@ -1,7 +1,22 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -13,229 +28,272 @@
import com.comze_instancelabs.minigamesapi.util.Util;
import com.comze_instancelabs.minigamesapi.util.Validator;
-public class ArenaSetup {
-
- // actually the most basic arena just needs a spawn and a lobby
-
- /**
- * Sets the spawn for a single-spawn arena
- *
- * @param arenaname
- * @param l
- * Location of the spawn
- */
- public void setSpawn(JavaPlugin plugin, String arenaname, Location l) {
- Util.saveComponentForArena(plugin, arenaname, "spawns.spawn0", l);
- }
-
- /**
- * Sets a new spawn for a multi-spawn arena without the need of a given index
- *
- * @param plugin
- * @param arenaname
- * @param l
- * Location of the spawn
- * @return the automatically used index
- */
- public int autoSetSpawn(JavaPlugin plugin, String arenaname, Location l) {
- int count = Util.getAllSpawns(plugin, arenaname).size();
- Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l);
- return count;
- }
-
- /**
- * Sets one of multiple spawns for a multi-spawn arena
- *
- * @param arenaname
- * @param l
- * Location of the spawn
- * @param count
- * Index of the spawn; if the given index is already set, the spawn location will be overwritten
- */
- public void setSpawn(JavaPlugin plugin, String arenaname, Location l, int count) {
- Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l);
- }
-
- /**
- * Removes a spawn at the given index
- *
- * @param plugin
- * @param arenaname
- * @param count
- * Index of the spawn
- */
- public boolean removeSpawn(JavaPlugin plugin, String arenaname, int count) {
- ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig();
- String path = "arenas." + arenaname + ".spawns.spawn" + Integer.toString(count);
- boolean ret = false;
- if (config.getConfig().isSet(path)) {
- ret = true;
- }
- config.getConfig().set(path, null);
- config.saveConfig();
- return ret;
- }
-
- /**
- * Sets the waiting lobby for an arena
- *
- * @param arenaname
- * @param l
- * Location of the lobby
- */
- public void setLobby(JavaPlugin plugin, String arenaname, Location l) {
- Util.saveComponentForArena(plugin, arenaname, "lobby", l);
- }
-
- /**
- * Sets the main lobby
- *
- * @param l
- * Location of the lobby
- */
- public void setMainLobby(JavaPlugin plugin, Location l) {
- Util.saveMainLobby(plugin, l);
- }
-
- /**
- * Sets low and high boundaries for later blocks resetting
- *
- * @param plugin
- * @param arenaname
- * @param l
- * Location to save
- * @param low
- * True if it's the low boundary, false if it's the high boundary
- */
- public void setBoundaries(JavaPlugin plugin, String arenaname, Location l, boolean low) {
- if (low) {
- Util.saveComponentForArena(plugin, arenaname, "bounds.low", l);
- } else {
- Util.saveComponentForArena(plugin, arenaname, "bounds.high", l);
- }
- }
-
- /**
- * Sets low and high boundaries for later blocks resetting for a sub component
- *
- * @param plugin
- * @param arenaname
- * @param l
- * Location to save
- * @param low
- * True if it's the low boundary, false if it's the high boundary
- * @param extra_component
- * Sub component string
- */
- public void setBoundaries(JavaPlugin plugin, String arenaname, Location l, boolean low, String extra_component) {
- if (low) {
- Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.low", l);
- } else {
- Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.high", l);
- }
- }
-
- /**
- * Saves a given arena if it was set up properly.
- *
- * @return Arena or null if setup failed
- */
- public Arena saveArena(JavaPlugin plugin, String arenaname) {
- if (!Validator.isArenaValid(plugin, arenaname)) {
- Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Arena " + arenaname + " appears to be invalid.");
- return null;
- }
- PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin);
- if (pli.getArenaByName(arenaname) != null) {
- pli.removeArenaByName(arenaname);
- }
- Arena a = Util.initArena(plugin, arenaname);
- if (a.getArenaType() == ArenaType.REGENERATION) {
- if (Util.isComponentForArenaValid(plugin, arenaname, "bounds")) {
- Util.saveArenaToFile(plugin, arenaname);
- } else {
- Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Could not save arena to file because boundaries were not set up.");
- }
- }
- this.setArenaVIP(plugin, arenaname, false);
- pli.addArena(a);
-
- // experimental:
- Class clazz = plugin.getClass();
- try {
- Method method = clazz.getDeclaredMethod("loadArenas", JavaPlugin.class, pli.getArenasConfig().getClass());
- if (method != null) {
- method.setAccessible(true);
- Object ret = method.invoke(this, plugin, pli.getArenasConfig());
- System.out.println(ret);
- pli.clearArenas();
- pli.addLoadedArenas((ArrayList) ret);
- }
- } catch (Exception e) {
- System.out.println("Failed to update Arena list, please reload the server.");
- e.printStackTrace();
- }
-
- String path = "arenas." + arenaname + ".displayname";
- if (!pli.getArenasConfig().getConfig().isSet(path)) {
- pli.getArenasConfig().getConfig().set(path, arenaname);
- pli.getArenasConfig().saveConfig();
- }
-
- return a;
- }
-
- public void setPlayerCount(JavaPlugin plugin, String arena, int count, boolean max) {
- String component = "max_players";
- if (!max) {
- component = "min_players";
- }
- String base = "arenas." + arena + "." + component;
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(base, count);
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
- }
-
- public int getPlayerCount(JavaPlugin plugin, String arena, boolean max) {
- if (!max) {
- if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet("arenas." + arena + ".min_players")) {
- setPlayerCount(plugin, arena, plugin.getConfig().getInt("config.defaults.default_min_players"), max);
- return plugin.getConfig().getInt("config.defaults.default_min_players");
- }
- return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt("arenas." + arena + ".min_players");
- }
- if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet("arenas." + arena + ".max_players")) {
- setPlayerCount(plugin, arena, plugin.getConfig().getInt("config.defaults.default_max_players"), max);
- return plugin.getConfig().getInt("config.defaults.default_max_players");
- }
- return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt("arenas." + arena + ".max_players");
- }
-
- public void setArenaVIP(JavaPlugin plugin, String arena, boolean vip) {
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".is_vip", vip);
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
- }
-
- public boolean getArenaVIP(JavaPlugin plugin, String arena) {
- return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getBoolean("arenas." + arena + ".is_vip");
- }
-
- public void setArenaEnabled(JavaPlugin plugin, String arena, boolean enabled) {
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".enabled", enabled);
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
- }
-
- public boolean getArenaEnabled(JavaPlugin plugin, String arena) {
- FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig();
- return config.isSet("arenas." + arena + ".enabled") ? config.getBoolean("arenas." + arena + ".enabled") : true;
- }
-
- public void setShowScoreboard(JavaPlugin plugin, String arena, boolean enabled) {
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set("arenas." + arena + ".showscoreboard", enabled);
- MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
- }
-
- public boolean getShowScoreboard(JavaPlugin plugin, String arena) {
- FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig();
- return config.isSet("arenas." + arena + ".showscoreboard") ? config.getBoolean("arenas." + arena + ".showscoreboard") : true;
- }
+/**
+ * Arena setup helper.
+ *
+ * @author instancelabs
+ */
+public class ArenaSetup
+{
+
+ // actually the most basic arena just needs a spawn and a lobby
+
+ /**
+ * Sets the spawn for a single-spawn arena
+ *
+ * @param arenaname
+ * @param l
+ * Location of the spawn
+ */
+ public void setSpawn(final JavaPlugin plugin, final String arenaname, final Location l)
+ {
+ Util.saveComponentForArena(plugin, arenaname, "spawns.spawn0", l);
+ }
+
+ /**
+ * Sets a new spawn for a multi-spawn arena without the need of a given index
+ *
+ * @param plugin
+ * @param arenaname
+ * @param l
+ * Location of the spawn
+ * @return the automatically used index
+ */
+ public int autoSetSpawn(final JavaPlugin plugin, final String arenaname, final Location l)
+ {
+ final int count = Util.getAllSpawns(plugin, arenaname).size();
+ Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l);
+ return count;
+ }
+
+ /**
+ * Sets one of multiple spawns for a multi-spawn arena
+ *
+ * @param arenaname
+ * @param l
+ * Location of the spawn
+ * @param count
+ * Index of the spawn; if the given index is already set, the spawn location will be overwritten
+ */
+ public void setSpawn(final JavaPlugin plugin, final String arenaname, final Location l, final int count)
+ {
+ Util.saveComponentForArena(plugin, arenaname, "spawns.spawn" + Integer.toString(count), l);
+ }
+
+ /**
+ * Removes a spawn at the given index
+ *
+ * @param plugin
+ * @param arenaname
+ * @param count
+ * Index of the spawn
+ */
+ public boolean removeSpawn(final JavaPlugin plugin, final String arenaname, final int count)
+ {
+ final ArenasConfig config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig();
+ final String path = ArenaConfigStrings.ARENAS_PREFIX + arenaname + ".spawns.spawn" + Integer.toString(count);
+ boolean ret = false;
+ if (config.getConfig().isSet(path))
+ {
+ ret = true;
+ }
+ config.getConfig().set(path, null);
+ config.saveConfig();
+ return ret;
+ }
+
+ /**
+ * Sets the waiting lobby for an arena
+ *
+ * @param arenaname
+ * @param l
+ * Location of the lobby
+ */
+ public void setLobby(final JavaPlugin plugin, final String arenaname, final Location l)
+ {
+ Util.saveComponentForArena(plugin, arenaname, "lobby", l);
+ }
+
+ /**
+ * Sets the main lobby
+ *
+ * @param l
+ * Location of the lobby
+ */
+ public void setMainLobby(final JavaPlugin plugin, final Location l)
+ {
+ Util.saveMainLobby(plugin, l);
+ }
+
+ /**
+ * Sets low and high boundaries for later blocks resetting
+ *
+ * @param plugin
+ * @param arenaname
+ * @param l
+ * Location to save
+ * @param low
+ * True if it's the low boundary, false if it's the high boundary
+ */
+ public void setBoundaries(final JavaPlugin plugin, final String arenaname, final Location l, final boolean low)
+ {
+ if (low)
+ {
+ Util.saveComponentForArena(plugin, arenaname, ArenaConfigStrings.BOUNDS_LOW, l);
+ }
+ else
+ {
+ Util.saveComponentForArena(plugin, arenaname, ArenaConfigStrings.BOUNDS_HIGH, l);
+ }
+ }
+
+ /**
+ * Sets low and high boundaries for later blocks resetting for a sub component
+ *
+ * @param plugin
+ * @param arenaname
+ * @param l
+ * Location to save
+ * @param low
+ * True if it's the low boundary, false if it's the high boundary
+ * @param extra_component
+ * Sub component string
+ */
+ public void setBoundaries(final JavaPlugin plugin, final String arenaname, final Location l, final boolean low, final String extra_component)
+ {
+ if (low)
+ {
+ Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.low", l);
+ }
+ else
+ {
+ Util.saveComponentForArena(plugin, arenaname, extra_component + ".bounds.high", l);
+ }
+ }
+
+ /**
+ * Saves a given arena if it was set up properly.
+ *
+ * @return Arena or null if setup failed
+ */
+ public Arena saveArena(final JavaPlugin plugin, final String arenaname)
+ {
+ if (!Validator.isArenaValid(plugin, arenaname))
+ {
+ Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Arena " + arenaname + " appears to be invalid.");
+ return null;
+ }
+ final PluginInstance pli = MinigamesAPI.getAPI().getPluginInstance(plugin);
+ if (pli.getArenaByName(arenaname) != null)
+ {
+ pli.removeArenaByName(arenaname);
+ }
+ final Arena a = Util.initArena(plugin, arenaname);
+ if (a.getArenaType() == ArenaType.REGENERATION)
+ {
+ if (Util.isComponentForArenaValid(plugin, arenaname, "bounds"))
+ {
+ Util.saveArenaToFile(plugin, arenaname);
+ }
+ else
+ {
+ Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Could not save arena to file because boundaries were not set up.");
+ }
+ }
+ this.setArenaVIP(plugin, arenaname, false);
+ pli.addArena(a);
+
+ // experimental:
+ final Class extends JavaPlugin> clazz = plugin.getClass();
+ try
+ {
+ final Method method = clazz.getDeclaredMethod("loadArenas", JavaPlugin.class, pli.getArenasConfig().getClass());
+ if (method != null)
+ {
+ method.setAccessible(true);
+ final Object ret = method.invoke(this, plugin, pli.getArenasConfig());
+ pli.clearArenas();
+ pli.addLoadedArenas((ArrayList) ret);
+ }
+ }
+ catch (final Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed to update Arena list, please reload the server.", e);
+ }
+
+ final String path = ArenaConfigStrings.ARENAS_PREFIX + arenaname + ArenaConfigStrings.DISPLAYNAME_SUFFIX;
+ if (!pli.getArenasConfig().getConfig().isSet(path))
+ {
+ pli.getArenasConfig().getConfig().set(path, arenaname);
+ pli.getArenasConfig().saveConfig();
+ }
+
+ return a;
+ }
+
+ public void setPlayerCount(final JavaPlugin plugin, final String arena, final int count, final boolean max)
+ {
+ String component = "max_players";
+ if (!max)
+ {
+ component = "min_players";
+ }
+ final String base = ArenaConfigStrings.ARENAS_PREFIX + arena + "." + component;
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(base, count);
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
+ }
+
+ public int getPlayerCount(final JavaPlugin plugin, final String arena, final boolean max)
+ {
+ if (!max)
+ {
+ if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".min_players"))
+ {
+ this.setPlayerCount(plugin, arena, plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS), max);
+ return plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MIN_PLAYERS);
+ }
+ return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".min_players");
+ }
+ if (!MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".max_players"))
+ {
+ this.setPlayerCount(plugin, arena, plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS), max);
+ return plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_DEFAULT_MAX_PLAYERS);
+ }
+ return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getInt(ArenaConfigStrings.ARENAS_PREFIX + arena + ".max_players");
+ }
+
+ public void setArenaVIP(final JavaPlugin plugin, final String arena, final boolean vip)
+ {
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".is_vip", vip);
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
+ }
+
+ public boolean getArenaVIP(final JavaPlugin plugin, final String arena)
+ {
+ return MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".is_vip");
+ }
+
+ public void setArenaEnabled(final JavaPlugin plugin, final String arena, final boolean enabled)
+ {
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled", enabled);
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
+ }
+
+ public boolean getArenaEnabled(final JavaPlugin plugin, final String arena)
+ {
+ final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig();
+ return config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled") ? config.getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".enabled") : true;
+ }
+
+ public void setShowScoreboard(final JavaPlugin plugin, final String arena, final boolean enabled)
+ {
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig().set(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard", enabled);
+ MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().saveConfig();
+ }
+
+ public boolean getShowScoreboard(final JavaPlugin plugin, final String arena)
+ {
+ final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getArenasConfig().getConfig();
+ return config.isSet(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard") ? config.getBoolean(ArenaConfigStrings.ARENAS_PREFIX + arena + ".showscoreboard") : true;
+ }
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java
index 69c7c6e1..d350c946 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaState.java
@@ -1,26 +1,95 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-public enum ArenaState {
-
- JOIN, STARTING, INGAME, RESTARTING;
-
- public static ArrayList getAllStateNames() {
- return new ArrayList(Arrays.asList("JOIN", "STARTING", "INGAME", "RESTARTING"));
- }
-
- public static HashMap getAllStateNameColors() {
- HashMap ret = new HashMap() {
- {
- put("JOIN", "&a");
- put("STARTING", "&a");
- put("INGAME", "&4");
- put("RESTARTING", "&e");
- }
- };
- return ret;
- }
+/**
+ * The states for an arena.
+ *
+ * @author instancelabs
+ */
+public enum ArenaState
+{
+
+ /** the default state; players can join. */
+ JOIN("&a"), //$NON-NLS-1$
+
+ /** the game is starting. */
+ STARTING("&a"), //$NON-NLS-1$
+
+ /** the game is running. */
+ INGAME("&4"), //$NON-NLS-1$
+
+ /** the arena is restarting after game ended; for example the broken blocks are replaced. */
+ RESTARTING("&e"); //$NON-NLS-1$
+
+ /** the states color code. */
+ private String colorCode;
+
+ /**
+ * Constructor.
+ *
+ * @param colorCode
+ * the states color code
+ */
+ private ArenaState(String colorCode)
+ {
+ this.colorCode = colorCode;
+ }
+
+ /**
+ * Returns the color code for this state.
+ *
+ * @return color code used to display this state.
+ */
+ public String getColorCode()
+ {
+ return this.colorCode;
+ }
+
+ /**
+ * Returns a list with all state names.
+ *
+ * @return list with all state names.
+ */
+ public static Iterable getAllStateNames()
+ {
+ final List result = new ArrayList<>();
+ for (final ArenaState state : ArenaState.values())
+ {
+ result.add(state.name());
+ }
+ return result;
+ }
+
+ /**
+ * Returns a map from state name to color code.
+ *
+ * @return map from state name to color code.
+ */
+ public static Map getAllStateNameColors()
+ {
+ final Map result = new HashMap<>();
+ for (final ArenaState state : ArenaState.values())
+ {
+ result.put(state.name(), state.getColorCode());
+ }
+ return result;
+ }
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java
index 4d6b541d..eb8436b5 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ArenaType.java
@@ -1,20 +1,38 @@
-package com.comze_instancelabs.minigamesapi;
-
-public enum ArenaType {
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
- /**
- * Standard arena with lobby + spawn and lobby countdown; can have multiple spawns too
- */
- DEFAULT,
+ 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 General Public License for more details.
- /**
- * Players just join the game whenever they like, no lobby countdowns or arena/sign states; doesn't allow multiple spawns
- */
- JUMPNRUN,
-
- /**
- * Default arena + automatic regeneration
- */
- REGENERATION
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+package com.comze_instancelabs.minigamesapi;
+/**
+ * Arena types.
+ */
+public enum ArenaType
+{
+
+ /**
+ * Standard arena with lobby + spawn and lobby countdown; can have multiple spawns too
+ */
+ DEFAULT,
+
+ /**
+ * Players just join the game whenever they like, no lobby countdowns or arena/sign states; doesn't allow multiple spawns
+ */
+ JUMPNRUN,
+
+ /**
+ * Default arena + automatic regeneration
+ */
+ REGENERATION
+
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java
new file mode 100644
index 00000000..f9676112
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/ChannelStrings.java
@@ -0,0 +1,44 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+/**
+ * Pluginc hannel strings.
+ *
+ * @author mepeisen
+ */
+public interface ChannelStrings
+{
+
+ /** bungee cord plugin channel. */
+ String CHANNEL_BUNGEE_CORD = "BungeeCord"; //$NON-NLS-1$
+
+ /**
+ * Bungee-cord sub channel for minigames lib.
+ */
+ String SUBCHANNEL_MINIGAMESLIB_BACK = "MinigamesLibBack"; //$NON-NLS-1$
+
+ /**
+ * Bungee-cord sub channel for minigames lib.
+ */
+ String SUBCHANNEL_MINIGAMESLIB_REQUEST = "MinigamesLibRequest"; //$NON-NLS-1$
+
+ /**
+ * Bungee-cord sub channel for minigames lib.
+ */
+ String SUBCHANNEL_MINIGAMESLIB_SIGN = "MinigamesLibSign"; //$NON-NLS-1$
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java
index ca18bade..6102f63a 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java
@@ -1,11 +1,23 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
-import net.milkbowl.vault.economy.EconomyResponse;
-
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
@@ -25,444 +37,600 @@
import com.comze_instancelabs.minigamesapi.util.Validator;
import com.shampaggon.crackshot.CSUtility;
-public class Classes {
-
- JavaPlugin plugin;
- PluginInstance pli;
- public HashMap lasticonm = new HashMap();
-
- public Classes(JavaPlugin plugin) {
- this.plugin = plugin;
- this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin);
- }
-
- public Classes(PluginInstance pli, JavaPlugin plugin) {
- this.plugin = plugin;
- this.pli = pli;
- }
-
- public void openGUI(final String p) {
- final Classes cl = this;
- IconMenu iconm;
- int mincount = pli.getAClasses().keySet().size();
- if (!Validator.isPlayerOnline(p)) {
- return;
- }
- Player player = Bukkit.getPlayerExact(p);
- if (lasticonm.containsKey(p)) {
- iconm = lasticonm.get(p);
- } else {
- iconm = new IconMenu(pli.getMessagesConfig().classes_item, (9 * plugin.getConfig().getInt("config.GUI.classes_gui_rows") > mincount - 1) ? 9 * plugin.getConfig().getInt("config.GUI.classes_gui_rows") : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() {
- @Override
- public void onOptionClick(IconMenu.OptionClickEvent event) {
- if (event.getPlayer().getName().equalsIgnoreCase(p)) {
- if (pli.global_players.containsKey(p)) {
- if (pli.getArenas().contains(pli.global_players.get(p))) {
- String d = event.getName();
- Player p = event.getPlayer();
- if (pli.getAClasses().containsKey(d)) {
- cl.setClass(pli.getClassesHandler().getInternalNameByName(d), p.getName(), true);
- }
- }
- }
- }
- event.setWillClose(true);
- }
- }, plugin);
-
- int c = 0;
- for (String ac : pli.getAClasses().keySet()) {
- AClass ac_ = pli.getAClasses().get(ac);
- if (ac_.isEnabled()) {
- if (!pli.show_classes_without_usage_permission) {
- if (!kitPlayerHasPermission(ac_.getInternalName(), player)) {
- continue;
- }
- }
- int slot = c;
- if (pli.getClassesConfig().getConfig().isSet("config.kits." + ac_.getInternalName() + ".slot")) {
- slot = pli.getClassesConfig().getConfig().getInt("config.kits." + ac_.getInternalName() + ".slot");
- if (slot < 0 || slot > iconm.getSize() - 1) {
- slot = c;
- }
- }
- iconm.setOption(slot, ac_.getIcon().clone(), ac_.getName(), pli.getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";"));
- c++;
- }
- }
- }
-
- iconm.open(player);
- lasticonm.put(p, iconm);
- }
-
- public void getClass(String player) {
- if (!pli.getPClasses().containsKey(player)) {
- ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items.");
- return;
- }
- AClass c = pli.getPClasses().get(player);
- final Player p = Bukkit.getServer().getPlayer(player);
- Util.clearInv(p);
- ArrayList items = new ArrayList(Arrays.asList(c.getItems()));
- ArrayList temp = new ArrayList(Arrays.asList(c.getItems()));
- ArrayList tempguns = new ArrayList();
- final ArrayList temppotions = new ArrayList();
- final ArrayList temppotions_lv = new ArrayList();
- final ArrayList temppotions_duration = new ArrayList();
-
- // crackshot support
- for (ItemStack item : temp) {
- if (item != null) {
- if (item.hasItemMeta()) {
- if (item.getItemMeta().hasDisplayName()) {
- if (item.getItemMeta().getDisplayName().startsWith("crackshot:")) {
- items.remove(item);
- tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]);
- } else if (item.getItemMeta().getDisplayName().startsWith("potioneffect:")) {
- items.remove(item);
- String potioneffect = item.getItemMeta().getDisplayName().split(":")[1];
- String data = item.getItemMeta().getDisplayName().split(":")[2];
- Integer time = Integer.parseInt(data.substring(0, data.indexOf("#")));
- Integer lv = Integer.parseInt(data.split("#")[1]);
- if (PotionEffectType.getByName(potioneffect) != null) {
- temppotions.add(PotionEffectType.getByName(potioneffect));
- temppotions_lv.add(lv);
- temppotions_duration.add(time);
- }
- }
- }
- }
- }
- }
-
- for (ItemStack item : items) {
- if (item != null) {
- Color c_ = null;
- if (item.hasItemMeta()) {
- if (item.getItemMeta().hasDisplayName()) {
- if (item.getItemMeta().getDisplayName().startsWith("#") && item.getItemMeta().getDisplayName().length() == 7) {
- c_ = Util.hexToRgb(item.getItemMeta().getDisplayName());
- }
- }
- }
- if (item.getTypeId() == 298 || item.getTypeId() == 302 || item.getTypeId() == 306 || item.getTypeId() == 310 || item.getTypeId() == 314) {
- if (item.getTypeId() == 298) {
- LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
- if (c_ != null) {
- lam.setColor(c_);
- }
- item.setItemMeta(lam);
- }
- p.getInventory().setHelmet(item);
- continue;
- }
- if (item.getTypeId() == 299 || item.getTypeId() == 303 || item.getTypeId() == 307 || item.getTypeId() == 311 || item.getTypeId() == 315) {
- if (item.getTypeId() == 299) {
- LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
- if (c_ != null) {
- lam.setColor(c_);
- }
- item.setItemMeta(lam);
- }
- p.getInventory().setChestplate(item);
- continue;
- }
- if (item.getTypeId() == 300 || item.getTypeId() == 304 || item.getTypeId() == 308 || item.getTypeId() == 312 || item.getTypeId() == 316) {
- if (item.getTypeId() == 300) {
- LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
- if (c_ != null) {
- lam.setColor(c_);
- }
- item.setItemMeta(lam);
- }
- p.getInventory().setLeggings(item);
- continue;
- }
- if (item.getTypeId() == 301 || item.getTypeId() == 305 || item.getTypeId() == 309 || item.getTypeId() == 313 || item.getTypeId() == 317) {
- if (item.getTypeId() == 301) {
- LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
- if (c_ != null) {
- lam.setColor(c_);
- }
- item.setItemMeta(lam);
- }
- p.getInventory().setBoots(item);
- continue;
- }
- if (item.getType() != Material.AIR) {
- p.getInventory().addItem(item);
- }
- }
- }
- // p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()]));
- p.updateInventory();
-
- if (MinigamesAPI.getAPI().crackshot) {
- for (String t : tempguns) {
- CSUtility cs = new CSUtility();
- cs.giveWeapon(p, t, 1);
- }
- }
-
- Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
- public void run() {
- if (p != null) {
- int index = 0;
- for (PotionEffectType t : temppotions) {
- p.addPotionEffect(new PotionEffect(t, temppotions_duration.get(index), temppotions_lv.get(index)));
- index++;
- }
- }
- }
- }, 10L);
-
- }
-
- /**
- * Sets the current class of a player
- *
- * @param classname
- * the INTERNAL classname
- * @param player
- */
- public void setClass(String internalname, String player, boolean money) {
- for (String c : pli.getAClasses().keySet()) {
- if (c.toLowerCase().equalsIgnoreCase(internalname.toLowerCase())) {
- internalname = c;
- }
- }
- if (!kitPlayerHasPermission(internalname, Bukkit.getPlayer(player))) {
- Bukkit.getPlayer(player).sendMessage(pli.getMessagesConfig().no_perm);
- return;
- }
- boolean continue_ = true;
- if (money) {
- if (kitRequiresMoney(internalname)) {
- continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname);
- }
- }
- if (continue_) {
- pli.setPClass(player, this.getClassByInternalname(internalname));
- Bukkit.getPlayer(player).sendMessage(pli.getMessagesConfig().set_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(internalname).getName())));
- }
- }
-
- public String getInternalNameByName(String name) {
- for (AClass ac : pli.getAClasses().values()) {
- if (ac.getName().equalsIgnoreCase(name)) {
- return ac.getInternalName();
- }
- }
- return "default";
- }
-
- public AClass getClassByInternalname(String internalname) {
- for (AClass ac : pli.getAClasses().values()) {
- if (ac.getInternalName().equalsIgnoreCase(internalname)) {
- return ac;
- }
- }
- return null;
- }
-
- public boolean hasClass(String player) {
- return pli.getPClasses().containsKey(player);
- }
-
- public String getSelectedClass(String player) {
- if (hasClass(player)) {
- return pli.getPClasses().get(player).getInternalName();
- }
- return "default";
- }
-
- public void loadClasses() {
- Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
- public void run() {
- FileConfiguration config = pli.getClassesConfig().getConfig();
- if (config.isSet("config.kits")) {
- for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) {
- AClass n;
- if (config.isSet("config.kits." + aclass + ".icon")) {
- n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0));
- } else {
- n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")));
- }
- pli.addAClass(config.getString("config.kits." + aclass + ".name"), n);
- if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) {
- plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!");
- }
- }
- }
- }
- }, 20L);
- }
-
- /**
- * Please use new Classes().loadClasses();
- *
- * @param plugin
- */
- @Deprecated
- public static void loadClasses(final JavaPlugin plugin) {
- Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
- public void run() {
- FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getClassesConfig().getConfig();
- if (config.isSet("config.kits")) {
- for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) {
- AClass n;
- if (config.isSet("config.kits." + aclass + ".icon")) {
- n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0));
- } else {
- n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")));
- }
- // pli.addAClass(aclass, n);
- MinigamesAPI.getAPI().getPluginInstance(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n);
- if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) {
- plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!");
- }
- }
- }
- }
- }, 20L);
- }
-
- /**
- * Returns whether the kit requires money to use it
- *
- * @param kit
- * Internal name of the kit
- * @return
- */
- public boolean kitRequiresMoney(String kit) {
- return pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money");
- }
-
- /**
- * Gives the player the kit if he has enough money to buy it
- *
- * @param p
- * Player to give the kit to
- * @param kit
- * Internal name of the kit
- * @return
- */
- public boolean kitTakeMoney(Player p, String kit) {
- // Credits
- if (plugin.getConfig().getBoolean("config.use_credits_instead_of_money_for_kits")) {
- String uuid = p.getUniqueId().toString();
- int points = 0;
- if (!MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points")) {
- points = pli.getStatsInstance().getPoints(p.getName());
- MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points);
- MinigamesAPI.getAPI().statsglobal.saveConfig();
- } else {
- points = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points");
- }
- if (plugin.getConfig().getBoolean("config.buy_classes_forever")) {
- ClassesConfig cl = pli.getClassesConfig();
- if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) {
- int money = pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount");
- if (points >= money) {
- MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money);
- MinigamesAPI.getAPI().statsglobal.saveConfig();
- cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true);
- cl.saveConfig();
- p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money)));
- } else {
- p.sendMessage(pli.getMessagesConfig().not_enough_money);
- return false;
- }
- } else {
- return true;
- }
- } else {
- if (hasClass(p.getName())) {
- if (getSelectedClass(p.getName()).equalsIgnoreCase(kit)) {
- return false;
- }
- }
- ClassesConfig config = pli.getClassesConfig();
- int money = config.getConfig().getInt("config.kits." + kit + ".money_amount");
- if (points >= money) {
- MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money);
- MinigamesAPI.getAPI().statsglobal.saveConfig();
- p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money)));
- } else {
- p.sendMessage(pli.getMessagesConfig().not_enough_money);
- return false;
- }
- }
- return true;
- }
-
- // Money (economy)
- if (!MinigamesAPI.getAPI().economy) {
- plugin.getLogger().warning("Economy is turned OFF. You can turn it on in the config.");
- return false;
- }
- if (MinigamesAPI.economy) {
- if (plugin.getConfig().getBoolean("config.buy_classes_forever")) {
- ClassesConfig cl = pli.getClassesConfig();
- if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) {
- int money = pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount");
- if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) {
- EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money);
- if (!r.transactionSuccess()) {
- p.sendMessage(String.format("An error occured: %s", r.errorMessage));
- return false;
- }
- cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true);
- cl.saveConfig();
- p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money)));
- } else {
- p.sendMessage(pli.getMessagesConfig().not_enough_money);
- return false;
- }
- } else {
- return true;
- }
- } else {
- if (hasClass(p.getName())) {
- if (getSelectedClass(p.getName()).equalsIgnoreCase(kit)) {
- return false;
- }
- if (kitRequiresMoney(kit)) {
- Util.sendMessage(plugin, p, pli.getMessagesConfig().kit_warning);
- }
- }
- ClassesConfig config = pli.getClassesConfig();
- int money = config.getConfig().getInt("config.kits." + kit + ".money_amount");
- if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) {
- EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money);
- if (!r.transactionSuccess()) {
- p.sendMessage(String.format("An error occured: %s", r.errorMessage));
- return false;
- }
- p.sendMessage(pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(kit).getName())).replaceAll("", Integer.toString(money)));
- } else {
- p.sendMessage(pli.getMessagesConfig().not_enough_money);
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
-
- }
-
- public boolean kitPlayerHasPermission(String kit, Player p) {
- if (!pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission")) {
- return true;
- } else {
- if (p.hasPermission(pli.getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node"))) {
- return true;
- } else {
- return false;
- }
- }
- }
+import net.milkbowl.vault.economy.EconomyResponse;
+/**
+ * Classes helper.
+ *
+ * @author instancelabs
+ */
+public class Classes
+{
+
+ JavaPlugin plugin;
+ PluginInstance pli;
+ public HashMap lasticonm = new HashMap<>();
+
+ public Classes(final JavaPlugin plugin)
+ {
+ this.plugin = plugin;
+ this.pli = MinigamesAPI.getAPI().getPluginInstance(plugin);
+ }
+
+ public Classes(final PluginInstance pli, final JavaPlugin plugin)
+ {
+ this.plugin = plugin;
+ this.pli = pli;
+ }
+
+ public void openGUI(final String p)
+ {
+ final Classes cl = this;
+ IconMenu iconm;
+ final int mincount = this.pli.getAClasses().keySet().size();
+ if (!Validator.isPlayerOnline(p))
+ {
+ return;
+ }
+ final Player player = Bukkit.getPlayerExact(p);
+ if (this.lasticonm.containsKey(p))
+ {
+ iconm = this.lasticonm.get(p);
+ }
+ else
+ {
+ iconm = new IconMenu(this.pli.getMessagesConfig().classes_item, (9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS) > mincount - 1)
+ ? 9 * this.plugin.getConfig().getInt(ArenaConfigStrings.CONFIG_CLASSES_GUI_ROWS) : Math.round(mincount / 9) * 9 + 9, event -> {
+ if (event.getPlayer().getName().equalsIgnoreCase(p))
+ {
+ if (Classes.this.pli.global_players.containsKey(p))
+ {
+ if (Classes.this.pli.getArenas().contains(Classes.this.pli.global_players.get(p)))
+ {
+ final String d = event.getName();
+ final Player p1 = event.getPlayer();
+ if (Classes.this.pli.getAClasses().containsKey(d))
+ {
+ cl.setClass(Classes.this.pli.getClassesHandler().getInternalNameByName(d), p1.getName(), true);
+ }
+ }
+ }
+ }
+ event.setWillClose(true);
+ }, this.plugin);
+
+ int c = 0;
+ for (final String ac : this.pli.getAClasses().keySet())
+ {
+ final AClass ac_ = this.pli.getAClasses().get(ac);
+ if (ac_.isEnabled())
+ {
+ if (!this.pli.show_classes_without_usage_permission)
+ {
+ if (!this.kitPlayerHasPermission(ac_.getInternalName(), player))
+ {
+ continue;
+ }
+ }
+ int slot = c;
+ if (this.pli.getClassesConfig().getConfig().isSet("config.kits." + ac_.getInternalName() + ".slot"))
+ {
+ slot = this.pli.getClassesConfig().getConfig().getInt("config.kits." + ac_.getInternalName() + ".slot");
+ if (slot < 0 || slot > iconm.getSize() - 1)
+ {
+ slot = c;
+ }
+ }
+ iconm.setOption(slot, ac_.getIcon().clone(), ac_.getName(), this.pli.getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";"));
+ c++;
+ }
+ }
+ }
+
+ iconm.open(player);
+ this.lasticonm.put(p, iconm);
+ }
+
+ public void getClass(final String player)
+ {
+ if (!this.pli.getPClasses().containsKey(player))
+ {
+ ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items.");
+ return;
+ }
+ final AClass c = this.pli.getPClasses().get(player);
+ if (c == null)
+ {
+ ArenaLogger.debug(player + " didn't select any kit and the auto_add_default_kit option might be turned off, thus he won't get any starting items.");
+ return;
+ }
+ final Player p = Bukkit.getServer().getPlayer(player);
+ Util.clearInv(p);
+ final ArrayList items = new ArrayList<>(Arrays.asList(c.getItems()));
+ final ArrayList temp = new ArrayList<>(Arrays.asList(c.getItems()));
+ final ArrayList tempguns = new ArrayList<>();
+ final ArrayList temppotions = new ArrayList<>();
+ final ArrayList temppotions_lv = new ArrayList<>();
+ final ArrayList temppotions_duration = new ArrayList<>();
+
+ // crackshot support
+ for (final ItemStack item : temp)
+ {
+ if (item != null)
+ {
+ if (item.hasItemMeta())
+ {
+ if (item.getItemMeta().hasDisplayName())
+ {
+ if (item.getItemMeta().getDisplayName().startsWith("crackshot:"))
+ {
+ items.remove(item);
+ tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]);
+ }
+ else if (item.getItemMeta().getDisplayName().startsWith("potioneffect:"))
+ {
+ items.remove(item);
+ final String potioneffect = item.getItemMeta().getDisplayName().split(":")[1];
+ final String data = item.getItemMeta().getDisplayName().split(":")[2];
+ final Integer time = Integer.parseInt(data.substring(0, data.indexOf("#")));
+ final Integer lv = Integer.parseInt(data.split("#")[1]);
+ if (PotionEffectType.getByName(potioneffect) != null)
+ {
+ temppotions.add(PotionEffectType.getByName(potioneffect));
+ temppotions_lv.add(lv);
+ temppotions_duration.add(time);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for (final ItemStack item : items)
+ {
+ if (item != null)
+ {
+ Color c_ = null;
+ if (item.hasItemMeta())
+ {
+ if (item.getItemMeta().hasDisplayName())
+ {
+ if (item.getItemMeta().getDisplayName().startsWith("#") && item.getItemMeta().getDisplayName().length() == 7)
+ {
+ c_ = Util.hexToRgb(item.getItemMeta().getDisplayName());
+ }
+ }
+ }
+ if (item.getTypeId() == 298 || item.getTypeId() == 302 || item.getTypeId() == 306 || item.getTypeId() == 310 || item.getTypeId() == 314)
+ {
+ if (item.getTypeId() == 298)
+ {
+ final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
+ if (c_ != null)
+ {
+ lam.setColor(c_);
+ }
+ item.setItemMeta(lam);
+ }
+ p.getInventory().setHelmet(item);
+ continue;
+ }
+ if (item.getTypeId() == 299 || item.getTypeId() == 303 || item.getTypeId() == 307 || item.getTypeId() == 311 || item.getTypeId() == 315)
+ {
+ if (item.getTypeId() == 299)
+ {
+ final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
+ if (c_ != null)
+ {
+ lam.setColor(c_);
+ }
+ item.setItemMeta(lam);
+ }
+ p.getInventory().setChestplate(item);
+ continue;
+ }
+ if (item.getTypeId() == 300 || item.getTypeId() == 304 || item.getTypeId() == 308 || item.getTypeId() == 312 || item.getTypeId() == 316)
+ {
+ if (item.getTypeId() == 300)
+ {
+ final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
+ if (c_ != null)
+ {
+ lam.setColor(c_);
+ }
+ item.setItemMeta(lam);
+ }
+ p.getInventory().setLeggings(item);
+ continue;
+ }
+ if (item.getTypeId() == 301 || item.getTypeId() == 305 || item.getTypeId() == 309 || item.getTypeId() == 313 || item.getTypeId() == 317)
+ {
+ if (item.getTypeId() == 301)
+ {
+ final LeatherArmorMeta lam = (LeatherArmorMeta) item.getItemMeta();
+ if (c_ != null)
+ {
+ lam.setColor(c_);
+ }
+ item.setItemMeta(lam);
+ }
+ p.getInventory().setBoots(item);
+ continue;
+ }
+ if (item.getType() != Material.AIR)
+ {
+ p.getInventory().addItem(item);
+ }
+ }
+ }
+ // p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()]));
+ p.updateInventory();
+
+ if (MinigamesAPI.getAPI().crackshotAvailable())
+ {
+ for (final String t : tempguns)
+ {
+ final CSUtility cs = new CSUtility();
+ cs.giveWeapon(p, t, 1);
+ }
+ }
+
+ Bukkit.getScheduler().runTaskLater(this.plugin, () -> {
+ if (p != null)
+ {
+ int index = 0;
+ for (final PotionEffectType t : temppotions)
+ {
+ p.addPotionEffect(new PotionEffect(t, temppotions_duration.get(index), temppotions_lv.get(index)));
+ index++;
+ }
+ }
+ }, 10L);
+
+ }
+
+ /**
+ * Sets the current class of a player
+ *
+ * @param iname
+ * the INTERNAL classname
+ * @param player
+ */
+ public void setClass(String iname, final String player, final boolean money)
+ {
+ String internalname = iname;
+ for (final String c : this.pli.getAClasses().keySet())
+ {
+ if (c.toLowerCase().equalsIgnoreCase(internalname.toLowerCase()))
+ {
+ internalname = c;
+ }
+ }
+ if (!this.kitPlayerHasPermission(internalname, Bukkit.getPlayer(player)))
+ {
+ Bukkit.getPlayer(player).sendMessage(this.pli.getMessagesConfig().no_perm);
+ return;
+ }
+ boolean continue_ = true;
+ if (money)
+ {
+ if (this.kitRequiresMoney(internalname))
+ {
+ continue_ = this.kitTakeMoney(Bukkit.getPlayer(player), internalname);
+ }
+ }
+ if (continue_)
+ {
+ final AClass classByInternalname = this.getClassByInternalname(internalname);
+ this.pli.setPClass(player, classByInternalname);
+ if (classByInternalname != null)
+ {
+ final String set_kit_msg = this.pli.getMessagesConfig().set_kit;
+ Bukkit.getPlayer(player)
+ .sendMessage(set_kit_msg.replaceAll("", ChatColor.translateAlternateColorCodes('&', classByInternalname.getName())));
+ }
+ }
+ }
+
+ public String getInternalNameByName(final String name)
+ {
+ for (final AClass ac : this.pli.getAClasses().values())
+ {
+ if (ac.getName().equalsIgnoreCase(name))
+ {
+ return ac.getInternalName();
+ }
+ }
+ return "default";
+ }
+
+ public AClass getClassByInternalname(final String internalname)
+ {
+ for (final AClass ac : this.pli.getAClasses().values())
+ {
+ if (ac.getInternalName().equalsIgnoreCase(internalname))
+ {
+ return ac;
+ }
+ }
+ return null;
+ }
+
+ public boolean hasClass(final String player)
+ {
+ return this.pli.getPClasses().containsKey(player);
+ }
+
+ public String getSelectedClass(final String player)
+ {
+ if (this.hasClass(player))
+ {
+ return this.pli.getPClasses().get(player).getInternalName();
+ }
+ return "default";
+ }
+
+ public void loadClasses()
+ {
+ Bukkit.getScheduler().runTaskLater(this.plugin, () -> {
+ final FileConfiguration config = Classes.this.pli.getClassesConfig().getConfig();
+ if (config.isSet("config.kits"))
+ {
+ for (final String aclass : config.getConfigurationSection("config.kits.").getKeys(false))
+ {
+ AClass n;
+ if (config.isSet("config.kits." + aclass + ".icon"))
+ {
+ n = new AClass(Classes.this.plugin, config.getString("config.kits." + aclass + ".name"), aclass,
+ config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true,
+ Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0));
+ }
+ else
+ {
+ n = new AClass(Classes.this.plugin, config.getString("config.kits." + aclass + ".name"), aclass,
+ config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true,
+ Util.parseItems(config.getString("config.kits." + aclass + ".items")));
+ }
+ Classes.this.pli.addAClass(config.getString("config.kits." + aclass + ".name"), n);
+ if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore"))
+ {
+ Classes.this.plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!");
+ }
+ }
+ }
+ }, 20L);
+ }
+
+ /**
+ * Please use new Classes().loadClasses();
+ *
+ * @param plugin
+ */
+ @Deprecated
+ public static void loadClasses(final JavaPlugin plugin)
+ {
+ Bukkit.getScheduler().runTaskLater(plugin, () -> {
+ final FileConfiguration config = MinigamesAPI.getAPI().getPluginInstance(plugin).getClassesConfig().getConfig();
+ if (config.isSet("config.kits"))
+ {
+ for (final String aclass : config.getConfigurationSection("config.kits.").getKeys(false))
+ {
+ AClass n;
+ if (config.isSet("config.kits." + aclass + ".icon"))
+ {
+ n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass,
+ config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true,
+ Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0));
+ }
+ else
+ {
+ n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass,
+ config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true,
+ Util.parseItems(config.getString("config.kits." + aclass + ".items")));
+ }
+ // pli.addAClass(aclass, n);
+ MinigamesAPI.getAPI().getPluginInstance(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n);
+ if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore"))
+ {
+ plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!");
+ }
+ }
+ }
+ }, 20L);
+ }
+
+ /**
+ * Returns whether the kit requires money to use it
+ *
+ * @param kit
+ * Internal name of the kit
+ * @return
+ */
+ public boolean kitRequiresMoney(final String kit)
+ {
+ return this.pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money");
+ }
+
+ /**
+ * Gives the player the kit if he has enough money to buy it
+ *
+ * @param p
+ * Player to give the kit to
+ * @param kit
+ * Internal name of the kit
+ * @return
+ */
+ public boolean kitTakeMoney(final Player p, final String kit)
+ {
+ // Credits
+ if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_USE_CREADITS_INSTEAD_MONEY_FOR_KITS))
+ {
+ final String uuid = p.getUniqueId().toString();
+ int points = 0;
+ if (!MinigamesAPI.getAPI().statsglobal.getConfig().isSet("players." + uuid + ".points"))
+ {
+ points = this.pli.getStatsInstance().getPoints(p.getName());
+ MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points);
+ MinigamesAPI.getAPI().statsglobal.saveConfig();
+ }
+ else
+ {
+ points = MinigamesAPI.getAPI().statsglobal.getConfig().getInt("players." + uuid + ".points");
+ }
+ if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUY_CLASSES_FOREVER))
+ {
+ final ClassesConfig cl = this.pli.getClassesConfig();
+ if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit))
+ {
+ final int money = this.pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount");
+ if (points >= money)
+ {
+ MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money);
+ MinigamesAPI.getAPI().statsglobal.saveConfig();
+ cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true);
+ cl.saveConfig();
+ p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName()))
+ .replaceAll("", Integer.toString(money)));
+ }
+ else
+ {
+ p.sendMessage(this.pli.getMessagesConfig().not_enough_money);
+ return false;
+ }
+ }
+ else
+ {
+ return true;
+ }
+ }
+ else
+ {
+ if (this.hasClass(p.getName()))
+ {
+ if (this.getSelectedClass(p.getName()).equalsIgnoreCase(kit))
+ {
+ return false;
+ }
+ }
+ final ClassesConfig config = this.pli.getClassesConfig();
+ final int money = config.getConfig().getInt("config.kits." + kit + ".money_amount");
+ if (points >= money)
+ {
+ MinigamesAPI.getAPI().statsglobal.getConfig().set("players." + uuid + ".points", points - money);
+ MinigamesAPI.getAPI().statsglobal.saveConfig();
+ p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName()))
+ .replaceAll("", Integer.toString(money)));
+ }
+ else
+ {
+ p.sendMessage(this.pli.getMessagesConfig().not_enough_money);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ MinigamesAPI.getAPI();
+ // Money (economy)
+ if (!MinigamesAPI.getAPI().economyAvailable())
+ {
+ this.plugin.getLogger().warning("Economy is turned OFF. You can turn it on in the config.");
+ return false;
+ }
+ if (MinigamesAPI.getAPI().economyAvailable())
+ {
+ if (this.plugin.getConfig().getBoolean(ArenaConfigStrings.CONFIG_BUY_CLASSES_FOREVER))
+ {
+ final ClassesConfig cl = this.pli.getClassesConfig();
+ if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit))
+ {
+ final int money = this.pli.getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount");
+ MinigamesAPI.getAPI();
+ if (MinigamesAPI.econ.getBalance(p.getName()) >= money)
+ {
+ MinigamesAPI.getAPI();
+ final EconomyResponse r = MinigamesAPI.econ.withdrawPlayer(p.getName(), money);
+ if (!r.transactionSuccess())
+ {
+ p.sendMessage(String.format("An error occured: %s", r.errorMessage));
+ return false;
+ }
+ cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true);
+ cl.saveConfig();
+ p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName()))
+ .replaceAll("", Integer.toString(money)));
+ }
+ else
+ {
+ p.sendMessage(this.pli.getMessagesConfig().not_enough_money);
+ return false;
+ }
+ }
+ else
+ {
+ return true;
+ }
+ }
+ else
+ {
+ if (this.hasClass(p.getName()))
+ {
+ if (this.getSelectedClass(p.getName()).equalsIgnoreCase(kit))
+ {
+ return false;
+ }
+ if (this.kitRequiresMoney(kit))
+ {
+ Util.sendMessage(this.plugin, p, this.pli.getMessagesConfig().kit_warning);
+ }
+ }
+ final ClassesConfig config = this.pli.getClassesConfig();
+ final int money = config.getConfig().getInt("config.kits." + kit + ".money_amount");
+ MinigamesAPI.getAPI();
+ if (MinigamesAPI.econ.getBalance(p.getName()) >= money)
+ {
+ MinigamesAPI.getAPI();
+ final EconomyResponse r = MinigamesAPI.econ.withdrawPlayer(p.getName(), money);
+ if (!r.transactionSuccess())
+ {
+ p.sendMessage(String.format("An error occured: %s", r.errorMessage));
+ return false;
+ }
+ p.sendMessage(this.pli.getMessagesConfig().successfully_bought_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', this.getClassByInternalname(kit).getName()))
+ .replaceAll("", Integer.toString(money)));
+ }
+ else
+ {
+ p.sendMessage(this.pli.getMessagesConfig().not_enough_money);
+ return false;
+ }
+ }
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+
+ }
+
+ public boolean kitPlayerHasPermission(final String kit, final Player p)
+ {
+ if (!this.pli.getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission"))
+ {
+ return true;
+ }
+ else
+ {
+ if (p.hasPermission(this.pli.getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node")))
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ }
+
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java
new file mode 100644
index 00000000..4369b288
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/CommandStrings.java
@@ -0,0 +1,359 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+/**
+ * Common command strings.
+ *
+ * @author mepeisen
+ */
+public interface CommandStrings
+{
+
+ /**
+ * "/start" command.
+ */
+ String START = "start"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <start> ...
+ */
+ String GAME_START = "start"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setspawn> ...
+ */
+ String GAME_SET_SPAWN = "setspawn"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setspecspawn> ...
+ */
+ String GAME_SET_SPEC_SPAWN = "setspecspawn"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setlobby> ...
+ */
+ String GAME_SET_LOBBY = "setlobby"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setmainlobby> ...
+ */
+ String GAME_SET_MAINLOBBY = "setmainlobby"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setbounds> ...
+ */
+ String GAME_SET_BOUNDS = "setbounds"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setlobbybounds> ...
+ */
+ String GAME_SET_LOBBY_BOUNDS = "setlobbybounds"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setspecbounds> ...
+ */
+ String GAME_SET_SPEC_BOUNDS = "setspecbounds"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <savearena> ...
+ */
+ String GAME_SAVE_ARENA = "savearena"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <save> ...
+ */
+ @Deprecated
+ String GAME_SAVE = "save"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setmaxplayers> ...
+ */
+ String GAME_SET_MAX_PLAYERS = "setmaxplayers"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setminplayers> ...
+ */
+ String GAME_SET_MIN_PLAYERS = "setminplayers"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setarenavip> ...
+ */
+ String GAME_SET_ARENA_VIP = "setarenavip"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setvip> ...
+ */
+ @Deprecated
+ String GAME_SET_VIP = "setvip"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <join> ...
+ */
+ String GAME_JOIN = "join"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <leave> ...
+ */
+ String GAME_LEAVE = "leave"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <stop> ...
+ */
+ String GAME_STOP = "stop"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <stopall> ...
+ */
+ String GAME_STOP_ALL = "stopall"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <removearena> ...
+ */
+ String GAME_REMOVE_ARENA = "removearena"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <removespawn> ...
+ */
+ String GAME_REMOVE_SPAWN = "removespawn"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setskull> ...
+ */
+ String GAME_SET_SKULL = "setskull"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setenabled> ...
+ */
+ String GAME_SET_ENABLED = "setenabled"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setshowscoreboard> ...
+ */
+ String GAME_SET_SHOW_SCOREBOARD = "setshowscoreboard"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <reset> ...
+ */
+ String GAME_RESET = "reset"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setauthor> ...
+ */
+ String GAME_SET_AUTHOR = "setauthor"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setdescription> ...
+ */
+ String GAME_SET_DESCRIPTION = "setdescription"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <setdisplayname> ...
+ */
+ String GAME_SET_DISPLAYNAME = "setdisplayname"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <kit> ...
+ */
+ String GAME_KIT = "kit"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <spectate> ...
+ */
+ String GAME_SPECTATE = "spectate"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <shop> ...
+ */
+ String GAME_SHOP = "shop"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <leaderboards> ...
+ */
+ String GAME_LEADER_BOARDS = "leaderboards"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <lb> ...
+ */
+ String GAME_LB = "lb"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <top> ...
+ */
+ @Deprecated
+ String GAME_TOP = "top"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <stats> ...
+ */
+ String GAME_STATS = "stats"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <sethologram> ...
+ */
+ String GAME_SET_HOLOGRAM = "sethologram"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <listholograms> ...
+ */
+ String GAME_LIST_HOLOGRAMS = "listholograms"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <removehologram> ...
+ */
+ String GAME_REMOVE_HOLOGRAM = "removehologram"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <help> ...
+ */
+ String GAME_HELP = "help"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <list> ...
+ */
+ String GAME_LIST = "list"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <reload> ...
+ */
+ String GAME_RELOAD = "reload"; //$NON-NLS-1$
+
+ // old commands
+
+ /**
+ * Command action: "/minigame <createarena> ...
+ * @deprecated removed in 1.5.0
+ */
+ @Deprecated
+ String GAME_CREATE_ARENA = "createarena"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/minigame <endall> ...
+ * @deprecated removed in 1.5.0
+ */
+ @Deprecated
+ String GAME_END_ALL = "endall"; //$NON-NLS-1$
+
+ // party commands
+
+ /**
+ * "/party" command.
+ */
+ String PARTY = "party"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <invite> ...
+ */
+ String PARTY_INVITE = "invite"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <accept> ...
+ */
+ String PARTY_ACCEPT = "accept"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <kick> ...
+ */
+ String PARTY_KICK = "kick"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <list> ...
+ */
+ String PARTY_LIST = "list"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <disband> ...
+ */
+ String PARTY_DISBAND = "disband"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/party <leave> ...
+ */
+ String PARTY_LEAVE = "leave"; //$NON-NLS-1$
+
+ // minigames api commands
+
+ /**
+ * "/mapi" command.
+ */
+ String MAPI = "mapi"; //$NON-NLS-1$
+
+ /**
+ * "/mgapi" command.
+ */
+ String MGAPI = "mgapi"; //$NON-NLS-1$
+
+ /**
+ * "/mglib" command.
+ */
+ String MGLIB = "mglib"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <info> ...
+ */
+ String MGLIB_INFO = "info"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <debug> ...
+ */
+ String MGLIB_DEBUG = "debug"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <list> ...
+ */
+ String MGLIB_LIST = "list"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <title> ...
+ */
+ String MGLIB_TITLE = "title"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <subtitle> ...
+ */
+ String MGLIB_SUBTITLE = "subtitle"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <signs> ...
+ */
+ String MGLIB_SIGNS = "signs"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <hologram> ...
+ */
+ String MGLIB_HOLOGRAM = "hologram"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <statshologram> ...
+ */
+ String MGLIB_STATS_HOLOGRAM = "statshologram"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <gamemodetest> ...
+ */
+ String MGLIB_GAMEMODE_TEST = "gamemodetest"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <bungeetest> ...
+ */
+ String MGLIB_BUNGEE_TEST = "bungeetest"; //$NON-NLS-1$
+
+ /**
+ * Command action: "/mglib <join> ...
+ */
+ String MGLIB_JOIN = "join"; //$NON-NLS-1$
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java
index e5484142..a5c63c26 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Effects.java
@@ -1,3 +1,17 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.lang.reflect.Constructor;
@@ -6,6 +20,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
@@ -19,452 +34,561 @@
import com.comze_instancelabs.minigamesapi.util.ParticleEffectNew;
import com.comze_instancelabs.minigamesapi.util.Validator;
-public class Effects {
-
- public static int getClientProtocolVersion(Player p) {
- int ret = 0;
- try {
- if (!MinigamesAPI.getAPI().version.equalsIgnoreCase("v1_8_r1")) {
- Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- playerConnection.setAccessible(true);
- Object playerConInstance = playerConnection.get(getHandle.invoke(p));
- Field networkManager = playerConInstance.getClass().getField("networkManager");
- networkManager.setAccessible(true);
- Object networkManagerInstance = networkManager.get(playerConInstance);
- Method getVersion = networkManagerInstance.getClass().getMethod("getVersion");
- Object version = getVersion.invoke(networkManagerInstance);
- ret = (Integer) version;
- }
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- return ret;
- }
-
- /**
- * Shows the particles of a redstone block breaking
- *
- * @param p
- */
- public static void playBloodEffect(Player p) {
- p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152);
- }
-
- public static void playEffect(Arena a, Location l, String effectname) {
- for (String p_ : a.getAllPlayers()) {
- if (Validator.isPlayerOnline(p_)) {
- Player p = Bukkit.getPlayer(p_);
- ParticleEffectNew eff = ParticleEffectNew.valueOf(effectname);
- eff.setId(152);
- eff.animateReflected(p, l, 1F, 3);
- }
- }
- }
-
- public static BukkitTask playFakeBed(Arena a, Player p) {
- return playFakeBed(a, p, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ());
- }
-
- public static BukkitTask playFakeBed(final Arena a, final Player p, int x, int y, int z) {
- try {
- final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- playerConnection.setAccessible(true);
- final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet"));
-
- Constructor packetPlayOutNamedEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutNamedEntitySpawn").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityHuman"));
- Constructor packetPlayOutBedConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutBed").getConstructor();
-
- final int id = -p.getEntityId() - 1000;
-
- final Object packet = packetPlayOutNamedEntityConstr.newInstance(getHandle.invoke(p));
- setValue(packet, "a", id);
-
- final Object packet_ = packetPlayOutBedConstr.newInstance();
- setValue(packet_, "a", id);
- setValue(packet_, "b", x);
- setValue(packet_, "c", y);
- setValue(packet_, "d", z);
-
- for (String p_ : a.getAllPlayers()) {
- Player p__ = Bukkit.getPlayer(p_);
- sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet);
- sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet_);
- }
-
- // Move the effect (fake player) to 0 0 0 after 4 seconds
- final ArrayList tempp = new ArrayList(a.getAllPlayers());
- final World currentworld = p.getWorld();
- return Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() {
- public void run() {
- try {
- setValue(packet_, "a", id);
- setValue(packet_, "b", 0);
- setValue(packet_, "c", 0);
- setValue(packet_, "d", 0);
- for (String p_ : tempp) {
- if (Validator.isPlayerOnline(p_)) {
- Player p__ = Bukkit.getPlayer(p_);
- if (p__.getWorld() == currentworld) {
- sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet);
- sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packet_);
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }, 20L * 4);
- } catch (Exception e) {
- System.out.println("Failed playing fakebed effect: " + e.getMessage());
- }
- return null;
- }
-
- public static void setValue(Object instance, String fieldName, Object value) throws Exception {
- Field field = instance.getClass().getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(instance, value);
- }
-
- /**
- * Respawns a player using moveToWorld (which among others also sends a respawn packet)
- *
- * @param p
- * Player to send it to
- * @param plugin
- */
- public static void playRespawn(final Player p, JavaPlugin plugin) {
- Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
- public void run() {
- try {
- final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- final Field minecraftServer = playerConnection.get(getHandle.invoke(p)).getClass().getDeclaredField("minecraftServer");
- minecraftServer.setAccessible(true);
-
- Object nmsMcServer = minecraftServer.get(playerConnection.get(getHandle.invoke(p)));
- Object playerlist = nmsMcServer.getClass().getDeclaredMethod("getPlayerList").invoke(nmsMcServer);
- Method moveToWorld = playerlist.getClass().getMethod("moveToWorld", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer"), int.class, boolean.class);
- moveToWorld.invoke(playerlist, getHandle.invoke(p), 0, false);
- } catch (Exception e) {
- System.out.println("Failed additional respawn packet: " + e.getMessage());
- }
- }
- }, 1L);
- }
-
- // TODO Unused right now
- public void playAura(Player p, int cr) {
- int cradius_s = cr * cr;
- Location start = p.getLocation();
- int x = start.getBlockX();
- int y = start.getBlockY();
- int z = start.getBlockZ();
- for (int x_ = -cr; x_ <= cr; x_++) {
- for (int z_ = -cr; z_ <= cr; z_++) {
- int t = (x_ * x_) + (z_ * z_);
- if (t >= cradius_s && t <= (cradius_s + 90)) {
- p.playEffect(new Location(start.getWorld(), x - x_, y, z - z_), Effect.POTION_BREAK, 5);
- }
- }
- }
- }
-
- /**
- * Plays a title/subtitle
- *
- * @param player
- * Player to play the title to
- * @param title
- * The title string
- * @param enumindex
- * The enum index, can be 0 for title, 1 for subtitle, 4 for reset
- */
- public static void playTitle(Player player, String title, int enumindex) {
- if (enumindex > 4) {
- enumindex = 0;
- }
- try {
- final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- playerConnection.setAccessible(true);
- final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet"));
- final Method a = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".ChatSerializer").getMethod("a", String.class);
-
- Constructor packetPlayOutTitleConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutTitle").getConstructor();
-
- final Object packet = packetPlayOutTitleConstr.newInstance();
- setValue(packet, "a", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EnumTitleAction").getEnumConstants()[enumindex]);
- setValue(packet, "b", a.invoke(null, "{text:\"" + title + "\"}"));
-
- sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet);
- } catch (Exception e) {
- System.out.println("Failed sending title packet: " + e.getMessage());
- }
- }
-
- static HashMap effectlocd = new HashMap();
- static HashMap effectlocd_taskid = new HashMap();
-
- /**
- * Sends a hologram to a player
- *
- * @param p
- * Player to send the hologram to
- * @param l
- * Location where the hologram will spawn (and slowly move down)
- * @param text
- * Hologram text
- * @param moveDown
- * Whether to play a moving down animation
- * @param removeAfterCooldown
- * Whether to remove the hologram after a few seconds or not
- * @return
- */
- public static ArrayList playHologram(final Player p, final Location l, String text, boolean moveDown, boolean removeAfterCooldown) {
- ArrayList ret = new ArrayList();
- if (MinigamesAPI.getAPI().version.equalsIgnoreCase("v1_8_r1")) {
- try {
- final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- playerConnection.setAccessible(true);
- final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet"));
-
- Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".CraftWorld");
- Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".World");
- Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Entity");
- Method getWorldHandle = craftw.getDeclaredMethod("getHandle");
- Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld()));
- final Constructor packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class);
- final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntityLiving").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityLiving"));
- final Constructor packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity);
- final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class);
- final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityVelocity").getConstructor(int.class, double.class, double.class, double.class);
-
- // EntityArmorStand
- Constructor entityArmorStandConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityArmorStand").getConstructor(w);
- final Object entityArmorStand = entityArmorStandConstr.newInstance(worldServer);
- final Method setLoc2 = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class);
- setLoc2.invoke(entityArmorStand, l.getX(), l.getY() - 1D, l.getZ(), 0F, 0F);
- Method setCustomName = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class);
- setCustomName.invoke(entityArmorStand, text);
- Method setCustomNameVisible = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class);
- setCustomNameVisible.invoke(entityArmorStand, true);
- Method getArmorStandId = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
- final int armorstandId = (Integer) (getArmorStandId.invoke(entityArmorStand));
- Method setInvisble = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class);
- setInvisble.invoke(entityArmorStand, true);
-
- effectlocd.put(armorstandId, 12); // send move packet 12 times
-
- // Send EntityArmorStand packet
- Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityArmorStand);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket);
-
- // Send velocity packets to move the entities slowly down
- if (moveDown) {
- effectlocd_taskid.put(armorstandId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() {
- public void run() {
- try {
- int i = effectlocd.get(armorstandId);
- Object packet = packetPlayOutEntityVelocity.newInstance(armorstandId, 0D, -0.05D, 0D);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet);
- if (i < -1) {
- int taskid = effectlocd_taskid.get(armorstandId);
- effectlocd_taskid.remove(armorstandId);
- effectlocd.remove(armorstandId);
- Bukkit.getScheduler().cancelTask(taskid);
- return;
- }
- effectlocd.put(armorstandId, effectlocd.get(armorstandId) - 1);
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- }
- }, 2L, 2L).getTaskId());
- }
-
- // Remove both entities (and thus the hologram) after 2 seconds
- if (removeAfterCooldown) {
- Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() {
- public void run() {
- try {
- Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance((Object) new int[] { armorstandId });
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket);
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- }
- }, 20L * 2);
- }
-
- ret.add(armorstandId);
-
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- return ret;
- }
- try {
- // If player is on 1.8, we'll have to use armor stands, otherwise just use the old 1.7 technique
- final boolean playerIs1_8 = getClientProtocolVersion(p) > 5;
-
- final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".entity.CraftPlayer").getMethod("getHandle");
- final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityPlayer").getField("playerConnection");
- playerConnection.setAccessible(true);
- final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Packet"));
-
- Class craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().version + ".CraftWorld");
- Class w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".World");
- Class entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".Entity");
- Method getWorldHandle = craftw.getDeclaredMethod("getHandle");
- Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld()));
- final Constructor packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class);
- final Constructor packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutSpawnEntityLiving").getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityLiving"));
- final Constructor packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity);
- final Constructor packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityDestroy").getConstructor(int[].class);
- final Constructor packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".PacketPlayOutEntityVelocity").getConstructor(int.class, double.class, double.class, double.class);
-
- // WitherSkull
- Constructor witherSkullConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityWitherSkull").getConstructor(w);
- final Object witherSkull = witherSkullConstr.newInstance(worldServer);
- final Method setLoc = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class);
- setLoc.invoke(witherSkull, l.getX(), l.getY() + 33D, l.getZ(), 0F, 0F);
- Method getWitherSkullId = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
- final int witherSkullId = (Integer) (getWitherSkullId.invoke(witherSkull));
-
- // EntityHorse
- Constructor entityHorseConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().version + ".EntityHorse").getConstructor(w);
- final Object entityHorse = entityHorseConstr.newInstance(worldServer);
- final Method setLoc2 = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class);
- setLoc2.invoke(entityHorse, l.getX(), l.getY() + (playerIs1_8 ? -1D : 33D), l.getZ(), 0F, 0F);
- Method setAge = entityHorse.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setAge", int.class);
- setAge.invoke(entityHorse, -1000000);
- Method setCustomName = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class);
- setCustomName.invoke(entityHorse, text);
- Method setCustomNameVisible = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class);
- setCustomNameVisible.invoke(entityHorse, true);
- Method getHorseId = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
- final int horseId = (Integer) (getHorseId.invoke(entityHorse));
-
- if (playerIs1_8) {
- // Set horse (later armor stand) invisible
- Method setInvisble = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class);
- setInvisble.invoke(entityHorse, true);
- }
-
- effectlocd.put(horseId, 12); // send move packet 12 times
-
- // Send Witherskull+EntityHorse packet
- Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityHorse);
- if (playerIs1_8) {
- // Set entity id to 30 (armor stand):
- setValue(horsePacket, "b", 30);
- // Fix datawatcher values to prevent crashes (ofc armor stands expect other data than horses):
- Field datawatcher = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("datawatcher");
- datawatcher.setAccessible(true);
- Object datawatcherInstance = datawatcher.get(entityHorse);
- Field d = datawatcherInstance.getClass().getDeclaredField("d");
- d.setAccessible(true);
- Map dmap = (Map) d.get(datawatcherInstance);
- dmap.remove(10);
- // These are the Rotation ones
- dmap.remove(11);
- dmap.remove(12);
- dmap.remove(13);
- dmap.remove(14);
- dmap.remove(15);
- dmap.remove(16);
- Method a = datawatcherInstance.getClass().getDeclaredMethod("a", int.class, Object.class);
- a.invoke(datawatcherInstance, 10, (byte) 0);
- }
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket);
- if (!playerIs1_8) {
- Object witherPacket = packetPlayOutSpawnEntityConstr.newInstance(witherSkull, 64);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), witherPacket);
- }
-
- // Send attach packet
- if (!playerIs1_8) {
- Object attachPacket = packetPlayOutAttachEntityConstr.newInstance(0, entityHorse, witherSkull);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), attachPacket);
- }
-
- // Send velocity packets to move the entities slowly down
- if (moveDown) {
- effectlocd_taskid.put(horseId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), new Runnable() {
- public void run() {
- try {
- int i = effectlocd.get(horseId);
- Object packet = packetPlayOutEntityVelocity.newInstance(horseId, 0D, -0.05D, 0D);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet);
- if (!playerIs1_8) {
- Object packet2 = packetPlayOutEntityVelocity.newInstance(witherSkullId, 0D, -0.05D, 0D);
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet2);
- }
- if (i < -1) {
- int taskid = effectlocd_taskid.get(horseId);
- effectlocd_taskid.remove(horseId);
- effectlocd.remove(horseId);
- Bukkit.getScheduler().cancelTask(taskid);
- return;
- }
- effectlocd.put(horseId, effectlocd.get(horseId) - 1);
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- }
- }, 2L, 2L).getTaskId());
- }
-
- // Remove both entities (and thus the hologram) after 2 seconds
- if (removeAfterCooldown) {
- Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), new Runnable() {
- public void run() {
- try {
- Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance((Object) new int[] { witherSkullId, horseId });
- sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket);
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- }
- }, 20L * 2);
- }
-
- ret.add(witherSkullId);
- ret.add(horseId);
-
- } catch (Exception e) {
- if (MinigamesAPI.debug) {
- e.printStackTrace();
- }
- }
- return ret;
- }
-
- public static void sendGameModeChange(Player p, int gamemode) {
- // NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator");
-
- if (!MinigamesAPI.getAPI().version.startsWith("v1_8") && gamemode == 3) {
- return;
- }
-
- p.setGameMode(GameMode.getByValue(gamemode));
-
- }
+/**
+ * Particle/Animation helper.
+ *
+ * @author instancelabs
+ */
+public class Effects
+{
+
+ /**
+ * Shows the particles of a redstone block breaking, simulating a blood effect.
+ *
+ * @param p
+ * target player.
+ */
+ public static void playBloodEffect(final Player p)
+ {
+ p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152);
+ }
+
+ /**
+ * Plays an effect by name.
+ *
+ * @param a
+ * arena
+ * @param l
+ * target location
+ * @param effectname
+ * effect name.
+ */
+ public static void playEffect(final Arena a, final Location l, final String effectname)
+ {
+ for (final String p_ : a.getAllPlayers())
+ {
+ if (Validator.isPlayerOnline(p_))
+ {
+ final Player p = Bukkit.getPlayer(p_);
+ final ParticleEffectNew eff = ParticleEffectNew.valueOf(effectname);
+ eff.setId(55);
+ eff.animateReflected(p, l, 1F, 2);
+ }
+ }
+ }
+
+ /**
+ * Places a fake bed on the current player position.
+ *
+ * @param a
+ * arena
+ * @param p
+ * target player
+ * @return bukkit task that can be cancelled.
+ */
+ public static BukkitTask playFakeBed(final Arena a, final Player p)
+ {
+ return Effects.playFakeBed(a, p, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ());
+ }
+
+ /**
+ * Places a fake bed on the given position.
+ *
+ * @param a
+ * arena
+ * @param p
+ * target player
+ * @param x
+ * x-position
+ * @param y
+ * y-position
+ * @param z
+ * z-position
+ * @return bukkit task that can be cancelled.
+ */
+ public static BukkitTask playFakeBed(final Arena a, final Player p, final int x, final int y, final int z)
+ {
+ try
+ {
+ final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle");
+ final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection");
+ playerConnection.setAccessible(true);
+ final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet"));
+
+ final Constructor> packetPlayOutNamedEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutNamedEntitySpawn")
+ .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityHuman"));
+ final Constructor> packetPlayOutBedConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutBed").getConstructor();
+
+ final int id = -p.getEntityId() - 1000;
+
+ final Object packetNamedEntity = packetPlayOutNamedEntityConstr.newInstance(getHandle.invoke(p));
+ Effects.setValue(packetNamedEntity, "a", id);
+
+ final Object packetFakeBed = packetPlayOutBedConstr.newInstance();
+ Effects.setValue(packetFakeBed, "a", id);
+ final Object packetFakeBed2 = packetPlayOutBedConstr.newInstance();
+ Effects.setValue(packetFakeBed2, "a", id);
+ if (MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_8_R1))
+ {
+ final Class> bpClazz = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".BlockPosition");
+ final Constructor> ctor = bpClazz.getDeclaredConstructor(int.class, int.class, int.class);
+ Effects.setValue(packetFakeBed, "b", ctor.newInstance(x, y, z));
+
+ Effects.setValue(packetFakeBed2, "b", ctor.newInstance(0, 0, 0));
+ }
+ else
+ {
+ Effects.setValue(packetFakeBed, "b", x);
+ Effects.setValue(packetFakeBed, "c", y);
+ Effects.setValue(packetFakeBed, "d", z);
+ Effects.setValue(packetFakeBed2, "b", 0);
+ Effects.setValue(packetFakeBed2, "c", 0);
+ Effects.setValue(packetFakeBed2, "d", 0);
+ }
+
+ for (final String p_ : a.getAllPlayers())
+ {
+ final Player p__ = Bukkit.getPlayer(p_);
+ sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetNamedEntity);
+ sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetFakeBed);
+ }
+
+ // Move the effect (fake player) to 0 0 0 after 4 seconds
+ final ArrayList tempp = new ArrayList<>(a.getAllPlayers());
+ final World currentworld = p.getWorld();
+ return Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> {
+ try
+ {
+ for (final String p_ : tempp)
+ {
+ if (Validator.isPlayerOnline(p_))
+ {
+ final Player p__ = Bukkit.getPlayer(p_);
+ if (p__.getWorld() == currentworld)
+ {
+ sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetNamedEntity);
+ sendPacket.invoke(playerConnection.get(getHandle.invoke(p__)), packetFakeBed2);
+ }
+ }
+ }
+ }
+ catch (final Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }, 20L * 4);
+ }
+ catch (final Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed playing fakebed effect", e);
+ }
+ return null;
+ }
+
+ /**
+ * Sets private object value.
+ *
+ * @param instance
+ * object instance
+ * @param fieldName
+ * field name
+ * @param value
+ * new value
+ * @throws Exception
+ * thrown on problems setting the field.
+ */
+ private static void setValue(final Object instance, final String fieldName, final Object value) throws Exception
+ {
+ final Field field = instance.getClass().getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(instance, value);
+ }
+
+ /**
+ * Respawns a player using moveToWorld (which among others also sends a respawn packet)
+ *
+ * @param p
+ * Player to send it to
+ * @param plugin
+ */
+ public static void playRespawn(final Player p, final JavaPlugin plugin)
+ {
+ Bukkit.getScheduler().runTaskLater(plugin, () -> {
+ try
+ {
+ final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle");
+ final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection");
+ final Field minecraftServer = playerConnection.get(getHandle.invoke(p)).getClass().getDeclaredField("minecraftServer");
+ minecraftServer.setAccessible(true);
+
+ final Object nmsMcServer = minecraftServer.get(playerConnection.get(getHandle.invoke(p)));
+ final Object playerlist = nmsMcServer.getClass().getDeclaredMethod("getPlayerList").invoke(nmsMcServer);
+ final Method moveToWorld = playerlist.getClass().getMethod("moveToWorld", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer"),
+ int.class, boolean.class);
+ moveToWorld.invoke(playerlist, getHandle.invoke(p), 0, false);
+ }
+ catch (final Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed additional respawn packet", e);
+ }
+ }, 1L);
+ }
+
+ /**
+ * Plays a title/subtitle
+ *
+ * @param player
+ * Player to play the title to
+ * @param title
+ * The title string
+ * @param eindex
+ * The enum index, can be 0 for title, 1 for subtitle, 4 for reset
+ */
+ public static void playTitle(final Player player, final String title, int eindex)
+ {
+ int enumindex = eindex;
+ if (enumindex > 4)
+ {
+ enumindex = 0;
+ }
+ try
+ {
+ final Method getHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle");
+ final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection");
+ playerConnection.setAccessible(true);
+ final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet"));
+ Class> enumClass = null;
+ Object chatComp = null;
+ if (MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_8_R2))
+ {
+ Method a = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".ChatSerializer").getMethod("a", String.class);
+ enumClass = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EnumTitleAction");
+ chatComp = a.invoke(null, "{text:\"" + title + "\"}");
+ }
+ else
+ {
+ enumClass = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutTitle$EnumTitleAction");
+ chatComp = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".ChatComponentText").getConstructor(String.class).newInstance(title);
+ }
+
+ final Constructor> packetPlayOutTitleConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutTitle").getConstructor();
+ final Object packet = packetPlayOutTitleConstr.newInstance();
+ Effects.setValue(packet, "a", enumClass.getEnumConstants()[enumindex]);
+ Effects.setValue(packet, "b", chatComp);
+
+ sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet);
+ }
+ catch (final Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "Failed sending title packet", e);
+ }
+ }
+
+ static HashMap effectlocd = new HashMap<>();
+ static HashMap effectlocd_taskid = new HashMap<>();
+
+ /**
+ * Sends a hologram to a player
+ *
+ * @param p
+ * Player to send the hologram to
+ * @param l
+ * Location where the hologram will spawn (and slowly move down)
+ * @param text
+ * Hologram text
+ * @param moveDown
+ * Whether to play a moving down animation
+ * @param removeAfterCooldown
+ * Whether to remove the hologram after a few seconds or not
+ * @return ids
+ */
+ public static ArrayList playHologram(final Player p, final Location l, final String text, final boolean moveDown, final boolean removeAfterCooldown)
+ {
+ final ArrayList ret = new ArrayList<>();
+ if (MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7))
+ {
+ try
+ {
+ final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle");
+ final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection");
+ playerConnection.setAccessible(true);
+ final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet"));
+
+ final Class> craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".CraftWorld");
+ final Class> w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".World");
+ final Class> entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Entity");
+ final Method getWorldHandle = craftw.getDeclaredMethod("getHandle");
+ final Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld()));
+// Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntity").getConstructor(entity, int.class);
+ final Constructor> packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntityLiving")
+ .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityLiving"));
+// Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutAttachEntity").getConstructor(int.class, entity, entity);
+ final Constructor> packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityDestroy")
+ .getConstructor(int[].class);
+ final Constructor> packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityVelocity")
+ .getConstructor(int.class, double.class, double.class, double.class);
+
+ // EntityArmorStand
+ final Constructor> entityArmorStandConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityArmorStand").getConstructor(w);
+ final Object entityArmorStand = entityArmorStandConstr.newInstance(worldServer);
+ final Method setLoc2 = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class);
+ setLoc2.invoke(entityArmorStand, l.getX(), l.getY() - 1D, l.getZ(), 0F, 0F);
+ final Method setCustomName = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class);
+ setCustomName.invoke(entityArmorStand, text);
+ final Method setCustomNameVisible = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class);
+ setCustomNameVisible.invoke(entityArmorStand, true);
+ final Method getArmorStandId = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
+ final int armorstandId = (Integer) (getArmorStandId.invoke(entityArmorStand));
+ final Method setInvisble = entityArmorStand.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible", boolean.class);
+ setInvisble.invoke(entityArmorStand, true);
+
+ Effects.effectlocd.put(armorstandId, 12); // send move packet 12 times
+
+ // Send EntityArmorStand packet
+ final Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityArmorStand);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket);
+
+ // Send velocity packets to move the entities slowly down
+ if (moveDown)
+ {
+ Effects.effectlocd_taskid.put(armorstandId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> {
+ try
+ {
+ final int i = Effects.effectlocd.get(armorstandId);
+ final Object packet = packetPlayOutEntityVelocity.newInstance(armorstandId, 0D, -0.05D, 0D);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet);
+ if (i < -1)
+ {
+ final int taskid = Effects.effectlocd_taskid.get(armorstandId);
+ Effects.effectlocd_taskid.remove(armorstandId);
+ Effects.effectlocd.remove(armorstandId);
+ Bukkit.getScheduler().cancelTask(taskid);
+ return;
+ }
+ Effects.effectlocd.put(armorstandId, Effects.effectlocd.get(armorstandId) - 1);
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ }, 2L, 2L).getTaskId());
+ }
+
+ // Remove both entities (and thus the hologram) after 2 seconds
+ if (removeAfterCooldown)
+ {
+ Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> {
+ try
+ {
+ final Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance(new int[] { armorstandId });
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket);
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ }, 20L * 2);
+ }
+
+ ret.add(armorstandId);
+
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ return ret;
+ }
+ try
+ {
+ // If player is on 1.8, we'll have to use armor stands, otherwise just use the old 1.7 technique
+ final boolean playerIs1_8 = MinigamesAPI.SERVER_VERSION.isAtLeast(MinecraftVersionsType.V1_8);
+
+ final Method getPlayerHandle = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".entity.CraftPlayer").getMethod("getHandle");
+ final Field playerConnection = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityPlayer").getField("playerConnection");
+ playerConnection.setAccessible(true);
+ final Method sendPacket = playerConnection.getType().getMethod("sendPacket", Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Packet"));
+
+ final Class> craftw = Class.forName("org.bukkit.craftbukkit." + MinigamesAPI.getAPI().internalServerVersion + ".CraftWorld");
+ final Class> w = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".World");
+ final Class> entity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".Entity");
+ final Method getWorldHandle = craftw.getDeclaredMethod("getHandle");
+ final Object worldServer = getWorldHandle.invoke(craftw.cast(l.getWorld()));
+ final Constructor> packetPlayOutSpawnEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntity")
+ .getConstructor(entity, int.class);
+ final Constructor> packetPlayOutSpawnEntityLivingConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutSpawnEntityLiving")
+ .getConstructor(Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityLiving"));
+ final Constructor> packetPlayOutAttachEntityConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutAttachEntity")
+ .getConstructor(int.class, entity, entity);
+ final Constructor> packetPlayOutEntityDestroyConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityDestroy")
+ .getConstructor(int[].class);
+ final Constructor> packetPlayOutEntityVelocity = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".PacketPlayOutEntityVelocity")
+ .getConstructor(int.class, double.class, double.class, double.class);
+
+ // WitherSkull
+ final Constructor> witherSkullConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityWitherSkull").getConstructor(w);
+ final Object witherSkull = witherSkullConstr.newInstance(worldServer);
+ final Method setLoc = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class);
+ setLoc.invoke(witherSkull, l.getX(), l.getY() + 33D, l.getZ(), 0F, 0F);
+ final Method getWitherSkullId = witherSkull.getClass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
+ final int witherSkullId = (Integer) (getWitherSkullId.invoke(witherSkull));
+
+ // EntityHorse
+ final Constructor> entityHorseConstr = Class.forName("net.minecraft.server." + MinigamesAPI.getAPI().internalServerVersion + ".EntityHorse").getConstructor(w);
+ final Object entityHorse = entityHorseConstr.newInstance(worldServer);
+ final Method setLoc2 = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setLocation", double.class,
+ double.class, double.class, float.class, float.class);
+ setLoc2.invoke(entityHorse, l.getX(), l.getY() + (playerIs1_8 ? -1D : 33D), l.getZ(), 0F, 0F);
+ final Method setAge = entityHorse.getClass().getSuperclass().getSuperclass().getDeclaredMethod("setAge", int.class);
+ setAge.invoke(entityHorse, -1000000);
+ final Method setCustomName = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomName", String.class);
+ setCustomName.invoke(entityHorse, text);
+ final Method setCustomNameVisible = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setCustomNameVisible", boolean.class);
+ setCustomNameVisible.invoke(entityHorse, true);
+ final Method getHorseId = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("getId");
+ final int horseId = (Integer) (getHorseId.invoke(entityHorse));
+
+ if (playerIs1_8)
+ {
+ // Set horse (later armor stand) invisible
+ final Method setInvisble = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredMethod("setInvisible",
+ boolean.class);
+ setInvisble.invoke(entityHorse, true);
+ }
+
+ Effects.effectlocd.put(horseId, 12); // send move packet 12 times
+
+ // Send Witherskull+EntityHorse packet
+ final Object horsePacket = packetPlayOutSpawnEntityLivingConstr.newInstance(entityHorse);
+ if (playerIs1_8)
+ {
+ // Set entity id to 30 (armor stand):
+ Effects.setValue(horsePacket, "b", 30);
+ // Fix datawatcher values to prevent crashes (ofc armor stands expect other data than horses):
+ final Field datawatcher = entityHorse.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("datawatcher");
+ datawatcher.setAccessible(true);
+ final Object datawatcherInstance = datawatcher.get(entityHorse);
+ final Field d = datawatcherInstance.getClass().getDeclaredField("d");
+ d.setAccessible(true);
+ final Map, ?> dmap = (Map, ?>) d.get(datawatcherInstance);
+ dmap.remove(10);
+ // These are the Rotation ones
+ dmap.remove(11);
+ dmap.remove(12);
+ dmap.remove(13);
+ dmap.remove(14);
+ dmap.remove(15);
+ dmap.remove(16);
+ final Method a = datawatcherInstance.getClass().getDeclaredMethod("a", int.class, Object.class);
+ a.invoke(datawatcherInstance, 10, (byte) 0);
+ }
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), horsePacket);
+ if (!playerIs1_8)
+ {
+ final Object witherPacket = packetPlayOutSpawnEntityConstr.newInstance(witherSkull, 64);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), witherPacket);
+ }
+
+ // Send attach packet
+ if (!playerIs1_8)
+ {
+ final Object attachPacket = packetPlayOutAttachEntityConstr.newInstance(0, entityHorse, witherSkull);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), attachPacket);
+ }
+
+ // Send velocity packets to move the entities slowly down
+ if (moveDown)
+ {
+ Effects.effectlocd_taskid.put(horseId, Bukkit.getScheduler().runTaskTimer(MinigamesAPI.getAPI(), () -> {
+ try
+ {
+ final int i = Effects.effectlocd.get(horseId);
+ final Object packet = packetPlayOutEntityVelocity.newInstance(horseId, 0D, -0.05D, 0D);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet);
+ if (!playerIs1_8)
+ {
+ final Object packet2 = packetPlayOutEntityVelocity.newInstance(witherSkullId, 0D, -0.05D, 0D);
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), packet2);
+ }
+ if (i < -1)
+ {
+ final int taskid = Effects.effectlocd_taskid.get(horseId);
+ Effects.effectlocd_taskid.remove(horseId);
+ Effects.effectlocd.remove(horseId);
+ Bukkit.getScheduler().cancelTask(taskid);
+ return;
+ }
+ Effects.effectlocd.put(horseId, Effects.effectlocd.get(horseId) - 1);
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ }, 2L, 2L).getTaskId());
+ }
+
+ // Remove both entities (and thus the hologram) after 2 seconds
+ if (removeAfterCooldown)
+ {
+ Bukkit.getScheduler().runTaskLater(MinigamesAPI.getAPI(), () -> {
+ try
+ {
+ final Object destroyPacket = packetPlayOutEntityDestroyConstr.newInstance(new int[] { witherSkullId, horseId });
+ sendPacket.invoke(playerConnection.get(getPlayerHandle.invoke(p)), destroyPacket);
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ }, 20L * 2);
+ }
+
+ ret.add(witherSkullId);
+ ret.add(horseId);
+
+ }
+ catch (final Exception e)
+ {
+ if (MinigamesAPI.debug)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e);
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Sends a game mode change to given player.
+ *
+ * @param p
+ * target player
+ * @param gamemode
+ * new game mode.
+ */
+ public static void sendGameModeChange(final Player p, final int gamemode)
+ {
+ // NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator");
+
+ if (MinigamesAPI.SERVER_VERSION.isAfter(MinecraftVersionsType.V1_7) && gamemode == 3)
+ {
+ return;
+ }
+
+ p.setGameMode(GameMode.getByValue(gamemode));
+ }
}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java
new file mode 100644
index 00000000..cd102ddd
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/LobbySignManager.java
@@ -0,0 +1,339 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.block.BlockState;
+import org.bukkit.block.Sign;
+import org.bukkit.configuration.file.FileConfiguration;
+import org.bukkit.event.block.SignChangeEvent;
+import org.bukkit.plugin.Plugin;
+
+import com.comze_instancelabs.minigamesapi.util.Signs;
+import com.google.common.io.ByteArrayDataOutput;
+import com.google.common.io.ByteStreams;
+
+/**
+ * Manager for cross server lobby signs.
+ *
+ * @author mepeisen
+ *
+ */
+public class LobbySignManager
+{
+
+ /**
+ * hash map for signs.
+ */
+ private final Map signs = new HashMap<>();
+
+ /**
+ * minigames api.
+ */
+ final Plugin plugin;
+
+ /**
+ * Constructor.
+ *
+ * @param plugin
+ */
+ public LobbySignManager(Plugin plugin)
+ {
+ this.plugin = plugin;
+ }
+
+ /**
+ * Attaches a new sign to the sign manager,
+ *
+ * @param location
+ * location
+ * @param serverName
+ * server name
+ * @param minigameName
+ * minigame name
+ * @param arenaName
+ * arena name
+ * @param spec
+ * true for spectator sign, false for join sign
+ */
+ public void attachSign(Location location, String serverName, String minigameName, String arenaName, boolean spec)
+ {
+ final SignData data = new SignData(location, serverName, minigameName, arenaName, spec);
+ this.signs.put(location, data);
+ data.setSignData(null);
+ }
+
+ /**
+ * Attaches a new sign to the sign manager,
+ *
+ * @param location
+ * location
+ * @param serverName
+ * server name
+ * @param minigameName
+ * minigame name
+ * @param arenaName
+ * arena name
+ * @param spec
+ * true for spectator sign, false for join sign
+ * @param evt
+ * sign change event
+ */
+ public void attachSign(Location location, String serverName, String minigameName, String arenaName, boolean spec, SignChangeEvent evt)
+ {
+ final SignData data = new SignData(location, serverName, minigameName, arenaName, spec);
+ this.signs.put(location, data);
+ data.setSignData(evt);
+ }
+
+ /**
+ * request sign updates.
+ *
+ * @param location
+ */
+ public void requestSignUpdate(Location location)
+ {
+ final SignData data = this.signs.get(location);
+ if (data != null)
+ {
+ data.requestServerSign();
+ }
+ }
+
+ /**
+ * Detaches a sign from manager.
+ *
+ * @param location
+ */
+ public void detachSign(Location location)
+ {
+ this.signs.remove(location);
+ }
+
+ /**
+ * @param location
+ * @param arenastate
+ * @param count
+ * @param maxcount
+ */
+ public void updateSign(Location location, String arenastate, int count, int maxcount)
+ {
+ final SignData data = this.signs.get(location);
+ if (data != null)
+ {
+ data.setSignData(count, maxcount, arenastate, null);
+ data.updateResponseDate();
+ }
+ }
+
+ /**
+ * private sign data.
+ */
+ private final class SignData
+ {
+
+ /** sign location. */
+ private final Location location;
+
+ /** server name. */
+ private final String serverName;
+
+ /** arena name. */
+ private final String arenaName;
+
+ /** minigame name. */
+ private final String minigameName;
+
+ /** spectate sign? */
+ private final boolean spec;
+
+ /**
+ * last max players info.
+ */
+ int lastMaxPlayers = 10;
+
+ /** last request of sign update. */
+ LocalDateTime lastRequest = LocalDateTime.now();
+
+ /** last response of sign update. */
+ LocalDateTime lastResponse = this.lastRequest;
+
+ /**
+ * timestamp a log warning was posted
+ */
+ LocalDateTime lastSignWarning = null;
+
+ /**
+ * @param location
+ * @param serverName
+ * @param minigameName
+ * @param arenaName
+ * @param spec
+ */
+ public SignData(Location location, String serverName, String minigameName, String arenaName, boolean spec)
+ {
+ this.location = location;
+ this.serverName = serverName;
+ this.minigameName = minigameName;
+ this.arenaName = arenaName;
+ this.spec = spec;
+ }
+
+ /**
+ * Updates the last response data.
+ */
+ public void updateResponseDate()
+ {
+ this.lastResponse = LocalDateTime.now();
+ }
+
+ /**
+ * Request server sign update.
+ */
+ public void requestServerSign()
+ {
+ this.lastRequest = LocalDateTime.now();
+ try
+ {
+ ByteArrayDataOutput out = ByteStreams.newDataOutput();
+ try
+ {
+ out.writeUTF("Forward"); //$NON-NLS-1$
+ out.writeUTF(this.serverName);
+ out.writeUTF(ChannelStrings.SUBCHANNEL_MINIGAMESLIB_REQUEST);
+
+ ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
+ DataOutputStream msgout = new DataOutputStream(msgbytes);
+ msgout.writeUTF(this.minigameName + ":" + this.arenaName); //$NON-NLS-1$
+
+ out.writeShort(msgbytes.toByteArray().length);
+ out.write(msgbytes.toByteArray());
+
+ Bukkit.getServer().sendPluginMessage(LobbySignManager.this.plugin, ChannelStrings.CHANNEL_BUNGEE_CORD, out.toByteArray());
+
+ // TODO if no answer after 2 seconds, server empty!
+
+ }
+ catch (Exception e)
+ {
+ MinigamesAPI.getAPI().getLogger().log(Level.WARNING, "exception", e); //$NON-NLS-1$
+ }
+ }
+ catch (Exception e)
+ {
+ LobbySignManager.this.plugin.getLogger().log(Level.WARNING, "Error occurred while sending extra sign request: ", e); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Sets initial sign data.
+ *
+ * @param evt
+ */
+ public void setSignData(SignChangeEvent evt)
+ {
+ this.setSignData(0, 10, this.spec ? "SPEC" : "JOIN", evt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Sets sign data.
+ *
+ * @param count
+ * @param maxcount
+ * @param arenastate
+ * @param evt
+ */
+ public void setSignData(int count, int maxcount, String arenastate, SignChangeEvent evt)
+ {
+ this.lastMaxPlayers = maxcount;
+ final FileConfiguration cfg = LobbySignManager.this.plugin.getConfig();
+ final String line0 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".0").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$
+ final String line1 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".1").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$
+ final String line2 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".2").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$
+ final String line3 = Signs.format(cfg.getString("signs." + arenastate.toLowerCase() + ".3").replace("", Integer.toString(count)).replace("", Integer.toString(maxcount)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ .replace("", this.arenaName).replace("", this.minigameName)); //$NON-NLS-1$ //$NON-NLS-2$
+ if (evt == null)
+ {
+ final BlockState state = this.location.getBlock().getState();
+ if (state instanceof Sign)
+ {
+ final Sign sign = (Sign) state;
+ sign.setLine(0, line0);
+ sign.setLine(1, line1);
+ sign.setLine(2, line2);
+ sign.setLine(3, line3);
+ sign.getBlock().getChunk().load();
+ sign.update();
+ }
+ else
+ {
+ if (this.lastSignWarning == null || this.lastSignWarning.until(LocalDateTime.now(), ChronoUnit.SECONDS) > 30)
+ {
+ this.lastSignWarning = LocalDateTime.now();
+ LobbySignManager.this.plugin.getLogger().log(Level.WARNING, "Cannot find lobby sign for " + this.minigameName + "/" + this.arenaName + " at position " + this.location); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ }
+ else
+ {
+ evt.setLine(0, line0);
+ evt.setLine(1, line1);
+ evt.setLine(2, line2);
+ evt.setLine(3, line3);
+ }
+ }
+
+ }
+
+ /**
+ *
+ */
+ public void ping()
+ {
+ for (final SignData data : this.signs.values())
+ {
+ if (data.lastResponse.isBefore(data.lastRequest))
+ {
+ if (data.lastResponse.until(data.lastRequest, ChronoUnit.SECONDS) > 5)
+ {
+ // assume there are no more players
+ data.setSignData(0, data.lastMaxPlayers, "JOIN", null); //$NON-NLS-1$
+ data.updateResponseDate();
+ }
+ }
+ else
+ {
+ if (data.lastResponse.until(LocalDateTime.now(), ChronoUnit.SECONDS) > 60)
+ {
+ data.requestServerSign();
+ }
+ }
+ }
+ }
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java
new file mode 100644
index 00000000..42f84cda
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MatchTimer.java
@@ -0,0 +1,341 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.util.function.Consumer;
+import java.util.logging.Logger;
+
+import org.bukkit.plugin.Plugin;
+import org.bukkit.scheduler.BukkitRunnable;
+import org.bukkit.scheduler.BukkitTask;
+
+/**
+ * Backport of v2 BasicMatchTimer rule
+ *
+ * @author mepeisen
+ *
+ */
+public class MatchTimer
+{
+
+
+ /**
+ * maximum seconds
+ */
+ private int seconds;
+
+ /**
+ * the current match duration in millis
+ */
+ private long matchDuration;
+
+ /**
+ * the current match maxmimum time
+ */
+ private long matchTime;
+
+ /**
+ * Flag for paused or running timers; {@code true} if timer is paused
+ */
+ private boolean paused;
+
+ /**
+ * Last start of timer
+ */
+ private LocalDateTime lastStart = LocalDateTime.now();
+
+ /**
+ * The timer task
+ */
+ private BukkitTask timerTask;
+
+ private Runnable arenaAbort;
+
+ private Consumer arenaNotify;
+
+ private boolean warn60 = true;
+
+ private boolean warn30 = true;
+
+ private boolean warn20 = true;
+
+ private boolean warn10 = true;
+
+ private boolean warn5 = true;
+
+ private boolean warn4 = true;
+
+ private boolean warn3 = true;
+
+ private boolean warn2 = true;
+
+ private boolean warn1 = true;
+
+ /** logger. */
+ private static final Logger LOGGER = Logger.getLogger(MatchTimer.class.getName());
+
+ /**
+ */
+ public MatchTimer(int maxSeconds, Runnable arenaAbort, Consumer arenaNotify)
+ {
+ this.setMaxSeconds(maxSeconds);
+ this.arenaAbort = arenaAbort;
+ this.arenaNotify = arenaNotify;
+ }
+
+ public int getMaxSeconds()
+ {
+ return this.seconds;
+ }
+
+ public void setMaxSeconds(int seconds)
+ {
+ this.seconds = seconds;
+ this.matchTime = this.seconds * 1000L;
+ }
+
+ public void pause()
+ {
+ if (!this.paused)
+ {
+ this.paused = true;
+ this.matchDuration += this.lastStart.until(LocalDateTime.now(), ChronoUnit.MILLIS);
+ }
+ }
+
+ public void resume()
+ {
+ if (this.paused)
+ {
+ this.paused = false;
+ this.lastStart = LocalDateTime.now();
+ }
+ }
+
+ public void resetAndResume()
+ {
+ this.paused = false;
+ this.lastStart = LocalDateTime.now();
+ this.matchDuration = 0;
+ this.fixWarnings();
+ }
+
+ public void resetAndPause()
+ {
+ this.paused = true;
+ this.matchDuration = 0;
+ this.fixWarnings();
+ }
+
+ public long getDurationMillis()
+ {
+ if (this.paused)
+ {
+ return this.matchDuration;
+ }
+ return this.matchDuration + this.lastStart.until(LocalDateTime.now(), ChronoUnit.MILLIS);
+ }
+
+ public long getMaxMillis()
+ {
+ return this.matchTime;
+ }
+
+ public void addMaxMillis(Plugin plugin, long millis)
+ {
+ this.matchTime += millis;
+ if (this.matchTime > 0 && this.timerTask == null)
+ {
+ this.startTimer(plugin);
+ }
+ this.fixWarnings();
+ }
+
+ public void substractMaxMillis(long millis)
+ {
+ this.matchTime -= millis;
+ if (this.matchTime <= 0)
+ {
+ this.stopTimer();
+ }
+ this.fixWarnings();
+ }
+
+ public void setMaxMillis(long millis)
+ {
+ this.matchTime = millis;
+ if (this.matchTime <= 0)
+ {
+ this.stopTimer();
+ }
+ this.fixWarnings();
+ }
+
+ public void addDurationMillis(long millis)
+ {
+ this.matchDuration += millis;
+ this.fixWarnings();
+ }
+
+ public void substractDurationMillis(long millis)
+ {
+ this.matchDuration -= millis;
+ this.fixWarnings();
+ }
+
+ public void setDurationMillis(long millis)
+ {
+ this.matchDuration = millis;
+ this.fixWarnings();
+ }
+
+ public void onArenaStart(Plugin plugin)
+ {
+ this.matchTime = this.seconds * 1000L;
+ this.matchDuration = 0;
+ this.lastStart = LocalDateTime.now();
+ this.paused = false;
+ if (this.matchTime > 0)
+ {
+ this.startTimer(plugin);
+ }
+ this.fixWarnings();
+ }
+
+
+ public void onArenaStop()
+ {
+ this.stopTimer();
+ }
+
+ /**
+ * Starts the bukkit timer task
+ */
+ private void startTimer(Plugin plugin)
+ {
+ if (this.timerTask == null)
+ {
+ this.timerTask = new BukkitRunnable() {
+
+ @Override
+ public void run()
+ {
+ MatchTimer.this.onTimer(MatchTimer.this.timerTask);
+ }
+ }.runTaskTimer(plugin, 20L, 20L);
+ }
+ }
+
+ /**
+ * Stops the bukkit timer task
+ */
+ private void stopTimer()
+ {
+ if (this.timerTask != null)
+ {
+ this.timerTask.cancel();
+ this.timerTask = null;
+ }
+ }
+
+ /**
+ * Fixes warnings depending on remaining game time
+ */
+ private void fixWarnings()
+ {
+ long delta = this.getMaxMillis() - this.getDurationMillis();
+ final int sec = (int) (delta / 1000);
+ this.warn60 = sec >= 60;
+ this.warn30 = sec >= 30;
+ this.warn20 = sec >= 20;
+ this.warn10 = sec >= 10;
+ this.warn5 = sec >= 5;
+ this.warn4 = sec >= 4;
+ this.warn3 = sec >= 3;
+ this.warn2 = sec >= 2;
+ this.warn1 = sec >= 1;
+ }
+
+ /**
+ * On timer tick
+ *
+ * @param task
+ */
+ private void onTimer(BukkitTask task)
+ {
+ if (!this.paused)
+ {
+ long delta = this.getMaxMillis() - this.getDurationMillis();
+ if (delta <= 0)
+ {
+ this.timerTask.cancel();
+ this.timerTask = null;
+ this.arenaAbort.run();
+ }
+ else
+ {
+ final int sec = (int) (delta / 1000);
+ if (this.warn60 && sec <= 60)
+ {
+ this.arenaNotify.accept(60);
+ this.warn60 = false;
+ }
+ else if (this.warn30 && sec <= 30)
+ {
+ this.arenaNotify.accept(30);
+ this.warn30 = false;
+ }
+ else if (this.warn20 && sec <= 20)
+ {
+ this.arenaNotify.accept(20);
+ this.warn20 = false;
+ }
+ else if (this.warn10 && sec <= 10)
+ {
+ this.arenaNotify.accept(10);
+ this.warn10 = false;
+ }
+ else if (this.warn5 && sec <= 5)
+ {
+ this.arenaNotify.accept(5);
+ this.warn5 = false;
+ }
+ else if (this.warn4 && sec <= 4)
+ {
+ this.arenaNotify.accept(4);
+ this.warn4 = false;
+ }
+ else if (this.warn3 && sec <= 3)
+ {
+ this.arenaNotify.accept(3);
+ this.warn3 = false;
+ }
+ else if (this.warn2 && sec <= 2)
+ {
+ this.arenaNotify.accept(2);
+ this.warn2 = false;
+ }
+ else if (this.warn1 && sec <= 1)
+ {
+ this.arenaNotify.accept(1);
+ this.warn1 = false;
+ }
+ }
+ }
+ }
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java
new file mode 100644
index 00000000..5c2b86b8
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Messages.java
@@ -0,0 +1,79 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+package com.comze_instancelabs.minigamesapi;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Localized message helper.
+ *
+ * @author mepeisen
+ */
+public class Messages
+{
+
+ /** the resource bundle name. */
+ private static final String BUNDLE_NAME = "com.comze_instancelabs.minigamesapi.messages"; //$NON-NLS-1$
+
+ /** the default resource bundle; used as fallback. */
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+
+ /** the bundles by locales. */
+ private static final Map BUNDLES = new ConcurrentHashMap<>();
+
+ /**
+ * hidden constructor.
+ */
+ private Messages()
+ {
+ }
+
+ /**
+ * Returns the localized string
+ *
+ * @param key
+ * string key
+ * @param locale
+ * locale to be used.
+ * @return localized string.
+ */
+ public static String getString(String key, Locale locale)
+ {
+ try
+ {
+ final ResourceBundle res = BUNDLES.computeIfAbsent(locale, (l) -> {
+ try
+ {
+ return ResourceBundle.getBundle(BUNDLE_NAME, l);
+ }
+ catch (@SuppressWarnings("unused") MissingResourceException ex)
+ {
+ return RESOURCE_BUNDLE;
+ }
+ });
+ return res.getString(key);
+ }
+ catch (@SuppressWarnings("unused") MissingResourceException e)
+ {
+ return '!' + key + '!';
+ }
+ }
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java
new file mode 100644
index 00000000..566fc669
--- /dev/null
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinecraftVersionsType.java
@@ -0,0 +1,238 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+package com.comze_instancelabs.minigamesapi;
+
+/**
+ * Supported versions of minecraft.
+ *
+ * @author mepeisen
+ */
+public enum MinecraftVersionsType
+{
+ /** an unknown version/ not supported. */
+ Unknown(false, "invalid"), //$NON-NLS-1$
+
+ /** any 1.7 version. */
+ V1_7(true, "v1_7_R1"), //$NON-NLS-1$
+
+ /** V1.7 R1 */
+ V1_7_R1(true, "v1_7_R1"), //$NON-NLS-1$
+
+ /** V1.7 R2 */
+ V1_7_R2(true, "v1_7_R2"), //$NON-NLS-1$
+
+ /** V1.7 R3 */
+ V1_7_R3(true, "v1_7_R3"), //$NON-NLS-1$
+
+ /** V1.7 R4 */
+ V1_7_R4(true, "v1_7_R4"), //$NON-NLS-1$
+
+ /** any 1.8 version. */
+ V1_8(true, "v1_8_R1"), //$NON-NLS-1$
+
+ /** V1.8 R1 */
+ V1_8_R1(true, "v1_8_R1"), //$NON-NLS-1$
+
+ /** V1.8 R2 */
+ V1_8_R2(true, "v1_8_R2"), //$NON-NLS-1$
+
+ /** V1.8 R3 */
+ V1_8_R3(true, "v1_8_R3"), //$NON-NLS-1$
+
+ /** any 1.9 version. */
+ V1_9(true, "v1_9_R1"), //$NON-NLS-1$
+
+ /** V1.9 R1 */
+ V1_9_R1(true, "v1_9_R1"), //$NON-NLS-1$
+
+ /** V1.9 R2 */
+ V1_9_R2(true, "v1_9_R2"), //$NON-NLS-1$
+
+ /** any 1.10 version. */
+ V1_10(true, "v1_10_R1"), //$NON-NLS-1$
+
+ /** V1.10 R1 */
+ V1_10_R1(true, "v1_10_R1"), //$NON-NLS-1$
+
+ /** any 1.11 version. */
+ V1_11(true, "v1_11_R1"), //$NON-NLS-1$
+
+ /** V1.11 R1 */
+ V1_11_R1(true, "v1_11_R1"), //$NON-NLS-1$
+
+ /** any 1.12 version. */
+ V1_12(true, "v1_12_R1"), //$NON-NLS-1$
+
+ /** V1.12 R1 */
+ V1_12_R1(true, "v1_12_R1"), //$NON-NLS-1$
+
+ ;
+
+ /**
+ * {@code true} if this version is still supported.
+ */
+ private final boolean isSupported;
+
+ /** the maven version string for update requests. */
+ private final String mavenVersion;
+
+ /**
+ * Constructor to create a version.
+ *
+ * @param supported
+ * true for support.
+ * @param mavenVersion
+ * the maven version string for update queries.
+ */
+ private MinecraftVersionsType(final boolean supported, final String mavenVersion)
+ {
+ this.isSupported = supported;
+ this.mavenVersion = mavenVersion;
+ }
+
+ /**
+ * {@code true} if this version is still supported.
+ *
+ * @return {@code true} if this version is still supported.
+ */
+ public boolean isSupported()
+ {
+ return this.isSupported;
+ }
+
+ /**
+ * Checks if this version equals given version.
+ *
+ *
+ * Notice: Pseudo versions (V1_7) will match every V1_7_R* version.
+ *
+ *
+ * @param type
+ * version to compare to.
+ * @return {@code true} if this version matches given version.
+ */
+ public boolean isEqual(final MinecraftVersionsType type)
+ {
+ switch (this)
+ {
+ case V1_12:
+ return type == V1_12 || type == V1_12_R1;
+ case V1_11:
+ return type == V1_11 || type == V1_11_R1;
+ case V1_10:
+ return type == V1_10 || type == V1_10_R1;
+ case V1_7:
+ return type == V1_7 || type == V1_7_R1 || type == V1_7_R2 || type == V1_7_R3 || type == V1_7_R4;
+ case V1_8:
+ return type == V1_8 || type == V1_8_R1 || type == V1_8_R2 || type == V1_8_R3;
+ case V1_9:
+ return type == V1_9 || type == V1_9_R1 || type == V1_9_R2;
+ // $CASES-OMITTED$
+ default:
+ switch (type)
+ {
+ case V1_12:
+ return this == V1_12 || this == V1_12_R1;
+ case V1_11:
+ return this == V1_11 || this == V1_11_R1;
+ case V1_10:
+ return this == V1_10 || this == V1_10_R1;
+ case V1_7:
+ return this == V1_7 || this == V1_7_R1 || this == V1_7_R2 || this == V1_7_R3 || this == V1_7_R4;
+ case V1_8:
+ return this == V1_8 || this == V1_8_R1 || this == V1_8_R2 || this == V1_8_R3;
+ case V1_9:
+ return this == V1_9 || this == V1_9_R1 || this == V1_9_R2;
+ // $CASES-OMITTED$
+ default:
+ return type == this;
+ }
+ }
+ }
+
+ /**
+ * Checks if this version is below given version.
+ *
+ *
+ * - V1_7 will be below V1_8*.
+ * - V1_7_R3 will be below V1_7_R4.
+ *
+ *
+ * @param type
+ * version to compare to.
+ * @return {@code true} if this version matches given version.
+ */
+ public boolean isBelow(final MinecraftVersionsType type)
+ {
+ if (this.isEqual(type))
+ {
+ return false;
+ }
+ return this.ordinal() < type.ordinal();
+ }
+
+ /**
+ * Checks if this version is after given version.
+ *
+ *
+ * - V1_8 will be after V1_7*.
+ * - V1_7_R4 will be after V1_7_R3.
+ *
+ *
+ * @param type
+ * version to compare to.
+ * @return {@code true} if this version matches given version.
+ */
+ public boolean isAfter(final MinecraftVersionsType type)
+ {
+ if (this.isEqual(type))
+ {
+ return false;
+ }
+ return this.ordinal() > type.ordinal();
+ }
+
+ /**
+ * Checks if this version is at least given version.
+ *
+ *
+ * - V1_7_R4 will be at least V1_7.
+ * - V1_7_R3 will be after V1_7_R2.
+ *
+ *
+ * @param type
+ * version to compare to.
+ * @return {@code true} if this version matches given version.
+ */
+ public boolean isAtLeast(final MinecraftVersionsType type)
+ {
+ if (this.isEqual(type))
+ {
+ return true;
+ }
+ return this.ordinal() > type.ordinal();
+ }
+
+ /**
+ * Returns the maven version string for update queries.
+ *
+ * @return maven version string.
+ */
+ public String mavenVersionString()
+ {
+ return this.mavenVersion;
+ }
+
+}
diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java
index d9c1a9fb..cb9f6c42 100644
--- a/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java
+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/MinigamesAPI.java
@@ -1,24 +1,56 @@
+/*
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
package com.comze_instancelabs.minigamesapi;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
+import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
-
-import net.milkbowl.vault.economy.Economy;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.UUID;
+import java.util.function.Supplier;
+import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.block.BlockState;
+import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+import org.bukkit.event.block.Action;
+import org.bukkit.event.block.BlockBreakEvent;
+import org.bukkit.event.block.SignChangeEvent;
+import org.bukkit.event.player.PlayerInteractEvent;
+import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.PluginMessageListener;
-import com.comze_instancelabs.minigamesapi.bungee.BungeeSocket;
import com.comze_instancelabs.minigamesapi.commands.CommandHandler;
import com.comze_instancelabs.minigamesapi.config.ArenasConfig;
import com.comze_instancelabs.minigamesapi.config.ClassesConfig;
@@ -33,549 +65,1932 @@
import com.comze_instancelabs.minigamesapi.util.Metrics;
import com.comze_instancelabs.minigamesapi.util.Metrics.Graph;
import com.comze_instancelabs.minigamesapi.util.ParticleEffectNew;
-import com.comze_instancelabs.minigamesapi.util.Updater;
+import com.comze_instancelabs.minigamesapi.util.UpdaterNexus;
import com.comze_instancelabs.minigamesapi.util.Util;
+import com.comze_instancelabs.minigamesapi.util.Validator;
import com.google.common.io.ByteArrayDataInput;
+import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-public class MinigamesAPI extends JavaPlugin implements PluginMessageListener {
-
- static MinigamesAPI instance = null;
- public static Economy econ = null;
- public static boolean economy = true;
- public boolean crackshot = false;
- public static boolean debug = false;
-
- public HashMap global_party = new HashMap();
- public HashMap> global_party_invites = new HashMap>();
-
- public static HashMap pinstances = new HashMap();
-
- public PartyMessagesConfig partymessages;
- public StatsGlobalConfig statsglobal;
-
- public String version = "";
- public boolean below1710 = false; // Used for scoreboard function (wether to use getScore(OfflinePlayer) or getScore(String))
-
- Metrics metrics;
-
- public void onEnable() {
- instance = this;
-
- this.version = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1);
- this.below1710 = version.startsWith("v1_7_R3") || version.startsWith("v1_7_R2") || version.startsWith("v1_7_R1") || version.startsWith("v1_6") || version.startsWith("v1_5");
- Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Loaded MinigamesAPI. We're on " + version + ".");
-
- this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
- this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this);
-
- if (economy) {
- if (!setupEconomy()) {
- getLogger().severe(String.format("[%s] - No Economy (Vault) dependency found! Disabling Economy.", getDescription().getName()));
- economy = false;
- }
- }
-
- getConfig().options().header("Want bugfree versions? Set this to true:");
- getConfig().addDefault("config.auto_updating", true);
- getConfig().addDefault("config.party_command_enabled", true);
- getConfig().addDefault("config.debug", false);
-
- getConfig().options().copyDefaults(true);
- this.saveConfig();
-
- partymessages = new PartyMessagesConfig(this);
- statsglobal = new StatsGlobalConfig(this, false);
-
- this.debug = getConfig().getBoolean("config.debug");
-
- Bukkit.getScheduler().runTaskLater(this, new Runnable() {
- public void run() {
- try {
- metrics = new Metrics(instance);
-
- Graph components = metrics.createGraph("Minigames");
- for (PluginInstance pli : pinstances.values()) {
- components.addPlotter(new Metrics.Plotter(pli.getPlugin().getName()) {
- @Override
- public int getValue() {
- return 1;
- }
- });
- if (MinigamesAPI.debug) {
- System.out.println("Loaded Graph for: " + pli.getPlugin().getName());
- }
- }
-
- metrics.start();
- } catch (IOException e) {
- System.out.println("# " + e.getMessage());
- }
- }
- }, 60L);
-
- if (getConfig().getBoolean("config.auto_updating")) {
- Updater updater = new Updater(this, 83025, this.getFile(), Updater.UpdateType.DEFAULT, false);
- }
-
- if (getServer().getPluginManager().getPlugin("CrackShot") != null) {
- crackshot = true;
- }
-
- Bukkit.getScheduler().runTaskLater(this, new Runnable() {
- public void run() {
- // Reset all arena signs and check if any arena was interrupted
- int i = 0;
- for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) {
- for (Arena a : pli.getArenas()) {
- if (a != null) {
- if (a.isSuccessfullyInit()) {
- Util.updateSign(pli.getPlugin(), a);
- a.getSmartReset().loadSmartBlocksFromFile();
- } else {
- System.out.println(a.getInternalName() + " not initialized at onEnable.");
- }
- }
- i++;
- }
- }
- System.out.println("Found " + i + " arenas.");
- }
- }, 50L);
- }
-
- public void onDisable() {
- for (PluginInstance pli : this.pinstances.values()) {
- // Reset arenas
- for (Arena a : pli.getArenas()) {
- if (a != null) {
- if (a.isSuccessfullyInit()) {
- if (a.getArenaState() != ArenaState.JOIN) {
- a.getSmartReset().saveSmartBlocksToFile();
- }
- ArrayList temp = new ArrayList(a.getAllPlayers());
- for (String p_ : temp) {
- a.leavePlayer(p_, true);
- }
- try {
- a.getSmartReset().resetRaw();
- } catch (Exception e) {
- System.out.println("Failed resetting arena at onDisable. " + e.getMessage());
- }
- } else {
- System.out.println(a.getName() + " not initialized thus not reset at onDisable.");
- }
- }
- }
-
- // Save important configs
- pli.getArenasConfig().saveConfig();
- pli.getPlugin().saveConfig();
- pli.getMessagesConfig().saveConfig();
- pli.getClassesConfig().saveConfig();
- }
-
- }
-
- /**
- * Sets up the API allowing to override all configs
- *
- * @param plugin_
- * @param arenaclass
- * @param arenasconfig
- * @param messagesconfig
- * @param classesconfig
- * @param statsconfig
- * @return
- */
- public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame, Class> arenaclass, ArenasConfig arenasconfig, MessagesConfig messagesconfig, ClassesConfig classesconfig, StatsConfig statsconfig, DefaultConfig defaultconfig, boolean customlistener) {
- pinstances.put(plugin_, new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig, new ArrayList()));
- if (!customlistener) {
- ArenaListener al = new ArenaListener(plugin_, pinstances.get(plugin_), minigame);
- pinstances.get(plugin_).setArenaListener(al);
- Bukkit.getPluginManager().registerEvents(al, plugin_);
- }
- Classes.loadClasses(plugin_);
- Guns.loadGuns(plugin_);
- pinstances.get(plugin_).getShopHandler().loadShopItems();
- return instance;
- }
-
- public static void registerArenaListenerLater(JavaPlugin plugin_, ArenaListener arenalistener) {
- Bukkit.getPluginManager().registerEvents(arenalistener, plugin_);
- }
-
- public static void registerArenaSetup(JavaPlugin plugin_, ArenaSetup arenasetup) {
- pinstances.get(plugin_).arenaSetup = arenasetup;
- }
-
- public static void registerScoreboard(JavaPlugin plugin_, ArenaScoreboard board) {
- pinstances.get(plugin_).scoreboardManager = board;
- }
-
- /**
- * Sets up the API, stuff won't work without that
- *
- * @param plugin_
- * @return
- */
- // Allow loading of arenas with own extended arena class into
- // PluginInstance:
- // after this setup, get the PluginInstance, load the arenas by yourself
- // and add the loaded arenas w/ custom arena class into the PluginInstance
- public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame, Class> arenaclass) {
- setupRaw(plugin_, minigame);
- return instance;
- }
-
- /**
- * Sets up the API, stuff won't work without that
- *
- * @param plugin_
- * @return
- */
- public static MinigamesAPI setupAPI(JavaPlugin plugin_, String minigame) {
- PluginInstance pli = setupRaw(plugin_, minigame);
- pli.addLoadedArenas(Util.loadArenas(plugin_, pli.getArenasConfig()));
- return instance;
- }
-
- public static PluginInstance setupRaw(JavaPlugin plugin_, String minigame) {
- ArenasConfig arenasconfig = new ArenasConfig(plugin_);
- MessagesConfig messagesconfig = new MessagesConfig(plugin_);
- ClassesConfig classesconfig = new ClassesConfig(plugin_, false);
- StatsConfig statsconfig = new StatsConfig(plugin_, false);
- DefaultConfig.init(plugin_, false);
- PluginInstance pli = new PluginInstance(plugin_, arenasconfig, messagesconfig, classesconfig, statsconfig);
- pinstances.put(plugin_, pli);
- ArenaListener al = new ArenaListener(plugin_, pinstances.get(plugin_), minigame);
- pinstances.get(plugin_).setArenaListener(al);
- Bukkit.getPluginManager().registerEvents(al, plugin_);
- Classes.loadClasses(plugin_);
- pli.getShopHandler().loadShopItems();
- Guns.loadGuns(plugin_);
- return pli;
- }
-
- public static MinigamesAPI getAPI() {
- return instance;
- }
-
- public static CommandHandler getCommandHandler() {
- return new CommandHandler();
- }
-
- private boolean setupEconomy() {
- if (getServer().getPluginManager().getPlugin("Vault") == null) {
- return false;
- }
- RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Economy.class);
- if (rsp == null) {
- return false;
- }
- econ = rsp.getProvider();
- return econ != null;
- }
-
- public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
- if (cmd.getName().equalsIgnoreCase("start")) {
- if (!(sender instanceof Player)) {
- sender.sendMessage("Please execute this command ingame.");
- return true;
- }
- if (!sender.hasPermission("minigamesapi.start")) {
- // TODO no_perm message
- return true;
- }
- Player p = (Player) sender;
- for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) {
- if (pli.containsGlobalPlayer(p.getName())) {
- Arena a = pli.global_players.get(p.getName());
- System.out.println(a.getName());
- if (a.getArenaState() == ArenaState.JOIN || (a.getArenaState() == ArenaState.STARTING && !a.getIngameCountdownStarted())) {
- a.start(true);
- sender.sendMessage(pli.getMessagesConfig().arena_action.replaceAll("", a.getDisplayName()).replaceAll("", "started"));
- break;
- }
- }
- }
- return true;
- }
- if (cmd.getName().equalsIgnoreCase("party")) {
- if (!getConfig().getBoolean("config.party_command_enabled")) {
- return true;
- }
- CommandHandler cmdhandler = this.getCommandHandler();
- if (!(sender instanceof Player)) {
- sender.sendMessage("Please execute this command ingame.");
- return true;
- }
- Player p = (Player) sender;
- if (args.length > 0) {
- String action = args[0];
- if (action.equalsIgnoreCase("invite")) {
- cmdhandler.partyInvite(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else if (action.equalsIgnoreCase("accept")) {
- cmdhandler.partyAccept(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else if (action.equalsIgnoreCase("kick")) {
- cmdhandler.partyKick(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else if (action.equalsIgnoreCase("list")) {
- cmdhandler.partyList(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else if (action.equalsIgnoreCase("disband")) {
- cmdhandler.partyDisband(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else if (action.equalsIgnoreCase("leave")) {
- cmdhandler.partyLeave(sender, args, "minigamesapi.party", "/" + cmd.getName(), action, this, p);
- } else {
- cmdhandler.sendPartyHelp("/" + cmd.getName(), sender);
- }
- } else {
- cmdhandler.sendPartyHelp("/" + cmd.getName(), sender);
- }
- } else {
- if (args.length > 0) {
- if (args[0].equalsIgnoreCase("info")) {
- if (args.length > 1) {
- String p = args[1];
- sender.sendMessage("Debug info about " + p);
- sender.sendMessage("~ global_players: ");
- for (PluginInstance pli : pinstances.values()) {
- if (pli.global_players.containsKey(p)) {
- sender.sendMessage(" " + pli.getPlugin().getName());
- }
- }
- sender.sendMessage("~ global_lost: ");
- for (PluginInstance pli : pinstances.values()) {
- if (pli.global_lost.containsKey(p)) {
- sender.sendMessage(" " + pli.getPlugin().getName());
- }
- }
- sender.sendMessage("~ SpectatorManager: ");
- for (PluginInstance pli : pinstances.values()) {
- if (pli.getSpectatorManager().isSpectating(Bukkit.getPlayer(p))) {
- sender.sendMessage(" " + pli.getPlugin().getName());
- }
- }
- sender.sendMessage("~ Arenas: ");
- for (PluginInstance pli : pinstances.values()) {
- if (pli.global_players.containsKey(p)) {
- sender.sendMessage(" " + pli.global_players.get(p).getInternalName() + " - " + pli.global_players.get(p).getArenaState());
- }
- }
- } else {
- for (PluginInstance pli : pinstances.values()) {
- sender.sendMessage("~ All players for " + pli.getPlugin().getName() + ": ");
- for (Arena a : pli.getArenas()) {
- if (a != null) {
- for (String p_ : a.getAllPlayers()) {
- sender.sendMessage(ChatColor.GRAY + " " + pli.getPlugin().getName() + " " + a.getInternalName() + " " + p_);
- }
- }
- }
- }
- }
- } else if (args[0].equalsIgnoreCase("debug")) {
- debug = !debug;
- this.getConfig().set("config.debug", debug);
- this.saveConfig();
- sender.sendMessage(ChatColor.GOLD + "Debug mode is now: " + debug);
- } else if (args[0].equalsIgnoreCase("list")) {
- int c = 0;
- for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) {
- c++;
- sender.sendMessage("~ " + pli.getPlugin().getName() + ": " + pli.getArenas().size() + " Arenas");
- }
- if (c < 1) {
- sender.sendMessage("~ No installed minigames found! Download/Install some from the project page.");
- }
- } else if (args[0].equalsIgnoreCase("restartserver")) {
- if (sender.isOp()) {
- Util.restartServer();
- }
- } else if (args[0].equalsIgnoreCase("title")) {
- if (args.length > 1) {
- if (sender instanceof Player) {
- Effects.playTitle((Player) sender, args[1], 0);
- }
- }
- } else if (args[0].equalsIgnoreCase("subtitle")) {
- if (args.length > 1) {
- if (sender instanceof Player) {
- Effects.playTitle((Player) sender, args[1], 1);
- }
- }
- } else if (args[0].equalsIgnoreCase("hologram")) {
- if (sender instanceof Player) {
- Player p = (Player) sender;
- p.sendMessage("Playing hologram.");
- Effects.playHologram(p, p.getLocation(), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "TEST", true, true);
- }
- } else if (args[0].equalsIgnoreCase("statshologram")) {
- if (sender instanceof Player) {
- Player p = (Player) sender;
- if (args.length > 1) {
- PluginInstance pli = getPluginInstance((JavaPlugin) Bukkit.getPluginManager().getPlugin(args[1]));
- p.sendMessage("Playing statistics hologram.");
-
- Effects.playHologram(p, p.getLocation().add(0D, 1D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Wins: " + pli.getStatsInstance().getWins(p.getName()), false, false);
- Effects.playHologram(p, p.getLocation().add(0D, 0.75D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Points: " + pli.getStatsInstance().getPoints(p.getName()), false, false);
- Effects.playHologram(p, p.getLocation().add(0D, 0.5D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Kills: " + pli.getStatsInstance().getKills(p.getName()), false, false);
- Effects.playHologram(p, p.getLocation().add(0D, 0.25D, 0D), ChatColor.values()[(int) (Math.random() * ChatColor.values().length - 1)] + "Deaths: " + pli.getStatsInstance().getDeaths(p.getName()), false, false);
-
- }
- }
- } else if (args[0].equalsIgnoreCase("protocol")) {
- if (sender instanceof Player) {
- Player p = (Player) sender;
- if (args.length > 1) {
- p = Bukkit.getPlayer(args[1]);
- }
- if (p != null) {
- int version = Effects.getClientProtocolVersion(p);
- sender.sendMessage("Protocol version of " + p.getName() + ": " + version);
- }
- }
- } else if (args[0].equalsIgnoreCase("gamemodetest")) {
- if (sender instanceof Player) {
- Player p = (Player) sender;
- if (p.isOp()) {
- Effects.sendGameModeChange(p, 3);
- }
- }
- } else if (args[0].equalsIgnoreCase("bungeetest")) {
- if (sender instanceof Player) {
- Player p = (Player) sender;
- if (p.isOp()) {
- PluginInstance pli = this.pinstances.get(Bukkit.getPluginManager().getPlugin("MGSkyWars"));
- BungeeSocket.sendSignUpdate(pli, pli.getArenas().get(0));
- }
- }
- }
- return true;
- }
- if (args.length < 1) {
- sender.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "MinigamesLib <3 " + this.getDescription().getVersion());
- int c = 0;
- for (PluginInstance pli : MinigamesAPI.getAPI().pinstances.values()) {
- c++;
- sender.sendMessage("~ " + ChatColor.GRAY + pli.getPlugin().getName() + ": " + ChatColor.WHITE + pli.getArenas().size() + " Arenas");
- }
- if (c < 1) {
- sender.sendMessage("~ No installed minigames found! Download/Install some from the project page.");
- }
- sender.sendMessage(ChatColor.GOLD + "Subcommands: ");
- sender.sendMessage("/mapi info ");
- sender.sendMessage("/mapi debug");
- sender.sendMessage("/mapi list");
- sender.sendMessage("/mapi title ");
- sender.sendMessage("/mapi subtitle ");
- sender.sendMessage("/mapi restartserver");
- sender.sendMessage("/mapi hologram");
- sender.sendMessage("/mapi protocol ");
- sender.sendMessage("/mapi ");
- sender.sendMessage("/mapi setstatshologram");
- }
- if (sender instanceof Player && args.length > 0) {
- Player p = (Player) sender;
- boolean cont = false;
- for (ParticleEffectNew f : ParticleEffectNew.values()) {
- if (f.name().equalsIgnoreCase(args[0])) {
- cont = true;
- }
- }
- if (!cont) {
- sender.sendMessage(ChatColor.RED + "Couldn't find particle effect.");
- return true;
- }
- ParticleEffectNew eff = ParticleEffectNew.valueOf(args[0]);
- eff.setId(152);
-
- for (float i = 0; i < 10; i++) {
- eff.animateReflected(p, p.getLocation().clone().add(i / 5F, i / 5F, i / 5F), 1F, 2);
- }
-
- p.getWorld().playEffect(p.getLocation(), Effect.STEP_SOUND, 152);
- p.getWorld().playEffect(p.getLocation().add(0D, 1D, 0D), Effect.STEP_SOUND, 152);
- }
- }
- return true;
- }
+import net.milkbowl.vault.economy.Economy;
- @Override
- public void onPluginMessageReceived(String channel, Player player, byte[] message) {
- if (!channel.equals("BungeeCord")) {
- return;
- }
- ByteArrayDataInput in = ByteStreams.newDataInput(message);
- String subchannel = in.readUTF();
- System.out.println(subchannel);
- if (subchannel.equals("MinigamesLibBack")) {
- short len = in.readShort();
- byte[] msgbytes = new byte[len];
- in.readFully(msgbytes);
+/**
+ * Main minigames API; plugin mplementation.
+ *
+ * @author instancelabs
+ *
+ */
+public class MinigamesAPI extends JavaPlugin implements PluginMessageListener, Listener
+{
+
+ /** the overall minecraft server versioon. */
+ public static final MinecraftVersionsType SERVER_VERSION = MinigamesAPI.getServerVersion();
+
+ /** the locale to be used. TODO: Change via config */
+ public static Locale LOCALE = Locale.ENGLISH;
+
+ /** the minigames plugin instance. */
+ private static MinigamesAPI instance = null;
+
+ /**
+ * Vault economy instance.
+ *
+ * @deprecated will be private and non-static in 1.5.0; replaced by new method
+ */
+ @Deprecated
+ public static Economy econ = null;
+
+ /**
+ * {@code true} if economy is installed.
+ *
+ * @deprecated will be private and non-static in 1.5.0, replace by {@link #economyAvailable()}
+ */
+ @Deprecated
+ public static boolean economy = true;
+
+ /**
+ * {@code true} if crackshot is installed.
+ *
+ * @deprecated will be private in 1.5.0, replace by {@link #crackshotAvailable()}
+ */
+ @Deprecated
+ public boolean crackshot = false;
+
+ /** a global debug flag; controls the output of finer debug messages. */
+ public static boolean debug = false;
+
+ /**
+ * @deprecated will be removed in 1.5.0
+ */
+ @Deprecated
+ int updatetime = 20 * 10;
+
+ /**
+ * Party per owning player
+ */
+ private HashMap global_party = new HashMap<>();
+
+ /**
+ * Invites per player
+ */
+ private HashMap> global_party_invites = new HashMap<>();
+
+ /**
+ * Hash map with internal plugin representations of each registered minigame.
+ *
+ * @deprecated will be private in 1.5.0; replaced by {@link #getPluginInstance(JavaPlugin)}
+ */
+ @Deprecated
+ public static HashMap pinstances = new HashMap<>();
+
+ /**
+ * The party messages.
+ *
+ * @deprecated will be private in 1.5.0; replaced by new methods.
+ */
+ @Deprecated
+ public PartyMessagesConfig partymessages;
+
+ /**
+ * The stats config.
+ *
+ * @deprecated will be private in 1.5.0; replaced by new methods.
+ */
+ @Deprecated
+ public StatsGlobalConfig statsglobal;
+
+ /**
+ * textual server version.
+ *
+ * @deprecated will be removed in 1.5.0; replaced by SERVER_VERSION enumeration.
+ */
+ @Deprecated
+ public String internalServerVersion = ""; //$NON-NLS-1$
+
+ /**
+ * {@code true} if this is below 1.7.10
+ *
+ * @deprecated will be removed in 1.5.0; replaced by SERVER_VERSION enumeration.
+ */
+ public boolean below1710 = false;
+
+ /**
+ * The plugin metrics report.
+ */
+ Metrics metrics;
+
+ /** the current motd */
+ private String motd;
+
+ /** suppliers or the motd strings. */
+ private Iterator> motdStrings = Collections.emptyIterator();
+
+ /** the lobby sign manager. */
+ private final LobbySignManager signManager = new LobbySignManager(this);
+
+ @Override
+ public void onEnable()
+ {
+ MinigamesAPI.instance = this;
+
+ this.internalServerVersion = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1); //$NON-NLS-1$
+ this.below1710 = MinigamesAPI.SERVER_VERSION.isBelow(MinecraftVersionsType.V1_7_R4);
+ this.getLogger().info(String.format("§c§lLoaded MinigamesAPI. We're on %0$s.", MinigamesAPI.SERVER_VERSION.name())); //$NON-NLS-1$
+
+ this.getServer().getMessenger().registerOutgoingPluginChannel(this, ChannelStrings.CHANNEL_BUNGEE_CORD);
+ this.getServer().getMessenger().registerIncomingPluginChannel(this, ChannelStrings.CHANNEL_BUNGEE_CORD, this);
+
+ if (!this.setupEconomy())
+ {
+ this.getLogger().severe(String.format("[%s] - No Economy (Vault) dependency found! Disabling Economy.", this.getDescription().getName())); //$NON-NLS-1$
+ MinigamesAPI.economy = false;
+ }
+
+ this.getConfig().options().header("Want bugfree versions? Set this to true for automatic updates:"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.AUTO_UPDATING, true);
+ this.getConfig().addDefault(PluginConfigStrings.POST_METRICS, true);
+ this.getConfig().addDefault(PluginConfigStrings.SIGNS_UPDATE_TIME, 20);
+ this.getConfig().addDefault(PluginConfigStrings.PARTY_COMMAND_ENABLED, true);
+ this.getConfig().addDefault(PluginConfigStrings.DEBUG, false);
+
+ this.getConfig().addDefault(PluginConfigStrings.PERMISSION_PREFIX, "ancient.core"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.PERMISSION_KITS_PREFIX, "ancient.core.kits"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.PERMISSION_GUN_PREFIX, "ancient.core.guns"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.PERMISSION_SHOP_PREFIX, "ancient.core.shopitems"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.PERMISSION_GAME_PREFIX, "ancient."); //$NON-NLS-1$
+
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_ENABLED, false);
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_ROTATION_SECONDS, 15);
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_TEXT, " arena : /"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_JOIN, "JOIN"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_STARTING, "STARTING"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_INGAME, "INGAME"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_RESTARTING, "RESTARTING"); //$NON-NLS-1$
+ this.getConfig().addDefault(PluginConfigStrings.MOTD_STATE_DISABLED, "DISABLED"); //$NON-NLS-1$
+
+ for (final ArenaState state : ArenaState.values())
+ {
+ this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".0", state.getColorCode() + "");
+ this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".1", state.getColorCode() + "");
+ this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".2", state.getColorCode() + "/");
+ this.getConfig().addDefault("signs." + state.name().toLowerCase() + ".3", state.getColorCode() + "");
+ }
+ this.getConfig().addDefault("signs.spec.0", "&aSPECTATE");
+ this.getConfig().addDefault("signs.spec.1", "&a");
+ this.getConfig().addDefault("signs.spec.2", "&a");
+ this.getConfig().addDefault("signs.spec.3", "&a/