org.spongepowered.api.item.inventory.ItemStack Java Examples

The following examples show how to use org.spongepowered.api.item.inventory.ItemStack. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlacklistListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onPickupItem(ChangeInventoryEvent.Pickup event, @Root Player player)
{
	if (!player.hasPermission("essentialcmds.blacklist.bypass"))
	{
		for (SlotTransaction transaction : event.getTransactions())
		{
			if (Utils.getBlacklistItems().contains(transaction.getFinal().createStack().getItem().getId()))
			{
				if (Utils.areBlacklistMsgsEnabled())
					player.sendMessage(Text.of(TextColors.RED, "The item ", TextColors.GRAY, transaction.getFinal().createStack().getItem().getId(), TextColors.RED, " has been confiscated as it is blacklisted."));

				transaction.setCustom(Sponge.getRegistry().createBuilder(ItemStack.Builder.class).itemType(ItemTypes.DIRT).quantity(1).build());
			}
		}
	}
}
 
Example #2
Source File: CachedPreview.java    From Web-API with MIT License 6 votes vote down vote up
public CachedPreview(Preview value) {
    super(value);

    this.type = value.getType();

    if (value instanceof FirstGuiPreview) {
        data.put("displayName", ((FirstGuiPreview) value).getDisplayName().orElse(null));
        data.put("scrollDelay", ((FirstGuiPreview) value).getScrollDelay());
        data.put("decorativeItems", ((FirstGuiPreview) value).getDecorativeItems().stream()
                .map(ItemStack::copy).collect(Collectors.toList()));
        data.put("decorativeItemsChangeDelay",
                ((FirstGuiPreview) value).getDecorativeItemsChangeMode()
                        .map(DecorativeItemsChangeMode::getChangeDelay).orElse(null));
        data.put("decorativeItemsIgnoredIndices",
                ((FirstGuiPreview) value).getDecorativeItemsChangeMode()
                        .map(DecorativeItemsChangeMode::getIgnoredIndices).orElse(null));
    } else if (value instanceof SecondGuiPreview) {
        data.put("displayName", ((SecondGuiPreview) value).getDisplayName().orElse(null));
    }
}
 
Example #3
Source File: FoodCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkPermission(sender, FoodPermissions.UC_FOOD_FOOD_BASE);
    if (!args.hasAny("player")) {
        checkIfPlayer(sender);
        Player p = (Player) sender;
        p.offer(Keys.FOOD_LEVEL, p.get(FoodData.class).get().foodLevel().getMaxValue());
        p.offer(Keys.SATURATION, ItemStack.builder().itemType(ItemTypes.COOKED_BEEF).build().getProperty(SaturationProperty.class).get().getValue());
        Messages.send(p, "food.command.food.success.self");
        return CommandResult.success();
    } else {
        checkPermission(sender, FoodPermissions.UC_FOOD_FOOD_OTHERS);
        Player t = args.<Player>getOne("player").get();
        t.offer(Keys.FOOD_LEVEL, t.get(FoodData.class).get().foodLevel().getMaxValue());
        t.offer(Keys.SATURATION, ItemStack.builder().itemType(ItemTypes.COOKED_BEEF).build().getProperty(SaturationProperty.class).get().getValue());
        Messages.send(sender, "food.command.food.success.others.self", "%player%", t);
        Messages.send(t, "food.command.food.success.others.others", "%player%", sender);
        return CommandResult.success();
    }
}
 
Example #4
Source File: VersionHelper56.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getInvValue(Iterable<Inventory> inv) {
    long value = 0;
    for (Inventory item : inv) {
        if (!item.peek().isPresent()) {
            continue;
        }
        ItemStack stack = item.peek().get();
        value += ((RedProtect.get().config.ecoRoot().items.values.get(stack.getItem().getName()) * stack.getQuantity()));
        if (stack.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
            for (ItemEnchantment enchant : stack.get(Keys.ITEM_ENCHANTMENTS).get()) {
                value += ((RedProtect.get().config.ecoRoot().enchantments.values.get(enchant.getEnchantment().getName()) * enchant.getLevel()));
            }
        }
    }
    return value;
}
 
