KnowledgeBookItem .java

net.minecraft.world.item.KnowledgeBookItem (class, 56 lines): members: use, LOGGER. imports: RecipeManager, RecipeHolder, Recipe, Stats, InteractionHand.

net.minecraft.world.itemclass56 linescommonextends Item1.7 KB

API Surface (1)

InteractionResult use(final Level level, final Player player, final InteractionHand hand)

Fields & Constants (1)

LOGGER

Full Source

KnowledgeBookItem.java56 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item;
2
3
import com.mojang.logging.LogUtils;
4
import java.util.ArrayList;
5
import java.util.List;
6
import java.util.Optional;
7
import net.minecraft.core.component.DataComponents;
8
import net.minecraft.resources.ResourceKey;
9
import net.minecraft.stats.Stats;
10
import net.minecraft.world.InteractionHand;
11
import net.minecraft.world.InteractionResult;
12
import net.minecraft.world.entity.player.Player;
13
import net.minecraft.world.item.crafting.Recipe;
14
import net.minecraft.world.item.crafting.RecipeHolder;
15
import net.minecraft.world.item.crafting.RecipeManager;
16
import net.minecraft.world.level.Level;
17
import org.slf4j.Logger;
18
19
public class KnowledgeBookItem extends Item {
20
	private static final Logger LOGGER = LogUtils.getLogger();
21
22
	public KnowledgeBookItem(final Item.Properties properties) {
23
		super(properties);
24
	}
25
26
	@Override
27
	public InteractionResult use(final Level level, final Player player, final InteractionHand hand) {
28
		ItemStack itemStack = player.getItemInHand(hand);
29
		List<ResourceKey<Recipe<?>>> recipeIds = itemStack.getOrDefault(DataComponents.RECIPES, List.of());
30
		itemStack.consume(1, player);
31
		if (recipeIds.isEmpty()) {
32
			return InteractionResult.FAIL;
33
		}
34
35
		if (!level.isClientSide()) {
36
			RecipeManager recipeManager = level.getServer().getRecipeManager();
37
			List<RecipeHolder<?>> recipes = new ArrayList<>(recipeIds.size());
38
39
			for (ResourceKey<Recipe<?>> recipeId : recipeIds) {
40
				Optional<RecipeHolder<?>> recipe = recipeManager.byKey(recipeId);
41
				if (!recipe.isPresent()) {
42
					LOGGER.error("Invalid recipe: {}", recipeId);
43
					return InteractionResult.FAIL;
44
				}
45
46
				recipes.add(recipe.get());
47
			}
48
49
			player.awardRecipes(recipes);
50
			player.awardStat(Stats.ITEM_USED.get(this));
51
		}
52
53
		return InteractionResult.SUCCESS;
54
	}
55
}
56

Decompiled Minecraft 26.3 source of KnowledgeBookItem (net/minecraft/world/item/KnowledgeBookItem.java) with Mojang official mappings, stored verbatim on the site.