Java Code Examples for org.bukkit.inventory.ItemStack

The following examples show how to use org.bukkit.inventory.ItemStack. These examples are extracted from open source projects. 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 Project: Skript   Author: SkriptLang   File: ExprXOf.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Object[] get(final Event e, final Object[] source) {
	return get(source, new Converter<Object, Object>() {
		@Override
		@Nullable
		public Object convert(final Object o) {
			final Number a = amount.getSingle(e);
			if (a == null)
				return null;
			if (o instanceof ItemStack) {
				final ItemStack is = ((ItemStack) o).clone();
				is.setAmount(a.intValue());
				return is;
			} else if (o instanceof ItemType) {
				ItemType type = ((ItemType) o).clone();
				type.setAmount(a.intValue());
				return type;
			} else {
				final EntityType t = ((EntityType) o).clone();
				t.amount = a.intValue();
				return t;
			}
		}
	});
}
 
Example #2
Source Project: Slimefun4   Author: TheBusyBiscuit   File: MultiBlockMachine.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected Inventory findOutputChest(Block b, ItemStack output) {
    for (BlockFace face : outputFaces) {
        Block potentialOutput = b.getRelative(face);

        if (potentialOutput.getType() == Material.CHEST) {
            String id = BlockStorage.checkID(potentialOutput);

            if (id != null && id.equals("OUTPUT_CHEST")) {
                // Found the output chest! Now, let's check if we can fit the product in it.
                Inventory inv = ((Chest) potentialOutput.getState()).getInventory();

                if (InvUtils.fits(inv, output)) {
                    return inv;
                }
            }
        }
    }

    return null;
}
 
Example #3
Source Project: BedWars   Author: ScreamingSandals   File: LuckyBlockAddonListener.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onLuckyBlockRegistered(BedwarsApplyPropertyToBoughtItem event) {
    if (event.getPropertyName().equalsIgnoreCase("luckyblock")) {
        ItemStack stack = event.getStack();

        LuckyBlock lucky = new LuckyBlock(event.getGame(), event.getPlayer(),
                event.getGame().getTeamOfPlayer(event.getPlayer()),
                (List<Map<String, Object>>) event.getProperty("data"));

        int id = System.identityHashCode(lucky);

        String luckyBlockString = LUCKY_BLOCK_PREFIX + id;

        APIUtils.hashIntoInvisibleString(stack, luckyBlockString);
    }
}
 
Example #4
Source Project: Slimefun4   Author: TheBusyBiscuit   File: SlimefunItemSetup.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void registerArmorSet(Category category, ItemStack baseComponent, ItemStack[] items, String idSyntax, PotionEffect[][] effects, SlimefunAddon addon) {
    String[] components = new String[] { "_HELMET", "_CHESTPLATE", "_LEGGINGS", "_BOOTS" };
    List<ItemStack[]> recipes = new ArrayList<>();

    recipes.add(new ItemStack[] { baseComponent, baseComponent, baseComponent, baseComponent, null, baseComponent, null, null, null });
    recipes.add(new ItemStack[] { baseComponent, null, baseComponent, baseComponent, baseComponent, baseComponent, baseComponent, baseComponent, baseComponent });
    recipes.add(new ItemStack[] { baseComponent, baseComponent, baseComponent, baseComponent, null, baseComponent, baseComponent, null, baseComponent });
    recipes.add(new ItemStack[] { null, null, null, baseComponent, null, baseComponent, baseComponent, null, baseComponent });

    for (int i = 0; i < 4; i++) {
        if (i < effects.length && effects[i].length > 0) {
            new SlimefunArmorPiece(category, new SlimefunItemStack(idSyntax + components[i], items[i]), RecipeType.ARMOR_FORGE, recipes.get(i), effects[i]).register(addon);
        }
        else {
            new SlimefunItem(category, new SlimefunItemStack(idSyntax + components[i], items[i]), RecipeType.ARMOR_FORGE, recipes.get(i)).register(addon);
        }
    }
}
 
