Creando un ItemStack

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!

Si quieres crear tus propios artículos, necesita pasar por varios pasos. Veamos un ejemplo básico y creemos una espada de diamante encantada.

Para crear un ItemStack, primero necesitamos tomar el constructor del ItemStack. Esto es hecho con el método ItemStack#builder(). En el constructor, podemos especificar cosas como el ItemType o la cantidad de artículos. En nuestro ejemplo, estaremos creando una espada de diamante que contiene encantamientos, un nombre personalizado, y es irrompible. Si quieres una espada simple sin ningún otro dato, entonces esto es todo lo que necesitas hacer:

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

public ItemStack generateSword() {
    ItemStack superMegaAwesomeSword = ItemStack.builder()
        .itemType(ItemTypes.DIAMOND_SWORD).build();
    return superMegaAwesomeSword;
}

La creación del articulo básico esta hecha. Ahora esta es una espada de diamante normal que creamos, pero ¿que si queremos crear algo mas interesante? ¿Que tal si encantamos y le damos nombre a nuestra espada? Podemos usar EnchantmentData para darle algunos encantamientos a nuestra espada. El siguiente ejemplo le dará a nuestra espada cada encantamiento en el juego, a nivel 1000. Asegúrate de incluir todo esto antes de return superMegaAwesomeSword;.

import java.util.List;
import java.util.stream.Collectors;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.manipulator.mutable.item.EnchantmentData;
import org.spongepowered.api.data.meta.ItemEnchantment
import org.spongepowered.api.item.Enchantment;

EnchantmentData enchantmentData = superMegaAwesomeSword
    .getOrCreate(EnchantmentData.class).get();
final List<EnchantmentType> enchantments = Sponge.getRegistry()
    .getAllOf(EnchantmentType.class).stream().collect(Collectors.toList());

for (EnchantmentType enchantment : enchantments) {
    enchantmentData.set(enchantmentData.enchantments()
        .add(Enchantment.of(enchantment, 1000)));
}
superMegaAwesomeSword.offer(enchantmentData);

Ahora digamos que queremos darle un nombre genial a nuestra espada super poderosa. Aquí, directamente podemos ofrecerle una clave al ItemStack. Usando esta clave, podemos cambiar el nombre del ItemStack a «SUPER MEGA ASOMBROSA Espada de Diamante»

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.item.ItemTypes;

superMegaAwesomeSword.offer(Keys.DISPLAY_NAME, TextComponent.ofChildren(
    Component.text("SUPER ", NamedTextColor.BLUE),
    Component.text("MEGA ", NamedTextColor.GOLD),
    Component.text("AWESOME ", NamedTextColor.DARK_AQUA),
    ItemTypes.DIAMOND_SWORD.asComponent().color(NamedTextColor.AQUA));

Finalmente, para hacer la espada irrompible, podemos usar las claves de nuevo:

superMegaAwesomeSword.offer(Keys.UNBREAKABLE, true);

Eso es todo. Ahora tienes una espada completamente encantada, irrompible, y hermosamente nombrada la cual le puedes dar a los jugadores.

Generando el Articulo

Sure, we can simply put the sword into a player’s inventory, but what if we wanted to throw it out into the open world and spawn the item? This is where entity spawning comes into play. Since the in-game graphical representation of an ItemStack is Item, we can spawn it in similarly to a normal Entity. The EntityType will simply be EntityTypes#ITEM and we will need to specify that the Entity will represent our ItemStack. This can be done using the Keys#REPRESENTED_ITEM key. An example is shown below:

import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.Extent;

import java.util.Optional;

public void spawnItem(ItemStack superMegaAwesomeSword, Location<World> spawnLocation) {
    Extent extent = spawnLocation.getExtent();
    Entity item = extent.createEntity(EntityTypes.ITEM, spawnLocation.getPosition());
    item.offer(Keys.REPRESENTED_ITEM, superMegaAwesomeSword.createSnapshot());

    try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLACEMENT);
        extent.spawnEntity(item);
    }
}

Creando un ItemStack Desde un Bloque

Un ItemStack para un bloque puede ser creado usando el método ItemStack.Builder#itemType(ItemType) de forma similar a los artículos normales, pero ¿que si queremos crear un ItemStack desde un BlockState? Para crear un ItemStack desde un BlockState, necesitarias usar el método ItemStack.Builder#fromBlockState(BlockState) en el constructor ItemStack. En ejemplo de esto es mostrado a continuación:

import org.spongepowered.api.block.BlockState;

public ItemStack createStack(BlockState state) {
    return ItemStack.builder().fromBlockState(state).build();
}