Example #5
Source File: BlacklistListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onChangeEquipment(ChangeInventoryEvent.Equipment event, @Root Player player)
{
	if (!player.hasPermission("essentialcmds.blacklist.bypass"))
	{
		for (SlotTransaction transaction : event.getTransactions())
		{
			if (Utils.getBlacklistItems().contains(transaction.getFinal().createStack().getItem().getId()))
			{
				if (Utils.areBlacklistMsgsEnabled())
					player.sendMessage(Text.of(TextColors.RED, "The item ", TextColors.GRAY, transaction.getFinal().createStack().getItem().getId(), TextColors.RED, " has been confiscated as it is blacklisted."));

				transaction.setCustom(Sponge.getRegistry().createBuilder(ItemStack.Builder.class).itemType(ItemTypes.DIRT).quantity(1).build());
			}
		}
	}
}
 
Example #6
Source File: ItemdurabilityCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMDURABILITY_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);
    int durability = args.<Integer>getOne("durability").get();

    if (!stack.supports(DurabilityData.class)) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "item.command.itemdurability.notsupported"));
    }

    if (durability < stack.get(DurabilityData.class).get().durability().getMinValue() || durability > stack.get(DurabilityData.class).get().durability().getMaxValue()) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "item.numberinvalid", "%number%", durability));
    }

    stack.offer(Keys.ITEM_DURABILITY, durability);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Messages.send(sender, "item.command.itemdurability.success", "%arg%", durability);
    return CommandResult.success();
}
 
Example #7
Source File: ItemquantityCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMDURABILITY_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);
    int quantity = args.<Integer>getOne("quantity").get();

    if (quantity > stack.getMaxStackQuantity()) {
        throw new ErrorMessageException(Messages.getFormatted(sender, "item.numberinvalid", "%number%", quantity));
    }

    stack.setQuantity(quantity);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Messages.send(sender, "item.command.itemquantity.success", "%arg%", quantity);
    return CommandResult.success();
}
 
Example #8
Source File: ItemListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener
public void onChange(ChangeInventoryEvent event, @First Player p) {
    ModuleConfig config = Modules.BLACKLIST.get().getConfig().get();
    CommentedConfigurationNode hnode = config.get();
    try {
        for (Inventory s : event.getTargetInventory().slots()) {
            ItemStack item = s.peek();
            CommentedConfigurationNode node = hnode.getNode("items", item.getType().getKey());
            if (!node.isVirtual()) {
                if (node.getNode("deny-possession").getBoolean()) {
                    s.poll();
                }
            }
        }
    } catch (Exception ignore) {
    }
}
 
Example #9
Source File: VersionHelper8.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getInvValue(Iterable<Inventory> inv) {
    long value = 0;
    for (Inventory item : inv) {
        if (item.peek().isEmpty()) {
            continue;
        }
        ItemStack stack = item.peek();
        value += ((RedProtect.get().config.ecoRoot().items.values.get(stack.getType().getName()) * stack.getQuantity()));
        if (stack.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
            for (Enchantment enchant : stack.get(Keys.ITEM_ENCHANTMENTS).get()) {
                value += ((RedProtect.get().config.ecoRoot().enchantments.values.get(enchant.getType().getName()) * enchant.getLevel()));
            }
        }
    }
    return value;
}
 
Example #10
Source File: ItemInfoExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent())
		{
			ItemStack itemInHand = player.getItemInHand(HandTypes.MAIN_HAND).get();
			player.sendMessage(Text.of(TextColors.GOLD, "The name of the item in your hand is: ", TextColors.GRAY, itemInHand.getTranslation().get()));
			player.sendMessage(Text.of(TextColors.GOLD, "The ID of the item in your hand is: ", TextColors.GRAY, itemInHand.getItem().getId()));
			player.sendMessage(Text.of(TextColors.GOLD, "The meta of the item in your hand is: ", TextColors.GRAY, itemInHand.toContainer().get(DataQuery.of("UnsafeDamage")).get().toString()));
		}
		else
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must hold an item."));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be an in-game player to use this command."));
	}

	return CommandResult.success();
}
 