Example #5
Source Project: MineTinker   Author: Flo56958   File: TridentListener.java    License: GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onTridentLaunch(ProjectileLaunchEvent event) {
	if (!(event.getEntity().getShooter() instanceof Player)) {
		return;
	}

	if (!(event.getEntity() instanceof Trident)) {
		return;
	}

	Player player = (Player) event.getEntity().getShooter();
	ItemStack trident = player.getInventory().getItemInMainHand().clone();

	if (!ModManager.instance().isToolViable(trident)) {
		return;
	}

	ModManager.instance().addExp(player, trident, -20000);
	//trident is a item clone and only for triggering modifier effects
	//this makes sure that the item duplicate does not get any level ups
	TridentToItemStack.put((Trident) event.getEntity(), trident);
}
 
Example #6
Source Project: Holograms   Author: sainttx   File: HologramEntityControllerImpl.java    License: MIT License 6 votes vote down vote up
@Override
public ItemHolder spawnItemHolder(HologramLine line, Location location, ItemStack itemstack) {
    WorldServer nmsWorld = ((CraftWorld) location.getWorld()).getHandle();
    EntityItemHolder item = new EntityItemHolder(nmsWorld, line);
    item.setPosition(location.getX(), location.getY() + line.getHeight(), location.getZ());
    item.setItem(itemstack);
    if (!addEntityToWorld(nmsWorld, item)) {
        plugin.getLogger().log(Level.WARNING, "Failed to spawn item entity in world " + location.getWorld().getName()
                + " at x:" + location.getX() + " y:" + location.getY() + " z:" + location.getZ());
    }
    EntityNameable armorStand = spawnNameable(line, location, false);
    item.setMount(armorStand);
    item.setLockTick(true);
    armorStand.setLockTick(true);
    return item;
}
 
Example #7
Source Project: ProjectAres   Author: OvercastNetwork   File: WoolMatchModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Repeatable(interval = @Time(seconds = 30), scope = MatchScope.RUNNING)
public void refillOneWoolPerContainer() {
    if(!Config.Wool.autoRefillWoolChests()) return;

    for(Entry<Inventory, Map<Integer, ItemStack>> chest : this.woolChests.entrySet()) {
        Inventory inv = chest.getKey();
        for(Entry<Integer, ItemStack> slotEntry : chest.getValue().entrySet()) {
            int slot = slotEntry.getKey();
            ItemStack wool = slotEntry.getValue();
            ItemStack stack = inv.getItem(slotEntry.getKey());

            if(stack == null) {
                stack = wool.clone();
                stack.setAmount(1);
                inv.setItem(slot, stack);
                break;
            } else if(stack.isSimilar(wool) && stack.getAmount() < wool.getAmount()) {
                stack.setAmount(stack.getAmount() + 1);
                inv.setItem(slot, stack);
                break;
            }
        }
    }
}
 
Example #8
Source Project: TabooLib   Author: TabooLib   File: Items.java    License: MIT License 6 votes vote down vote up
public static ItemStack fromJson(String item) {
    JsonElement json = new JsonParser().parse(item);
    if (json instanceof JsonObject) {
        ItemBuilder itemBuilder = new ItemBuilder(Material.STONE);
        JsonElement type = ((JsonObject) json).get("type");
        if (type != null) {
            itemBuilder.material(Items.asMaterial(type.getAsString()));
        }
        JsonElement data = ((JsonObject) json).get("data");
        if (data != null) {
            itemBuilder.damage(data.getAsInt());
        }
        JsonElement amount = ((JsonObject) json).get("amount");
        if (amount != null) {
            itemBuilder.amount(amount.getAsInt());
        }
        ItemStack itemBuild = itemBuilder.build();
        JsonElement meta = ((JsonObject) json).get("meta");
        if (meta != null) {
            return NMS.handle().saveNBT(itemBuild, NBTCompound.fromJson(meta.toString()));
        }
        return itemBuild;
    }
    return null;
}
 
Example #9
Source Project: RedProtect   Author: FabioZumbi12   File: Region.java    License: GNU General Public License v3.0 6 votes vote down vote up
public boolean denyEnterWithItens(Player p) {
    if (!flagExists("deny-enter-items")) {
        return true;
    }
    if (checkAllowedPlayer(p, "deny-enter-items")) {
        return true;
    }

    List<String> items = Arrays.asList(getFlagString("deny-enter-items").replace(" ", "").split(","));
    for (ItemStack slot : p.getInventory().getContents()) {
        if (slot == null || slot.getType().equals(Material.AIR)) {
            continue;
        }

        if (items.stream().anyMatch(k -> k.equalsIgnoreCase(slot.getType().name()))) {
            return false;
        }
    }
    return true;
}
 
Example #10
Source Project: civcraft   Author: netizen539   File: UnitMaterial.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean validateUnitUse(Player player, ItemStack stack) {
	if (stack == null) {
		return true;
	}
	
	Resident resident = CivGlobal.getResident(player);
	Town town = getOwningTown(stack);
	
	
	if (town == null) {
		return true;
	}
	
	if (town.getCiv() != resident.getCiv()) {
		return false;
	}
	
	return true;
}
 
Example #11
Source Project: ProRecipes   Author: mcgrizzz   File: RecipeChest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public String getId(ItemStack[][] i){
	String k = "";
	String[][] b = new String[i.length][i[0].length];
	for(int t = 0; t < i.length; t++){
		for(int z = 0; z <i[t].length; z++){
			if(i.length < t || i[t].length < z){
				continue;
			}
			if(i[t][z] == null){
				b[t][z] = ProRecipes.airString;
				continue;
			}
			if(i[t][z].getType().equals(Material.AIR)){
				i[t][z] = new ItemStack(Material.AIR);
			}
			b[t][z] = ItemUtils.itemToStringBlob(i[t][z]);
		}
	}
	k = Arrays.deepToString(convertToMinimizedStructure(b, ProRecipes.airString));
	return k;
}
 
Example #12
Source Project: Thermos   Author: CyberdyneCC   File: CraftShapedRecipe.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void addToCraftingManager() {
    Object[] data;
    String[] shape = this.getShape();
    Map<Character, ItemStack> ingred = this.getIngredientMap();
    int datalen = shape.length;
    datalen += ingred.size() * 2;
    int i = 0;
    data = new Object[datalen];
    for (; i < shape.length; i++) {
        data[i] = shape[i];
    }
    for (char c : ingred.keySet()) {
        ItemStack mdata = ingred.get(c);
        if (mdata == null) continue;
        data[i] = c;
        i++;
        int id = mdata.getTypeId();
        short dmg = mdata.getDurability();
        data[i] = new net.minecraft.item.ItemStack(CraftMagicNumbers.getItem(id), 1, dmg);
        i++;
    }
    net.minecraft.item.crafting.CraftingManager.getInstance().addRecipe(CraftItemStack.asNMSCopy(this.getResult()), data);
}
 
Example #13
Source Project: Skript   Author: SkriptLang   File: AliasesProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Applies given tags to an item stack.
 * @param stack Item stack.
 * @param tags Tags.
 * @return Additional flags for the item.
 */
public int applyTags(ItemStack stack, Map<String, Object> tags) {
	// Hack damage tag into item
	Object damage = tags.get("Damage");
	int flags = 0;
	if (damage instanceof Number) { // Use helper for version compatibility
		ItemUtils.setDamage(stack, ((Number) damage).shortValue());
		tags.remove("Damage");
		flags |= ItemFlags.CHANGED_DURABILITY;
	}
	
	if (tags.isEmpty()) // No real tags to apply
		return flags;
	
	// Apply random tags using JSON
	String json = gson.toJson(tags);
	assert json != null;
	BukkitUnsafe.modifyItemStack(stack, json);
	flags |= ItemFlags.CHANGED_TAGS;
	
	return flags;
}
 
