public class FossilCleanerBlockEntity extends BlockEntity implements MenuProvider {
private final ItemStackHandler itemHandler = new ItemStackHandler(5);
text
private static final int INPUT_SLOT = 0;
private static final int INPUT_SLOT2 = 4;
private static final int OUTPUT_SLOT = 1;
private static final int OUTPUT_SLOT2 = 2;
private static final int OUTPUT_SLOT3 = 3;
public class FossilCleaningRecipe implements Recipe {
private final NonNullList inputItems;
private final ItemStack output;
private final ResourceLocation id;
@Override
public boolean canCraftInDimensions(int pWidth, int pHeight) {
return true;
}
@Override
public ItemStack getResultItem(RegistryAccess pRegistryAccess) {
return output.copy();
}
@Override
public ResourceLocation getId() {
return id;
}
@Override
public RecipeSerializer<?> getSerializer() {
return Serializer.INSTANCE;
}
@Override
public RecipeType<?> getType() {
return Type.INSTANCE;
}
public static class Type implements RecipeType {
public static final Type INSTANCE = new Type();
public static final String ID = "fossil_cleaning";
}
public static class Serializer implements RecipeSerializer {
public static final Serializer INSTANCE = new Serializer();
public static final ResourceLocation ID = new ResourceLocation(PrehistoricAscension.MOD_ID, "fossil_cleaning");
These will be the random outputs all with different chances of being these items
Bones, bonemeal, coal, deepslate, cobblestone, sand, or the random fossil
For the random fossil make it so it will choose out of a tag
Please send all of the classes back fully so I can easily copy paste them with the fixes
Below are two complete, updated classes that implement your desired behavior. In these versions:
The recipe now “displays” an output (for JEI) but when crafting the block‐entity asks the recipe for a freshly generated, random output.
Each of the three output slots gets its own random result chosen using weighted chances.
One of the weighted options is “a random fossil” which is selected from a tag (make sure you have defined the tag prehistoricascension:fossils in your data pack).
Some helper methods (and the weighted selection helper class) have been added to make the code more readable.
Make sure to adjust any imports if your environment differs.
FossilCleanerBlockEntity.java
java
package net.newt.prehistoricascension.block.entity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.Containers;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ContainerData;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import net.newt.prehistoricascension.recipe.FossilCleaningRecipe;
import net.newt.prehistoricascension.screen.FossilCleanerMenu;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
public class FossilCleanerBlockEntity extends BlockEntity implements MenuProvider {
private final ItemStackHandler itemHandler = new ItemStackHandler(5);
// Input/Output slot constants
private static final int INPUT_SLOT = 0;
private static final int INPUT_SLOT2 = 4;
private static final int OUTPUT_SLOT = 1;
private static final int OUTPUT_SLOT2 = 2;
private static final int OUTPUT_SLOT3 = 3;
private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty();
protected final ContainerData data;
private int progress = 0;
private int maxProgress = 78;
public FossilCleanerBlockEntity(BlockPos pos, BlockState state) {
super(ModBlockEntities.FOSSIL_CLEANER.get(), pos, state);
this.data = new ContainerData() {
@Override
public int get(int index) {
return switch (index) {
case 0 -> FossilCleanerBlockEntity.this.progress;
case 1 -> FossilCleanerBlockEntity.this.maxProgress;
default -> 0;
};
}
@Override
public void set(int index, int value) {
switch (index) {
case 0 -> FossilCleanerBlockEntity.this.progress = value;
case 1 -> FossilCleanerBlockEntity.this.maxProgress = value;
}
}
@Override
public int getCount() {
return 2;
}
};
}
public void drops() {
SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots());
for (int i = 0; i < itemHandler.getSlots(); i++) {
inventory.setItem(i, itemHandler.getStackInSlot(i));
}
Containers.dropContents(this.level, this.worldPosition, inventory);
}
@Override
public Component getDisplayName() {
return Component.translatable("block.prehistoricascension.fossil_cleaner");
}
@Override
public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
if (cap == ForgeCapabilities.ITEM_HANDLER) {
return lazyItemHandler.cast();
}
return super.getCapability(cap, side);
}
@Override
public void onLoad() {
super.onLoad();
lazyItemHandler = LazyOptional.of(() -> itemHandler);
}
@Override
public void invalidateCaps() {
super.invalidateCaps();
lazyItemHandler.invalidate();
}
@Override
public @Nullable AbstractContainerMenu createMenu(int containerId, Inventory playerInventory, Player player) {
return new FossilCleanerMenu(containerId, playerInventory, this, this.data);
}
@Override
protected void saveAdditional(CompoundTag tag) {
tag.put("inventory", itemHandler.serializeNBT());
tag.putInt("fossil_cleaner.progress", progress);
super.saveAdditional(tag);
}
@Override
public void load(CompoundTag tag) {
super.load(tag);
itemHandler.deserializeNBT(tag.getCompound("inventory"));
progress = tag.getInt("fossil_cleaner.progress");
}
public void tick(Level level, BlockPos pos, BlockState state) {
if(hasRecipe()) {
increaseCraftingProgress();
setChanged(level, pos, state);
if(hasProgressFinished()) {
craftItem();
resetProgress();
}
} else {
resetProgress();
}
}
private void resetProgress() {
progress = 0;
}
private void craftItem() {
Optional<FossilCleaningRecipe> recipeOptional = getCurrentRecipe();
if (recipeOptional.isEmpty())
return;
FossilCleaningRecipe recipe = recipeOptional.get();
// Remove one from each input slot
this.itemHandler.extractItem(INPUT_SLOT, 1, false);
this.itemHandler.extractItem(INPUT_SLOT2, 1, false);
// For each output slot, generate a random output via the recipe.
for (int i = 0; i < 3; i++) {
// Generate a new random output for each slot.
ItemStack output = recipe.getRandomOutput(this.level.registryAccess());
int outputSlot = OUTPUT_SLOT + i;
// If the slot is empty, simply set the output.
if(this.itemHandler.getStackInSlot(outputSlot).isEmpty()) {
this.itemHandler.setStackInSlot(outputSlot, output);
}
// Else if the item is the same, merge the stacks (up to the max stack size).
else if(this.itemHandler.getStackInSlot(outputSlot).is(output.getItem())) {
ItemStack existing = this.itemHandler.getStackInSlot(outputSlot);
int newCount = Math.min(existing.getCount() + output.getCount(), existing.getMaxStackSize());
existing.setCount(newCount);
}
// Otherwise, if the slot contains a different item, you might want to drop the item in the world.
// (Here we simply skip it.)
}
}
private boolean hasProgressFinished() {
return progress >= maxProgress;
}
private void increaseCraftingProgress() {
progress++;
}
private boolean hasRecipe() {
Optional<FossilCleaningRecipe> recipeOptional = getCurrentRecipe();
if(recipeOptional.isEmpty()) {
return false;
}
// Check that both inputs are present.
SimpleContainer inventory = new SimpleContainer(this.itemHandler.getSlots());
for(int i = 0; i < itemHandler.getSlots(); i++) {
inventory.setItem(i, this.itemHandler.getStackInSlot(i));
}
// Also check that at least one output slot is available.
return recipeOptional.get().matches(inventory, level) && hasEmptyOrMergableOutput();
}
private boolean hasEmptyOrMergableOutput() {
// At least one output slot must be empty or mergeable.
for (int i = 0; i < 3; i++) {
ItemStack stack = this.itemHandler.getStackInSlot(OUTPUT_SLOT + i);
if(stack.isEmpty() || stack.getCount() < stack.getMaxStackSize()) {
return true;
}
}
return false;
}
private Optional<FossilCleaningRecipe> getCurrentRecipe() {
SimpleContainer inventory = new SimpleContainer(this.itemHandler.getSlots());
for (int i = 0; i < itemHandler.getSlots(); i++) {
inventory.setItem(i, this.itemHandler.getStackInSlot(i));
}
return this.level.getRecipeManager().getRecipeFor(FossilCleaningRecipe.Type.INSTANCE, inventory, level);
}
}
FossilCleaningRecipe.java
java
Recipe JSON Example
Place the following JSON in your datapack (for example, under data/prehistoricascension/recipes/fossil_cleaning.json):
Note: The output given in the JSON is only used to display the recipe in JEI and similar tools; the block entity calls getRandomOutput(...) at craft time to randomly choose one of the seven weighted items.
You can now copy-paste these two classes into your mod. Remember to also define your fossil tag (for example: data/prehistoricascension/tags/items/fossils.json) so that the random fossil picker works correctly. Enjoy cleaning those fossils!
package net.newt.prehistoricascension.recipe;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.core.NonNullList;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.Holder;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.Level;
import net.newt.prehistoricascension.PrehistoricAscension;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* In this recipe, the output is generated randomly at craft time.
* The JSON output is only used for display (JEI) purposes.
*/
public class FossilCleaningRecipe implements Recipe<SimpleContainer> {
private final NonNullList<Ingredient> inputItems;
private final ItemStack displayOutput;
private final ResourceLocation id;
// Constructor: the display output is not used at craft time.
public FossilCleaningRecipe(NonNullList<Ingredient> inputItems, ItemStack displayOutput, ResourceLocation id) {
this.inputItems = inputItems;
this.displayOutput = displayOutput;
this.id = id;
}
@Override
public boolean matches(SimpleContainer container, Level level) {
if(level.isClientSide()) {
return false;
}
// We assume the recipe expects two inputs: slot 0 and slot 4.
return inputItems.get(0).test(container.getItem(0)) &&
inputItems.get(1).test(container.getItem(4));
}
/**
* This method is no longer used for crafting,
* as we use getRandomOutput() instead.
*/
@Override
public ItemStack assemble(SimpleContainer container, RegistryAccess registryAccess) {
return displayOutput.copy();
}
@Override
public boolean canCraftInDimensions(int width, int height) {
return true;
}
@Override
public ItemStack getResultItem(RegistryAccess registryAccess) {
return displayOutput.copy();
}
@Override
public ResourceLocation getId() {
return id;
}
@Override
public RecipeSerializer<?> getSerializer() {
return Serializer.INSTANCE;
}
@Override
public RecipeType<?> getType() {
return Type.INSTANCE;
}
/**
* Generates a random output based on weighted chances.
* The possible items are:
* - Bone
* - Bone Meal
* - Coal
* - Deepslate
* - Cobblestone
* - Sand
* - A random fossil (from the tag "prehistoricascension:fossils")
*/
public ItemStack getRandomOutput(RegistryAccess registryAccess) {
WeightedRandom<ItemStack> weightedOutputs = new WeightedRandom<>();
// Weights for each output
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.BONE), 20));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.BONE_MEAL), 15));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.COAL), 10));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.DEEPSLATE), 8));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.COBBLESTONE), 8));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(Items.SAND), 8));
// For the random fossil, we pull all items from the tag.
TagKey<Item> fossilTag = TagKey.create(Registry.ITEM_REGISTRY, new ResourceLocation("prehistoricascension", "fossils"));
Registry<Item> itemRegistry = registryAccess.registry(Registry.ITEM_REGISTRY).orElse(null);
if (itemRegistry != null) {
// Get a list of items from the fossil tag.
List<Item> fossilItems = new ArrayList<>();
// The registry returns holders for tagged items.
itemRegistry.getTag(fossilTag).ifPresent(holderSet -> {
for (Holder<Item> holder : holderSet) {
fossilItems.add(holder.value());
}
});
if (!fossilItems.isEmpty()) {
// Choose a random fossil from the list and add it as an option.
Item randomFossil = fossilItems.get(RandomHolder.RANDOM.nextInt(fossilItems.size()));
weightedOutputs.add(new WeightedRandom.WeightedEntry<>(new ItemStack(randomFossil), 10));
}
}
return weightedOutputs.getRandom(RandomHolder.RANDOM);
}
public NonNullList<Ingredient> getIngredients() {
return inputItems;
}
// --- Recipe Type and Serializer ---
public static class Type implements RecipeType<FossilCleaningRecipe> {
public static final Type INSTANCE = new Type();
public static final String ID = "fossil_cleaning";
}
public static class Serializer implements RecipeSerializer<FossilCleaningRecipe> {
public static final Serializer INSTANCE = new Serializer();
public static final ResourceLocation ID = new ResourceLocation(PrehistoricAscension.MOD_ID, "fossil_cleaning");
@Override
public FossilCleaningRecipe fromJson(ResourceLocation recipeId, JsonObject json) {
// The output element is only used for display
JsonObject outputObj = GsonHelper.getAsJsonObject(json, "output");
ItemStack displayOutput = ShapedRecipe.itemStackFromJson(outputObj);
JsonArray ingredients = GsonHelper.getAsJsonArray(json, "ingredients");
NonNullList<Ingredient> inputs = NonNullList.withSize(2, Ingredient.EMPTY);
for (int i = 0; i < inputs.size(); i++) {
inputs.set(i, Ingredient.fromJson(ingredients.get(i)));
}
return new FossilCleaningRecipe(inputs, displayOutput, recipeId);
}
@Override
public @Nullable FossilCleaningRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) {
int ingredientsSize = buffer.readInt();
NonNullList<Ingredient> inputs = NonNullList.withSize(ingredientsSize, Ingredient.EMPTY);
for (int i = 0; i < ingredientsSize; i++) {
inputs.set(i, Ingredient.fromNetwork(buffer));
}
ItemStack displayOutput = buffer.readItem();
return new FossilCleaningRecipe(inputs, displayOutput, recipeId);
}
@Override
public void toNetwork(FriendlyByteBuf buffer, FossilCleaningRecipe recipe) {
buffer.writeInt(recipe.inputItems.size());
for (Ingredient ingredient : recipe.getIngredients()) {
ingredient.toNetwork(buffer);
}
buffer.writeItemStack(recipe.getResultItem(null), false);
}
}
/**
* A helper class for weighted random selection.
*/
public static class WeightedRandom<T> {
private final List<WeightedEntry<T>> entries = new ArrayList<>();
private double totalWeight = 0;
public void add(WeightedEntry<T> entry) {
entries.add(entry);
totalWeight += entry.weight;
}
public T getRandom(Random random) {
if (entries.isEmpty())
return null;
double r = random.nextDouble() * totalWeight;
double cumulativeWeight = 0;
for (WeightedEntry<T> entry : entries) {
cumulativeWeight += entry.weight;
if (r <= cumulativeWeight) {
return entry.item;
}
}
return entries.get(entries.size() - 1).item;
}
public static class WeightedEntry<T> {
public final T item;
public final double weight;
public WeightedEntry(T item, double weight) {
this.item = item;
this.weight = weight;
}
}
}
/**
* A holder class for a shared Random instance.
*/
private static class RandomHolder {
private static final Random RANDOM = new Random();
}
}