@@ -83,23 +83,60 @@ private int getCraftableUnits(Recipe recipe) {
8383 Integer minCraftableUnits = null ;
8484 List <Ingredient > ingredients = recipe .getIngredients ();
8585
86- // Check the existence of the crafting table within inventory if the recipe
87- // required it
86+ // Take a snapshot of current inventory
87+ HashMap <Item , Integer > inventorySnapshot = new HashMap <Item , Integer >();
88+
89+ for (Ingredient ingredient : ingredients ) {
90+ Item item = ingredient .getItem ();
91+ inventorySnapshot .put (item , this .inventory .getItemQuantity (item ));
92+ }
93+
94+ // Track crafting table if needed
95+ Item craftingTable = null ;
96+ List <Ingredient > craftingTableIngredients = null ;
97+
8898 if (recipe .needsCraftingTable ()) {
89- Item craftingTable = recipe .getCraftingTable ();
99+ craftingTable = recipe .getCraftingTable ();
90100 int quantityInInventory = this .inventory .getItemQuantity (craftingTable );
91101
92- // If crafting table is not in inventory return
93102 if (quantityInInventory < 1 ) {
94- return 0 ;
103+ // If crafting table is not in inventory, check if it is craftable
104+ if (!craftingTable .isBase ()) {
105+ int maxCraftable = 0 ;
106+ Recipe bestRecipe = null ;
107+
108+ for (Recipe tableRecipe : craftingTable .getRecipes ()) {
109+ int craftableUnits = getCraftableUnits (tableRecipe );
110+
111+ if (craftableUnits > maxCraftable ) {
112+ maxCraftable = craftableUnits ;
113+ bestRecipe = tableRecipe ;
114+ }
115+ }
116+
117+ if (maxCraftable < 1 ) {
118+ return 0 ;
119+ }
120+ // Subtract ingredients needed for crafting table from inventory snapshot
121+ craftingTableIngredients = bestRecipe .getIngredients ();
122+
123+ for (Ingredient ctIng : craftingTableIngredients ) {
124+ Item ctItem = ctIng .getItem ();
125+ int ctQty = ctIng .getQuantity ();
126+ inventorySnapshot .put (ctItem ,
127+ inventorySnapshot .getOrDefault (ctItem , this .inventory .getItemQuantity (ctItem )) - ctQty );
128+ }
129+ } else {
130+ return 0 ;
131+ }
95132 }
96133 }
97134
98135 // Check the existence of each required ingredient to craft the recipe
99136 for (Ingredient ingredient : ingredients ) {
100137 Item item = ingredient .getItem ();
101138 int requiredQuantity = ingredient .getQuantity ();
102- int quantityInInventory = this .inventory .getItemQuantity (item );
139+ int quantityInInventory = inventorySnapshot . getOrDefault ( item , this .inventory .getItemQuantity (item ) );
103140
104141 int totalAvailable = quantityInInventory ;
105142
0 commit comments