Example #11
Source File: FactionChestImpl.java    From EagleFactions with MIT License 6 votes vote down vote up
private List<SlotItem> toSlotItems(final Inventory inventory)
{
    final List<FactionChest.SlotItem> slotItemList = new ArrayList<>();
    final Iterable<Inventory> slots = inventory.slots();
    int column = 1;
    int row = 1;
    for(Inventory slot : slots)
    {
        Optional<ItemStack> optionalItemStack = slot.peek();
        if(optionalItemStack.isPresent())
        {
            slotItemList.add(new FactionChestImpl.SlotItemImpl(column, row, optionalItemStack.get()));
        }

        column++;
        if(column > 9)
        {
            row++;
            column = 1;
        }

        if(row > 3)
            break;
    }
    return slotItemList;
}
 
Example #12
Source File: HuskyUI.java    From HuskyUI-Plugin with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Handle item drops
 * @param event dispense event
 */
@Listener
public void onItemDrop(DropItemEvent.Dispense event){
    for(Entity e :event.getEntities()){
        if(e instanceof Item){
            ItemStack affectedStack = ((Item) e).getItemData().item().get().createStack();
            Optional<Integer> potentialID = registry.getElementIDFromItemStack(affectedStack);
            if(potentialID.isPresent()){
                if(registry.elementExists(potentialID.get())){
                    event.setCancelled(true); //NOTHING should drop a registered item. >:(
                    //TODO: handle https://github.com/SpongePowered/SpongeCommon/issues/1678 properly w/ workaround
                }
            }
        }
    }
}
 
Example #13
Source File: ItemhidetagsCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMHIDETAGS_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);

    Key<Value<Boolean>> key = args.<Key<Value<Boolean>>>getOne("tag").get();
    boolean value = args.<Boolean>getOne("enabled").get();

    stack.offer(key, value);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Messages.send(sender, "item.command.itemhidetags.success", "%tag%", key.getName(), "%status%", Messages.getFormatted(value ? "item.command.itemhidetags.hidden" : "item.command.itemhidetags.shown"));
    return CommandResult.success();
}
 
Example #14
Source File: BlacklistListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onChangeHeldItem(ChangeInventoryEvent.Held event, @Root Player player)
{
	if (!player.hasPermission("essentialcmds.blacklist.bypass"))
	{
		for (SlotTransaction transaction : event.getTransactions())
		{
			if (Utils.getBlacklistItems().contains(transaction.getFinal().createStack().getItem().getId()))
			{
				if (Utils.areBlacklistMsgsEnabled())
					player.sendMessage(Text.of(TextColors.RED, "The item ", TextColors.GRAY, transaction.getFinal().createStack().getItem().getId(), TextColors.RED, " has been confiscated as it is blacklisted."));

				transaction.setCustom(Sponge.getRegistry().createBuilder(ItemStack.Builder.class).itemType(ItemTypes.DIRT).quantity(1).build());
			}
		}
	}
}
 
Example #15
Source File: ItemcanbreakCommand.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException {
    checkIfPlayer(sender);
    checkPermission(sender, ItemPermissions.UC_ITEM_ITEMCANBREAK_BASE);
    Player p = (Player) sender;

    if (p.getItemInHand(HandTypes.MAIN_HAND).getType().equals(ItemTypes.NONE)) {
        throw new ErrorMessageException(Messages.getFormatted(p, "item.noiteminhand"));
    }
    ItemStack stack = p.getItemInHand(HandTypes.MAIN_HAND);
    Set<BlockType> types = new HashSet<>(args.<BlockType>getAll("blocktypes"));

    stack.offer(Keys.BREAKABLE_BLOCK_TYPES, types);
    p.setItemInHand(HandTypes.MAIN_HAND, stack);
    Text items = Text.joinWith(Text.of(", "), types.stream().map(type -> Text.of(type.getName())).collect(Collectors.toList()));
    Messages.send(sender, "item.command.itemcanbreak.success", "%arg%", items);
    return CommandResult.success();
}
 
Example #16
Source File: InventorySerializer.java    From EagleFactions with MIT License 6 votes vote down vote up
public static List<DataView> serializeInventory(Inventory inventory) {
    DataContainer container;
    List<DataView> slots = new LinkedList<>();

    int i = 0;
    Optional<ItemStack> stack;

    for (Inventory inv : inventory.slots()) {
        stack = inv.peek();

        if (stack.isPresent()) {
            container = DataContainer.createNew(SafetyMode.ALL_DATA_CLONED);

            container.set(SLOT, i);
            container.set(STACK, serializeItemStack(stack.get()));

            slots.add(container);
        }

        i++;
    }

    return slots;
}
 
Example #17
Source File: InteractPermListener.java    From Nations with MIT License 6 votes vote down vote up
@Listener(order=Order.FIRST, beforeModifications = true)
public void onInteract(InteractBlockEvent event, @First Player player)
{
	if (!ConfigHandler.getNode("worlds").getNode(player.getWorld().getName()).getNode("enabled").getBoolean())
	{
		return;
	}
	if (player.hasPermission("nations.admin.bypass.perm.interact"))
	{
		return;
	}
	Optional<ItemStack> optItem = player.getItemInHand(HandTypes.MAIN_HAND);
	if (optItem.isPresent() && (ConfigHandler.isWhitelisted("use", optItem.get().getItem().getId()) || optItem.get().getItem().equals(ItemTypes.GOLDEN_AXE) && ConfigHandler.getNode("others", "enableGoldenAxe").getBoolean(true)))
		return;
	event.getTargetBlock().getLocation().ifPresent(loc -> {
		if (!DataHandler.getPerm("interact", player.getUniqueId(), loc))
		{
			event.setCancelled(true);
			if (loc.getBlockType() != BlockTypes.STANDING_SIGN && loc.getBlockType() != BlockTypes.WALL_SIGN)
				player.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_INTERACT));
		}
	});
}
 
Example #18
Source File: UIRenderer.java    From SubServers-2 with Apache License 2.0 6 votes vote down vote up
/**
 * Parse an ItemStack from a String
 *
 * @param str String to parse
 * @param def Default to return if unable to parse
 * @return ItemStack
 */
public ItemStack parseItem(String str, ItemStack def) {
    final Container<String> item = new Container<String>(str);
    // minecraft:name
    if (item.get().toLowerCase().startsWith("minecraft:")) {
        item.set(item.get().substring(10));
    } else

        // bukkit:name (ignored on sponge)
        if (item.get().toLowerCase().startsWith("bukkit:")) {
            item.set(item.get().substring(7));
        }

    // material name
    if (!Util.isException(() -> ItemTypes.class.getDeclaredField(item.get().toUpperCase()).get(null))) {
        return ItemStack.builder().itemType((ItemType) Util.getDespiteException(() -> ItemTypes.class.getDeclaredField(item.get().toUpperCase()).get(null), null)).quantity(1).build();
    }

    return def;
}
 
Example #19
Source File: Utils.java    From EssentialCmds with MIT License 6 votes vote down vote up
public static void updatePlayerInventory(Player player, UUID worldUuid)
{
	if (!Utils.areSeparateWorldInventoriesEnabled())
		return;

	PlayerInventory playerInventory = Utils.getPlayerInventory(player.getUniqueId(), worldUuid);
	player.getInventory().clear();

	if (playerInventory != null)
	{
		final Iterator<ItemStack> slots = playerInventory.getSlots().iterator();
		player.getInventory().slots().forEach(c -> {
			if (slots.hasNext())
				c.set(slots.next());
		});
	}
}
 
