Skip to content

Instantly share code, notes, and snippets.

@seanc
Created November 21, 2015 02:57
Show Gist options
  • Save seanc/1893e38f242ad5341e4d to your computer and use it in GitHub Desktop.
Save seanc/1893e38f242ad5341e4d to your computer and use it in GitHub Desktop.
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.HashSet;
import java.util.Set;
class CommandTest implements CommandExecutor {
private final Set<Subcommand> subcommands = new HashSet<>();
{
subcommands.add(new SuicideCommand());
subcommands.add(new EchoCommand());
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
for(Subcommand sub : subcommands) {
if(sub.getLabel().equalsIgnoreCase(args[0])) {
return sub.onCommand(commandSender, args);
}
}
// If no subcommands could handle this.
commandSender.sendMessage("Invalid subcommand");
return false;
}
}
/**
* Template for a subcommand
*/
abstract class Subcommand {
private final String label;
/**
* Should be called by subclass with the appropriate label
* @param label Label of the subcommand
*/
public Subcommand(String label) {
this.label = label;
}
/**
* Gets the label of the subcommand
* @return The label of the subcommand.
*/
public final String getLabel() {
return this.label;
}
/**
* Execute a subcommand if the name matches the first argument of the main command.
* @param commandSender The sender of the command.
* @param args Arguments, starting with the label of the subcommand
* @return true if the command was processed successfully.
*/
public abstract boolean onCommand(CommandSender commandSender, String[] args);
}
/**
* SuicideCommand can only be excecuted by a player, who will recieve a message
*/
final class SuicideCommand extends Subcommand {
public SuicideCommand() {
super("suicide");
}
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
if(commandSender instanceof Player) {
commandSender.sendMessage("Killing you");
((Player) commandSender).setHealth(0D);
// Command handled
return true;
}
// Not a player ;(
return false;
}
}
/**
* EchoCommand can only be executed by the console, who will have the args repeated to them
*/
final class EchoCommand extends Subcommand {
public EchoCommand() {
super("kickall");
}
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
if(commandSender instanceof Player) {
commandSender.sendMessage("Can only be sent by console");
// Not console
return false;
}
StringBuilder toEcho = new StringBuilder();
for(String string : args) {
toEcho.append(string).append(' ');
}
commandSender.sendMessage(toEcho.toString());
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment