Uso Básico de Ítems

Advertencia

These docs were written for SpongeAPI 7 and are likely out of date. If you feel like you can help update them, please submit a PR!

Los ítems son representados mediante un ItemStack. Un ItemStack es un ítem de inventario con información como la cantidad del ítem en pilas, el tipo de ítem y datos extra como la durabilidad. Un :javadoc:`Ítem` en sí mismo es la representación gráfica de un ItemStack como una entidad. Tenga en cuenta que siempre obtendrá una copia y no el ItemStack real y en consecuencia, necesitará establecerlo de nuevo en un inventario si lo desea.

Verificación del Tipo de un Ítem

Checking the type of the item is very simple. You just need to call the ItemStack#getType() method.

import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.ItemStack;

public boolean isStick(ItemStack stack) {
    ItemType type = stack.getType();
    return type.equals(ItemTypes.STICK);
}

¿Ve qué simple es eso? Porque los palos se pueden apilar, podemos también averiguar cuántos están presentes.

Getting the number of items in an ItemStack is relatively easy. The ItemStack#getQuantity() method will handle this for us.

Modificación de Datos de ItemStack

La manipulación de datos como la durabilidad o la historia de un ítem se realiza simplemente utilizando claves. Solo necesita especificar la clave que necesita ser cambiada:

import org.spongepowered.api.data.key.Keys;

public void setUnbreakable(ItemStack stack) {
    stack.offer(Keys.UNBREAKABLE, true);
}

En esto, especificaremos que la clave Keys#UNBREAKABLE es la clave que quisiéramos cambiar. Entonces estableceremos su valor en verdad para implicar que el ítem nunca se romperá. Todo esto está incluido en el método offer() del ItemStack para regresar nuestros cambios a la ItemStack.

Different keys will require different values based on their job. For example, to change the lore of an item, one would need to specify a List of Component rather than a boolean or other value. It is also important to perform checks to see if the key can actually apply to the item. For example, some items might not have durability or may already have lore applied to the item.

import net.kyori.adventure.text.Component;

import java.util.List;

public void setLore(ItemStack stack, List<Component> itemLore) {
    if (stack.get(Keys.ITEM_LORE).isPresent()) {
        stack.offer(Keys.ITEM_LORE, itemLore);
    }
}

Nota

Almost all API methods that return an ItemStack only return a copy of it, so modifying it does not have any impact on the real stack (e.g. in an inventory). You have to explicitly set it for your changes to persist.

Propiedades del Ítem

Ciertos ítems pueden tener propiedades específicas. Por ejemplo, ciertos ítems pueden minar bloques específicos, como un pico de diamante para obsidiana. La propiedades son utilizadas para determinar si un ítem puede causar una acción sin realmente verificar el tipo del ítem. Podemos verificar si un ítem puede minar obsidiana utilizando al HarvestingProperty de ese ítem.

import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.data.property.item.HarvestingProperty;

import java.util.Optional;

public boolean canMineObsidian(ItemStack stack) {
    Optional<HarvestingProperty> optional =
        stack.getProperty(HarvestingProperty.class);

    if (optional.isPresent()) {
        HarvestingProperty property = optional.get();
        return property.getValue().contains(BlockTypes.OBSIDIAN);
    }
    return false;
}

Este código verificará si el ítem tiene una HarvestingProperty, como un pico. Si está presente, entonces devuelve si este ítem puede recoger obsidiana sin la necesidad de verificar el tipo del ítem. Es muy útil en caso de que un mod o una actualización de Minecraft agregue una nueva herramienta con la capacidad de minar obsidiana.

Comparación de ItemStacks

La clase ItemStack contiene un método ordenado para comparar dos ItemStacks. Utilizando el método ItemStack#equalTo(ItemStack) de una ya existente ItemStack, podemos ver si las dos ItemStacks son “iguales”. En decir, comparten el mismo tamaño de pila, ItemType y datos. Un ejemplo es mostrado a continuación:

public boolean isEqual(ItemStack stack1, ItemStack stack2) {
    return stack1.equalTo(stack2);
}