Example #14
Source Project: MineTinker   Author: Flo56958   File: Soulbound.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Effect if a player drops an item
 *
 * @param event the event
 */
@EventHandler(ignoreCancelled = true)
public void effect(PlayerDropItemEvent event) {
	Item item = event.getItemDrop();
	ItemStack tool = item.getItemStack();

	if (!(modManager.isArmorViable(tool) || modManager.isToolViable(tool) || modManager.isWandViable(tool))) {
		return;
	}

	if (!modManager.hasMod(tool, this)) {
		return;
	}

	if (toolDroppable) {
		return;
	}

	ChatWriter.logModifier(event.getPlayer(), event, this, tool, "Tool not droppable");

	event.setCancelled(true);
}
 
Example #15
Source Project: uSkyBlock   Author: rlf   File: Challenge.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Challenge(String name, String displayName, String description, Type type, List<String> requiredItems,
                 List<EntityMatch> requiredEntities, List<String> requiredChallenges, double requiredLevel, Rank rank, int resetInHours,
                 ItemStack displayItem, String tool, ItemStack lockedItem, int offset, boolean takeItems,
                 int radius, Reward reward, Reward repeatReward, int repeatLimit) {
    this.name = name;
    this.displayName = displayName;
    this.type = type;
    this.requiredItems = requiredItems;
    this.requiredEntities = requiredEntities;
    this.requiredChallenges = requiredChallenges;
    this.requiredLevel = requiredLevel;
    this.rank = rank;
    this.resetInHours = resetInHours;
    this.displayItem = displayItem;
    this.tool = tool;
    this.lockedItem = lockedItem;
    this.offset = offset;
    this.takeItems = takeItems;
    this.radius = radius;
    this.reward = reward;
    this.repeatReward = repeatReward;
    this.description = description;
    this.repeatLimit = repeatLimit;
}
 
Example #16
Source Project: Skript   Author: SkriptLang   File: ItemType.java    License: GNU General Public License v3.0 6 votes vote down vote up
public boolean isContainedIn(Iterable<ItemStack> items) {
	int amount = getAmount();
	for (final ItemData d : types) {
		int found = 0;
		for (final ItemStack i : items) {
			if (d.isOfType(i)) {
				found += i == null ? 1 : i.getAmount();
				if (found >= amount) {
					if (!all)
						return true;
					break;
				}
			}
		}
		if (all && found < amount)
			return false;
	}
	return all;
}
 
Example #17
Source Project: UhcCore   Author: Mezy   File: CraftsManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static Craft getCraft(ItemStack result) {
	if(result.hasItemMeta() && result.getItemMeta().hasDisplayName()){
		String displayName = result.getItemMeta().getDisplayName();
		for(Craft craft : getCrafts()){
			if(displayName.equals(craft.getCraft().getItemMeta().getDisplayName())){
				return craft;
			}
		}
	}
	return null;
}
 
Example #18
Source Project: BedWars   Author: ScreamingSandals   File: RescuePlatformListener.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onRescuePlatformRegistered(BedwarsApplyPropertyToBoughtItem event) {
    if (event.getPropertyName().equalsIgnoreCase("rescueplatform")) {
        ItemStack stack = event.getStack();
        APIUtils.hashIntoInvisibleString(stack, applyProperty(event));
    }
}
 
Example #19
Source Project: HeavySpleef   Author: xaniox   File: FlagShovels.java    License: GNU General Public License v3.0 5 votes vote down vote up
private ItemStack createShovel() {
	ItemStack shovelStack = new ItemStack(Material.DIAMOND_SPADE);
	
	ItemMeta meta = shovelStack.getItemMeta();
	meta.setDisplayName(getI18N().getString(Messages.Player.SHOVEL));
	String lore = getI18N().getString(Messages.Player.SHOVEL_LORE);
	if (!lore.isEmpty()) {
		meta.setLore(Lists.newArrayList(lore.split("\n")));
	}
	
	shovelStack.setItemMeta(meta);
	return shovelStack;
}
 
