Today we will be learning about healing and feeding!
First we are going to start by making a separate class for this command. Inside, we are going to pass the instance from our main class which contains our onEnable() and onDisable() methods.
We are also going to set the commandExecutor class and then call new commandClass(this); in our main class.
public Main plugin;
public commandClass(Main instance){
  this.plugin = instance
  plugin.getCommand("feed").setExecutor(this);
  plugin.getCommand("heal").setExecutor(this);
}
Now we will be creating the usual method that we start with when creating a plugin.
public void onCommand(CommandSender sender, Command command, String label, String[] args){
}
Inside our onCommand() method, we are going to check if the sender is an actual player and not the console, to do this we use an instanceof comparison.
if(!(sender instanceof Player)){ // If it is NOT a player.
  plugin.getLogger().log(Level.INFO, "Cannot use the command from here!");
  return false;
}
Time to check if the command that the method has retrieved is equal to heal or feed.
if(command.getName().equalsIgnoreCase("heal")){
  return false;
}
if (command.getName().equalsIgnoreCase("feed")){
  return false;
}
Right underneath the method parameters, we are going to add the following. We are basically saying that the sender of the message is a player, and not the console.
Player player = (Player) sender;
Inside our heal method, we are going to do the following things:
- Set their health.
- Send them a message.
player.setHealth(20); // (1)
player.sendMessage("You have been healed!"); // (2)
Inside our feed method, we are going to do the following things:
- Set their food level
- Send them a message
player.setFoodLevel(20); // (1)
player.sendMessage("Your appetite is now at its max!"); // (2)
To prevent a possible internal error, we are also going to make sure that the arguments length are equal to 0 which means that the command is exactly : /heal and not /heal Tom
if(!(args.length == 0)) { return; }
You might be asking, "Blessings, why are we setting their food and health to 20? There are only 10 hearts and 10 food symbols!"
The reason behind this is that when you damage a player, they can end up having half a heart. In that case, 10 hearts x 2 half hearts per heart is equal to 20 half hearts. Same for food.
Thanks for reading!