Example #20
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerInteractEntity(InteractEntityEvent.Primary event, @First Player player) {
    if (!GPFlags.INTERACT_ENTITY_PRIMARY || !GriefPreventionPlugin.instance.claimsEnabledForWorld(player.getWorld().getProperties())) {
        return;
    }

    final Entity targetEntity = event.getTargetEntity();
    final HandType handType = event.getHandType();
    final ItemStack itemInHand = player.getItemInHand(handType).orElse(ItemStack.empty());
    final Object source = !itemInHand.isEmpty() ? itemInHand : player;
    if (GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.INTERACT_ENTITY_PRIMARY.toString(), targetEntity, player.getWorld().getProperties())) {
        return;
    }

    GPTimings.PLAYER_INTERACT_ENTITY_PRIMARY_EVENT.startTimingIfSync();
    Location<World> location = targetEntity.getLocation();
    GPClaim claim = this.dataStore.getClaimAt(location);
    if (event.isCancelled() && claim.getData().getPvpOverride() == Tristate.TRUE && targetEntity instanceof Player) {
        event.setCancelled(false);
    }

    Tristate result = GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.INTERACT_ENTITY_PRIMARY, source, targetEntity, player, TrustType.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        final Text message = GriefPreventionPlugin.instance.messageData.claimProtectedEntity
                .apply(ImmutableMap.of(
                "owner", claim.getOwnerName())).build();
        GriefPreventionPlugin.sendMessage(player, message);
        event.setCancelled(true);
        this.sendInteractEntityDenyMessage(itemInHand, targetEntity, claim, player, handType);
        GPTimings.PLAYER_INTERACT_ENTITY_PRIMARY_EVENT.stopTimingIfSync();
        return;
    }
}
 
Example #21
Source File: PlayerUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static boolean hasItemInOneHand(Player player, ItemType itemType) {
    ItemStack mainHand = player.getItemInHand(HandTypes.MAIN_HAND).orElse(null);
    ItemStack offHand = player.getItemInHand(HandTypes.OFF_HAND).orElse(null);
    if ((mainHand != null && mainHand.getType().equals(itemType)) || (offHand != null && offHand.getType().equals(itemType))) {
        return true;
    }

    return false;
}
 
Example #22
Source File: GDPermissionManager.java    From GriefDefender with MIT License 5 votes vote down vote up
private void addPlayerContexts(Player player, Set<Context> contexts) {
    if(!PermissionUtil.getInstance().containsKey(contexts, "used_item") && NMSUtil.getInstance().getActiveItem(player, this.currentEvent) != null) {
        final ItemStack stack = NMSUtil.getInstance().getActiveItem(player, this.currentEvent);
        if (!stack.isEmpty()) {
            contexts.add(new Context("used_item", getPermissionIdentifier(stack)));
            final Text displayName = stack.get(Keys.DISPLAY_NAME).orElse(null);
            if (displayName != null) {
                String itemName = displayName.toPlain().replaceAll("[^A-Za-z0-9]", "").toLowerCase();
                if (itemName != null && !itemName.isEmpty()) {
                    if (!itemName.contains(":")) {
                        itemName = "minecraft:" + itemName;
                    }
                    contexts.add(new Context("item_name", itemName));
                }
            }
        }
    }
    final ItemStack helmet = player.getEquipped(EquipmentTypes.HEADWEAR).orElse(null);
    final ItemStack chestplate = player.getEquipped(EquipmentTypes.CHESTPLATE).orElse(null);
    final ItemStack leggings = player.getEquipped(EquipmentTypes.LEGGINGS).orElse(null);
    final ItemStack boots = player.getEquipped(EquipmentTypes.BOOTS).orElse(null);
    if (helmet != null && !helmet.isEmpty()) {
        contexts.add(new Context("helmet", getPermissionIdentifier(helmet)));
    }
    if (chestplate != null && !chestplate.isEmpty()) {
        contexts.add(new Context("chestplate", getPermissionIdentifier(chestplate)));
    }
    if (leggings != null && !leggings.isEmpty()) {
        contexts.add(new Context("leggings", getPermissionIdentifier(leggings)));
    }
    if (boots != null && !boots.isEmpty()) {
        contexts.add(new Context("boots", getPermissionIdentifier(boots)));
    }
}
 