Example #20
Source Project: Kettle   Author: KettleFoundation   File: CraftInventory.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void remove(int materialId) {
    ItemStack[] items = getStorageContents();
    for (int i = 0; i < items.length; i++) {
        if (items[i] != null && items[i].getTypeId() == materialId) {
            clear(i);
        }
    }
}
 
Example #21
Source Project: Slimefun4   Author: TheBusyBiscuit   File: TestVanillaMachinesListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
private InventoryClickEvent mockGrindStoneEvent(ItemStack item) {
    Player player = server.addPlayer();
    Inventory inv = TestUtilities.mockInventory(InventoryType.GRINDSTONE, item, null);
    InventoryView view = player.openInventory(inv);
    InventoryClickEvent event = new InventoryClickEvent(view, SlotType.CONTAINER, 2, ClickType.LEFT, InventoryAction.PICKUP_ONE);

    listener.onGrindstone(event);
    return event;
}
 
Example #22
Source Project: BedWars   Author: ScreamingSandals   File: Game.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public void addChestForFutureClear(Location loc, Inventory inventory) {
    if (!usedChests.containsKey(loc)) {
        ItemStack[] contents = inventory.getContents();
        ItemStack[] clone = new ItemStack[contents.length];
        for (int i = 0; i < contents.length; i++) {
            ItemStack stack = contents[i];
            if (stack != null)
                clone[i] = stack.clone();
        }
        usedChests.put(loc, clone);
    }
}
 
Example #23
Source Project: DungeonsXL   Author: DRE2N   File: RewardListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
    Player player = event.getPlayer();
    if (DPlayerListener.isCitizensNPC(player)) {
        return;
    }
    GlobalPlayer dPlayer = plugin.getPlayerCache().get(player);
    if (plugin.getInstanceWorld(player.getWorld()) != null) {
        return;
    }
    Block block = player.getLocation().getBlock();
    if (dPlayer.hasRewardItemsLeft() && !VanillaItem.NETHER_PORTAL.is(block.getRelative(0, 1, 0)) && !VanillaItem.NETHER_PORTAL.is(block.getRelative(0, -1, 0))
            && !VanillaItem.NETHER_PORTAL.is(block.getRelative(1, 0, 0)) && !VanillaItem.NETHER_PORTAL.is(block.getRelative(-1, 0, 0))
            && !VanillaItem.NETHER_PORTAL.is(block.getRelative(0, 0, 1)) && !VanillaItem.NETHER_PORTAL.is(block.getRelative(0, 0, -1))) {
        PaginatedInventoryGUI lootInventory = new PaginatedInventoryGUI(DMessage.PLAYER_TREASURES.getMessage());
        PaginatedFlowInventoryLayout layout = new PaginatedFlowInventoryLayout(lootInventory, 54, PaginationButtonPosition.BOTTOM);
        layout.setSwitchButtonLinePlaceholdersEnabled(true);
        lootInventory.setLayout(layout);
        lootInventory.register();
        for (ItemStack item : dPlayer.getRewardItems()) {
            if (item != null) {
                InventoryButton button = new InventoryButton(item);
                button.setStealable(true);
                lootInventory.add(button);
            }
        }
        lootInventory.open(player);
        dPlayer.setRewardItems(null);
    }
}
 
Example #24
Source Project: ProjectAres   Author: OvercastNetwork   File: ToolRepairMatchModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void doRepair(PlayerPickupItemEvent event, ItemStack stack) {
    ItemStack pickup = event.getItem().getItemStack();

    int hitsLeft = pickup.getType().getMaxDurability() - pickup.getDurability() + 1;
    stack.setDurability((short) Math.max(stack.getDurability() - hitsLeft, 0));

    event.setCancelled(true);
    event.getItem().remove();
    event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_ITEM_PICKUP, 0.5f, 1f);
}
 
