Volver al índice
src/main/java/ar/com/companeros/Crafting.java
package ar.com.companeros;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.TransientCraftingContainer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.item.crafting.ShapedRecipe;
/** Usa recetas del servidor y una copia del inventario: no inventa recursos. */
public final class Crafting {
private Crafting() { }
public static boolean make(Companion bot, Item wanted) {
boolean table = false;
for (var pos : net.minecraft.core.BlockPos.betweenClosed(bot.blockPosition().offset(-4, -2, -4),
bot.blockPosition().offset(4, 2, 4))) {
if (bot.serverLevel().hasChunkAt(pos) && bot.level().getBlockState(pos).is(net.minecraft.world.level.block.Blocks.CRAFTING_TABLE)) {
table = true; break;
}
}
return make(bot.serverLevel(), bot.bag, wanted, table);
}
public static boolean make(ServerLevel level, SimpleContainer inventory, Item wanted, boolean workbench) {
for (CraftingRecipe recipe : level.getRecipeManager().getAllRecipesFor(RecipeType.CRAFTING)) {
if (!recipe.getResultItem(level.registryAccess()).is(wanted)) continue;
if (!workbench && !recipe.canCraftInDimensions(2, 2)) continue;
SimpleContainer scratch = new SimpleContainer(inventory.getContainerSize());
for (int i = 0; i < inventory.getContainerSize(); i++) scratch.setItem(i, inventory.getItem(i).copy());
var matrix = new TransientCraftingContainer(new AbstractContainerMenu(null, -1) {
@Override public ItemStack quickMoveStack(Player player, int slot) { return ItemStack.EMPTY; }
@Override public boolean stillValid(Player player) { return false; }
}, 3, 3);
boolean enough = true;
int width = recipe instanceof ShapedRecipe shaped ? shaped.getWidth() : 3;
for (int n = 0; n < recipe.getIngredients().size(); n++) {
var ingredient = recipe.getIngredients().get(n);
if (ingredient.isEmpty()) continue;
int slot = -1;
for (int i = 0; i < scratch.getContainerSize(); i++) {
if (!scratch.getItem(i).isEmpty() && ingredient.test(scratch.getItem(i))) { slot = i; break; }
}
if (slot < 0) { enough = false; break; }
matrix.setItem(n / width * 3 + n % width, scratch.removeItem(slot, 1));
}
if (!enough || !recipe.matches(matrix, level)) continue;
ItemStack result = recipe.assemble(matrix, level.registryAccess());
if (!scratch.addItem(result).isEmpty()) continue;
boolean room = true;
for (ItemStack remaining : recipe.getRemainingItems(matrix)) {
if (!remaining.isEmpty() && !scratch.addItem(remaining.copy()).isEmpty()) { room = false; break; }
}
if (!room) continue;
for (int i = 0; i < inventory.getContainerSize(); i++) inventory.setItem(i, scratch.getItem(i).copy());
return true;
}
return false;
}
}