Example #23
Source File: GoldenAxeListener.java    From Nations with MIT License 5 votes vote down vote up
@Listener
public void onPlayerRightClick(InteractBlockEvent.Secondary.MainHand event, @First Player player)
{
	if (ConfigHandler.getNode("others", "enableGoldenAxe").getBoolean(true) == false)
	{
		return ;
	}
	Optional<ItemStack> optItem = player.getItemInHand(HandTypes.MAIN_HAND);
	if (!optItem.isPresent())
	{
		return;
	}
	if (optItem.get().getItem().equals(ItemTypes.GOLDEN_AXE))
	{
		event.setCancelled(true);
		Optional<Location<World>> optLoc = event.getTargetBlock().getLocation();
		if (!optLoc.isPresent())
		{
			return;
		}
		Point secondPoint = new Point(optLoc.get().getExtent(), optLoc.get().getBlockX(), optLoc.get().getBlockZ());
		DataHandler.setSecondPoint(player.getUniqueId(), secondPoint);
		Point firstPoint = DataHandler.getFirstPoint(player.getUniqueId());
		if (firstPoint != null && !firstPoint.getWorld().equals(secondPoint.getWorld()))
		{
			firstPoint = null;
			DataHandler.setFirstPoint(player.getUniqueId(), firstPoint);
		}
		
		String coord = secondPoint.getX() + " " + secondPoint.getY() + ")" + ((firstPoint != null) ? " (" + new Rect(firstPoint, secondPoint).size() + ")" : "");
		player.sendMessage(Text.of(TextColors.AQUA, LanguageHandler.AXE_SECOND.replaceAll("\\{COORD\\}", coord)));
	}
}
 
Example #24
Source File: CachedSlot.java    From Web-API with MIT License 5 votes vote down vote up
public CachedSlot(Slot value) {
    super(value);

    this.stack = value.peek().map(ItemStack::copy).orElse(null);

    // Add properties
    Map<Class<? extends Property<?, ?>>, String> props = WebAPI.getSerializeService().getSupportedProperties();
    for (Map.Entry<Class<? extends Property<?, ?>>, String> entry : props.entrySet()) {
        if (InventoryProperty.class.isAssignableFrom(entry.getKey())) {
            Class<? extends InventoryProperty<?, ?>> propClass =
                    (Class<? extends InventoryProperty<?, ?>>) entry.getKey();
            value.getInventoryProperty(propClass).ifPresent(val -> data.put(entry.getValue(), val.getValue()));
        }
    }
}
 
Example #25
Source File: UCVHelper8.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ItemStack getItemInHand(Player sender) {
    if (!sender.getItemInHand(HandTypes.MAIN_HAND).isEmpty()) {
        return sender.getItemInHand(HandTypes.MAIN_HAND);
    } else if (!sender.getItemInHand(HandTypes.OFF_HAND).isEmpty()) {
        return sender.getItemInHand(HandTypes.OFF_HAND);
    }
    return ItemStack.empty();
}
 
Example #26
Source File: SpongePlayer.java    From PlotMe-Core with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IItemStack getItemInHand() {
    Optional<ItemStack> itemInHand = player.getItemInHand();
    if (itemInHand.isPresent()) {
        return new SpongeItemStack(itemInHand.get());
    } else {
        return null;
    }
}
 
Example #27
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public boolean isGuiItem(ItemStack pitem) {
    if (pitem.get(Keys.ITEM_LORE).isPresent() &&
            pitem.get(Keys.ITEM_LORE).get().size() >= 2 &&
            RedProtect.get().config.getDefFlags().contains(pitem.get(Keys.ITEM_LORE).get().get(1).toPlain().replace("ยง0", ""))) {
        return true;
    }
    if (pitem.get(Keys.ITEM_LORE).isPresent()) {
        List<Text> lore = pitem.get(Keys.ITEM_LORE).get();
        return RedProtect.get().config.getGuiSeparator().get(Keys.ITEM_LORE).get().equals(lore);
    }
    return false;
}
 
Example #28
Source File: LoreBase.java    From EssentialCmds with MIT License 5 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	int number = ctx.<Integer> getOne("number").get();

	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (player.getItemInHand(HandTypes.MAIN_HAND).isPresent())
		{
			ItemStack stack = player.getItemInHand(HandTypes.MAIN_HAND).get();
			LoreData loreData = stack.getOrCreate(LoreData.class).get();
			List<Text> newLore = loreData.lore().get();
			newLore.remove(number - 1);
			DataTransactionResult dataTransactionResult = stack.offer(Keys.ITEM_LORE, newLore);

			if (dataTransactionResult.isSuccessful())
			{
				player.setItemInHand(HandTypes.MAIN_HAND, stack);
				src.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Removed lore from item."));
			}
			else
			{
				src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Could not remove lore from item."));
			}
		}
		else
		{
			src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be holding an item!"));
		}
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You must be a player to name items."));
	}
	return CommandResult.success();
}
 