Example #25
Source Project: Thermos   Author: CyberdyneCC   File: CraftItemStack.java    License: GNU General Public License v3.0 5 votes vote down vote up
static boolean makeTag(net.minecraft.item.ItemStack item) {
    if (item == null) {
        return false;
    }

    if (item.stackTagCompound == null) {
        item.setTagCompound(new net.minecraft.nbt.NBTTagCompound());
    }

    return true;
}
 
Example #26
Source Project: Crazy-Crates   Author: badbones69   File: Prize.java    License: MIT License 5 votes vote down vote up
/**
 * @return Returns the display item that is shown for the preview and the winning prize.
 */
public ItemStack getDisplayItem() {
    if (displayItemStack == null) {
        displayItemStack = displayItem.build();
        NBTItem nbt = new NBTItem(displayItemStack);
        nbt.setString("crazycrate-prize", name);
        displayItemStack = nbt.getItem();
    }
    return displayItemStack.clone();
}
 
Example #27
Source Project: GiantTrees   Author: rmichela   File: ItemCost.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void dropExcess(Player player, int nToDrop) {
    while (nToDrop > 0) {
        ItemStack stack = new ItemStack(getMaterial(), Math.min(nToDrop, getMaterial().getMaxStackSize()), getData());
        player.getWorld().dropItemNaturally(player.getLocation(), stack);
        nToDrop -= getMaterial().getMaxStackSize();
    }
}
 
Example #28
Source Project: DungeonsXL   Author: DRE2N   File: Announcer.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param button the button
 * @return the matching DGroup
 */
public DGroup getDGroupByButton(ItemStack button) {
    int index = buttons.indexOf(button);
    if (dGroups.size() <= index || index < 0) {
        return null;
    } else {
        return dGroups.get(index);
    }
}
 
Example #29
Source Project: NyaaUtils   Author: NyaaCat   File: SignEditCommands.java    License: MIT License 5 votes vote down vote up
@SubCommand(value = "sign", permission = "nu.se.player")
public void commandSign(CommandSender sender, Arguments args) {
    Player player = asPlayer(sender);
    ItemStack item = getItemInHand(sender).clone();
    if (!SignEditListener.isSign(item.getType())) {
        msg(sender, "user.signedit.need_sign");
        return;
    }
    if (args.length() == 4) {
        int line = args.nextInt();
        String text = args.nextString();
        checkFormatCodes(text);
        text = ChatColor.translateAlternateColorCodes('&', text);
        if (ChatColor.stripColor(text).length() > plugin.cfg.signedit_max_length) {
            throw new BadCommandException("user.signedit.too_long", plugin.cfg.signedit_max_length);
        }
        if (line >= 0 && line < 4) {
            SignContent signContent = SignContent.fromItemStack(item);
            if ("CLEAR".equalsIgnoreCase(text)) {
                text = "";
            }
            signContent.setLine(line, text);
            printSignContent(player, signContent);
            player.getInventory().setItemInMainHand(signContent.toItemStack(item));
        } else {
            msg(sender, "user.signedit.invalid_line");
        }
    } else {
        printSignContent(player, SignContent.fromItemStack(item));
    }
}
 
Example #30
Source Project: SonarPet   Author: TechzoneMC   File: AbstractEntityZombiePet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initiateEntityPet() {
    super.initiateEntityPet();
    new BukkitRunnable() {
        @Override
        public void run() {
            //noinspection deprecation - 1.8.8 compatibility
            getBukkitEntity().getEquipment().setItemInHand(new ItemStack(getInitialItemInHand()));
        }
    }.runTaskLater(EchoPet.getPlugin(), 5L);
}