Solved Check if item is in crafting recepie?

Discussion in 'Plugin Development' started by The_Nesko, Nov 24, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    The_Nesko

    Hello i was just wondering is there a way to check if a crafting recipe contains certain item that it needs to be crafted. For example if Furnace contains cobblestone in it's crafting recipe then execute the code in the if statement.
     
  2. Offline

    Abstract97

    @The_Nesko

    Code:java
    1.  
    2.  
    3. //Get the recipe iterator from Bukkit, which contains all of the registered
    4. //recipes on the server.
    5. Iterator<Recipe> recipes = Bukkit.getServer().recipeIterator();
    6.  
    7. //If the iterator has a next element this will be true.
    8. while (recipes.hasNext()) {
    9. //Using recipes.next(); this will retrieve the next element in the iterator,
    10. //which is the next recipe.
    11. Recipe rec = recipes.next();
    12.  
    13. //If the recipe is not equal to nothing, if the result for
    14. //that recipe is not equal to nothing and the type of the itemstack
    15. //is a furnace, the code continues.
    16. if (rec != null && rec.getResult() != null
    17. && rec.getResult().getType() == Material.FURNACE) {
    18. //Create a new list which will contain
    19. // all of the ingredients of the particular recipe.
    20. List<ItemStack> ingredients = null;
    21.  
    22. //As the recipe is an interface, we need to check the
    23. //current type of the recipe.
    24. if (rec instanceof ShapelessRecipe) {
    25. //If it is a shapeless recipe, cast the recipe to the ShapelessRecipe
    26. ShapelessRecipe slRec = (ShapelessRecipe) rec;
    27.  
    28. //Instantiates the ingredients list, by setting it to the
    29. //shapeless recipe's ingredient's list.
    30. ingredients = slRec.getIngredientList();
    31. } else if (rec instanceof ShapedRecipe) {
    32. //If it is a shaped recipe, cast the recipe to the ShapedRecipe
    33. ShapedRecipe slRec = (ShapedRecipe) rec;
    34.  
    35. //Instantiates the ingredients list, by creating a new
    36. //ArrayList and passing the shaped recipe's ingredient map's values, as it
    37. //returns a collection, not a list. This will put the collection into the ArrayList.
    38. ingredients = new ArrayList<ItemStack>(slRec
    39. .getIngredientMap().values());
    40. }
    41.  
    42. //If the list of ingredients is not equal to nothing and is not empty carry on.
    43. if (ingredients != null && !ingredients.isEmpty()) {
    44. //This will loop through all of the items in the list, required to make the furnace.
    45. for (ItemStack item : ingredients) {
    46. //All ingredients in making furnace
    47.  
    48. //If the itemstack is not equal to null, and the type (material) is equal to cobble
    49. //stone it will carry on.
    50. if(item != null
    51. && item.getType() == Material.COBBLE_STONE) {
    52. //Do your thing...
    53. //We break here so we don't continue looping through the rest
    54. //of the ingredients.
    55. break;
    56. }
    57. }
    58. }
    59. }
    60.  
    61. //We break here as we found the recipe we were looking for.
    62. break;
    63. }
    64. }


    To conclude, we loop through all of the registered recipes on the server, we check if the result is a furnace or whatever type you like, we then cast the recipe to either a ShapedRecipe or ShapelessRecipe, we can then get the ingredients, loop through them and check if the ingredients contain a particular ingredient, if so we break the loop and run whatever function you like.

    You could simply create a method with this code like so:

    Code:java
    1.  
    2. public boolean recipeContains(ItemStack recipeFor, ItemStack ingredient) {
    3. Iterator<Recipe> recipes = Bukkit.getServer().recipeIterator();
    4.  
    5. boolean contains = false;
    6.  
    7. while (recipes.hasNext()) {
    8. Recipe rec = recipes.next();
    9.  
    10. if (rec != null && rec.getResult() != null
    11. && rec.getResult().equals(recipeFor)) {
    12. List<ItemStack> ingredients = null;
    13.  
    14. if (rec instanceof ShapelessRecipe) {
    15. ShapelessRecipe slRec = (ShapelessRecipe) rec;
    16.  
    17. ingredients = slRec.getIngredientList();
    18. } else if (rec instanceof ShapedRecipe) {
    19. ShapedRecipe slRec = (ShapedRecipe) rec;
    20.  
    21. ingredients = new ArrayList<ItemStack>(slRec
    22. .getIngredientMap().values());
    23. }
    24.  
    25. if (ingredients != null && !ingredients.isEmpty()) {
    26. if (ingredients.contains(ingredient)) {
    27. contains = true;
    28. }
    29. }
    30. }
    31.  
    32. break;
    33. }
    34. }
    35. return contains;
    36. }


    *On a side note i wrote this up quite quickly and has not been tested.*
     
    Last edited: Nov 24, 2015
  3. Offline

    Scimiguy

    An explanation of the above spoonfed code would be helpful, at the least.
     
  4. Offline

    Abstract97

    @Scimiguy I assume the guy knows Java, so it should be pretty self explanatory. However i will add some more brief comments.

    EDIT: Seriously young man, i don't see what your problem is. I can see your point on why i should explain the code, however saying i am spoon feeding code is absurd, perhaps if i was giving him a few classes worth of code without explaining it that would have been true.
     
    Last edited: Nov 24, 2015
  5. Offline

    The_Nesko

    @Abstract97 I completely understand the code no need for extra comments but i'm still new to bukkit and bukkit forum so i was just wondering if there is any way to do this. The code works btw thanks for the help :)
     
  6. Offline

    Abstract97

    @The_Nesko Great! Glad i could have been of assistance, make sure to mark the thread as solved/filled! :)
     
  7. Offline

    The_Nesko

    @Abstract97 I tried your method for the above post but it didn't work i managed to find the error it's this part:
    Code:
    if (ingredients.contains(ingredient)) {
        return true;
    }
    
    But i don't know how to fix it any suggestions?
     
  8. Offline

    Abstract97

    @The_Nesko Can you screenshot the error? Can you send me the stack-trace in the console?
     
  9. Offline

    The_Nesko

    @Abstract97 Here it is.
    Code:
    [18:08:37 INFO]: The_Nesko issued server command: /test
    [18:08:37 ERROR]: null
    org.bukkit.command.CommandException: Unhandled exception executing command 'test
    ' in plugin XenoSurvival v1.0
            at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spi
    got-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:14
    1) ~[spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServe
    r.java:641) ~[spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerCon
    nection.java:1162) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java
    :997) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java
    :45) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java
    :1) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:1
    3) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [
    ?:1.8.0_66]
            at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_66]
            at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [spigot-1.8
    .8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:7
    15) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:3
    74) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:6
    54) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java
    :557) [spigot-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            at java.lang.Thread.run(Unknown Source) [?:1.8.0_66]
    Caused by: java.lang.NullPointerException
            at me.thenesko.rpgaddon.Main.containsItem(Main.java:97) ~[?:?]
            at me.thenesko.rpgaddon.Main.onCommand(Main.java:66) ~[?:?]
            at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spi
    got-1.8.8.jar:git-Spigot-5f38d38-12698ea]
            ... 15 more
    
     
  10. Offline

    Abstract97

    @The_Nesko

    Please provide code for this class:

    • Caused by: java.lang.NullPointerException
    • at me.thenesko.rpgaddon.Main.containsItem(Main.java:97) ~[?:?]
     
  11. Offline

    The_Nesko

    @Abstract97 Okay this is starting to confuse me a lot because now it doesn't show any errors but it still doesn't work.

    Here is the class:

    Code:
    package me.thenesko.rpgaddon;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.logging.Logger;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.Recipe;
    import org.bukkit.inventory.ShapedRecipe;
    import org.bukkit.inventory.ShapelessRecipe;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import me.thenesko.rpgaddon.skills.WoodCutter;
    
    public class Main extends JavaPlugin{
    
        PluginDescriptionFile pdfFile = getDescription();
        Logger logger = Logger.getLogger("Minecraft");
        XenoSkills xeno;
    
        public void onEnable() {    
              xeno = new XenoSkills(this);
              new WoodCutter(this);
            logger.info(pdfFile.getName() + " has been enabled (v." + pdfFile.getVersion() + ")");
        }
    
        public void onDisable() {
            logger.info(pdfFile.getName() + " has been disabled (v." + pdfFile.getVersion() + ")");
        }
    
        public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
        
            if (!(sender instanceof Player)) {
                sender.sendMessage("This plugin doesn't have any console commands!");
            }
    
            Player player = (Player) sender;
            int length = args.length;
        
            if (command.getName().equalsIgnoreCase("choseSkill")) {
            
                if (length == 0) {
                
                    xeno.showSkills(player);
                    return true;
                }
                else {
                
                    player.sendMessage(ChatColor.RED + "Something went wrong!");
                    return true;
                }    
            }
        
            if (command.getName().equalsIgnoreCase("test")) {        
                ItemStack item = new ItemStack(Material.COBBLESTONE);
                ItemStack recipe = new ItemStack(Material.FURNACE);
            
               Iterator<Recipe> recipes = Bukkit.getServer().recipeIterator();
               while (recipes.hasNext()) {
                   Recipe rec = recipes.next();
    
                   if (rec != null && rec.getResult() != null && rec.getResult().equals(recipe)) {
                   List<ItemStack> ingredients = null;
    
                       if (rec instanceof ShapelessRecipe) {
                           ShapelessRecipe slRec = (ShapelessRecipe) rec;
    
                       ingredients = slRec.getIngredientList();
                       } else if (rec instanceof ShapedRecipe) {
                           ShapedRecipe slRec = (ShapedRecipe) rec;
    
                           ingredients = new ArrayList<ItemStack>(slRec.getIngredientMap().values());
                       }
    
                       if (ingredients != null && !ingredients.isEmpty()) {
                           if (ingredients.contains(item)) {                        
                                 player.sendMessage("Working");
                           }
                      
                       }
                   }
                   break;
               } 
            
            }
                
            return false;
        }
        
    }
    
    This one doesn't show any errors but it's not working.
    The test command is where i'm trying to use your code so i can see if it works first.
     
  12. Offline

    Scimiguy

    Ok. Here we go!

    Don't steal Minecraft's Logger.

    Get rid of these line, Bukkit does this already for you.

    Get rid of this line, Bukkit does this already for you.

    Get rid of that empty method

    You're not returning from this, so console will still be running all your commands

    You don't need to create these two variables every time a command is run, or even the "length" one at all.

    You don't need to do this at all, if you don't care about any arguments, then just run the command per normal regardless of what they put in

    You're only checking if the Collection contains your Itemstack, which it won't.
     
    Abstract97 likes this.
  13. Offline

    The_Nesko

    @Scimiguy soo.. how do i do it right?
    I'm asking about this one?
    Code:
    if (ingredients.contains(item)) {
    player.sendMessage("Working");
    }
    
     
  14. Offline

    teej107

Thread Status:
Not open for further replies.

Share This Page