Example #29
Source File: ItemStackDeserializer.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public ItemStack deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonNode root = p.readValueAsTree();
    if (root.path("type").isMissingNode())
        throw new IOException("Missing item type");

    String id = root.path("type").isTextual()
            ? root.path("type").asText()
            : root.path("type").path("id").asText();
    Optional<ItemType> optType = Sponge.getRegistry().getType(ItemType.class, id);
    if (!optType.isPresent())
        throw new IOException("Invalid item type " + id);

    Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt();

    ItemType type = optType.get();

    ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount);
    ItemStack item = builder.build();

    if (!root.path("data").isMissingNode()) {
        Iterator<Map.Entry<String, JsonNode>> it = root.path("data").fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> entry = it.next();
            Class<? extends DataManipulator> c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey());
            if (c == null) continue;
            Optional<? extends DataManipulator> optData = item.getOrCreate(c);
            if (!optData.isPresent())
                throw new IOException("Invalid item data: " + entry.getKey());
            DataManipulator data = optData.get();
            item.offer(data);
        }
    }

    return item;
}
 
Example #30
Source File: CachedOpenManager.java    From Web-API with MIT License 5 votes vote down vote up
public CachedOpenManager(OpenManager value) {
    super(value);

    this.type = value.getType();
    this.openSound = value.getOpenSound().map(CachedCatalogType::new).orElse(null);

    if (value instanceof FirstOpenManager) {
        data.put("displayName", ((FirstOpenManager) value).getDisplayName().orElse(null));
        data.put("closeDelay", ((FirstOpenManager) value).getCloseDelay());
        data.put("decorativeItems", ((FirstOpenManager) value).getDecorativeItems().stream()
                .map(ItemStack::copy).collect(Collectors.toList()));
        data.put("decorativeItemsChangeDelay",
                ((FirstOpenManager) value).getDecorativeItemsChangeMode()
                        .map(DecorativeItemsChangeMode::getChangeDelay).orElse(null));
        data.put("decorativeItemsIgnoredIndices",
                ((FirstOpenManager) value).getDecorativeItemsChangeMode()
                        .map(DecorativeItemsChangeMode::getIgnoredIndices).orElse(null));
        data.put("scrollDelays", ((FirstOpenManager) value).getScrollDelays());
        data.put("scrollSound",
                ((FirstOpenManager) value).getScrollSound().map(CachedCatalogType::new).orElse(null));
        data.put("winSound",
                ((FirstOpenManager) value).getWinSound().map(CachedCatalogType::new).orElse(null));
    } else if (value instanceof SecondOpenManager) {
        data.put("displayName", ((SecondOpenManager) value).getDisplayName().orElse(null));
        data.put("closeDelay", ((SecondOpenManager) value).getCloseDelay());
        data.put("clickSound",
                ((SecondOpenManager) value).getClickSound().map(CachedCatalogType::new).orElse(null));
        data.put("hiddenItem", ((SecondOpenManager) value).getHiddenItem().copy());
        data.put("rows", ((SecondOpenManager) value).getRows());
        data.put("showOtherDropsDelay", ((SecondOpenManager) value).getShowOtherDropsDelay());
    } else if (value instanceof Animation1OpenManager) {
        data.put("closeDelay", ((Animation1OpenManager) value).getCloseDelay());
        data.put("crate", new CachedCatalogType<>(((Animation1OpenManager) value).getCrateBlockType()));
        data.put("fence", new CachedCatalogType<>(((Animation1OpenManager) value).getFenceBlockType()));
        data.put("floor", new CachedCatalogType<>(((Animation1OpenManager) value).getFloorBlockType()));
    }
}