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.
Example 1
Project: Skript   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
Project: Slimefun4   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
Project: BedWars   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
Project: Slimefun4   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
Project: MineTinker   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
Project: Holograms   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
Project: ProjectAres   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
Project: 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
Project: RedProtect   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
Project: civcraft   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
Project: ProRecipes   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
Project: Thermos   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
Project: Skript   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
Project: MineTinker   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
Project: uSkyBlock   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
Project: Skript   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
Project: UhcCore   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
Project: BedWars   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
Project: HeavySpleef   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
Project: Kettle   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
Project: Slimefun4   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
Project: BedWars   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
Project: DungeonsXL   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
Project: ProjectAres   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
Project: Thermos   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
Project: Crazy-Crates   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
Project: GiantTrees   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
Project: DungeonsXL   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
Project: NyaaUtils   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
Project: SonarPet   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);
}
 
Example 31
Project: Thermos   File: CraftInventoryView.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setItem(int slot, ItemStack item) {
    net.minecraft.item.ItemStack stack = CraftItemStack.asNMSCopy(item);
    if (slot != -999) {
        container.getSlot(slot).putStack(stack);
    } else {
        player.getHandle().dropPlayerItemWithRandomChoice(stack, false);
    }
}
 
Example 32
Project: IF   File: PaginatedPane.java    License: The Unlicense 5 votes vote down vote up
/**
 * Populates the PaginatedPane based on the provided list by adding new pages until all items can fit.
 * This can be helpful when dealing with lists of unknown size.
 *
 * @param items The list to populate the pane with
 */
@Contract("null -> fail")
public void populateWithItemStacks(@NotNull List<ItemStack> items) {
	//Don't do anything if the list is empty
	if (items.isEmpty()) {
	    return;
       }

	int itemsPerPage = this.height * this.length;
	int pagesNeeded = (int) Math.max(Math.ceil(items.size() / (double) itemsPerPage), 1);

	for (int i = 0; i < pagesNeeded; i++) {
		OutlinePane page = new OutlinePane(0, 0, this.length, this.height);

		for (int j = 0; j < itemsPerPage; j++) {
			//Check if the loop reached the end of the list
			int index = i * itemsPerPage + j;

			if (index >= items.size()) {
			    break;
               }

			page.addItem(new GuiItem(items.get(index)));
		}

		this.addPane(i, page);
	}
}
 
Example 33
Project: Civs   File: ShopMenu.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean doActionAndCancel(Civilian civilian, String actionString, ItemStack clickedItem) {
    if (actionString.equals("view-item")) {
        String key = clickedItem.getItemMeta().getLore().get(0);
        Player player = Bukkit.getPlayer(civilian.getUuid());
        String sortType = (String) MenuManager.getData(civilian.getUuid(), "sort");
        HashMap<String, String> params = new HashMap<>();
        String name = ChatColor.stripColor(key).toLowerCase();
        CivItem civItem = ItemManager.getInstance().getItemType(name);
        if (civItem != null) {
            if (civItem.getItemType() == CivItem.ItemType.REGION) {
                params.put("regionType", name);
                params.put("showPrice", "true");
                MenuManager.getInstance().openMenu(player, "region-type", params);
                return true;
            } else if (civItem.getItemType() == CivItem.ItemType.TOWN) {
                params.put("townType", name);
                params.put("showPrice", "true");
                MenuManager.getInstance().openMenu(player, "town-type", params);
                return true;
            }
        } else if (clickedItem.getType() == Material.BARRIER) {
            return true;
        }
        if ("level".equals(sortType)) {
            int level = Integer.parseInt(name);
            params.put("level", "" + level);
            params.put("sort", "level");
            MenuManager.getInstance().openMenu(player, "shop", params);
            return true;
        } else if ("category".equals(sortType)) {
            params.put("sort", "category");
            params.put("parent", ChatColor.stripColor(key).toLowerCase());
            MenuManager.getInstance().openMenu(player, "shop", params);
            return true;
        }
        return true;
    }
    return super.doActionAndCancel(civilian, actionString, clickedItem);
}
 
Example 34
Project: Shopkeepers   File: BuyingPlayerShopkeeper.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void saveEditor(Inventory inventory, Player player) {
	final BuyingPlayerShopkeeper shopkeeper = this.getShopkeeper();
	for (int column = 0; column < 8; column++) {
		ItemStack tradedItem = inventory.getItem(column + 18);
		if (!Utils.isEmpty(tradedItem)) {
			ItemStack priceItem = inventory.getItem(column);
			if (priceItem != null && priceItem.getType() == Settings.currencyItem && priceItem.getAmount() > 0) {
				shopkeeper.addOffer(tradedItem, priceItem.getAmount());
			} else {
				shopkeeper.removeOffer(tradedItem);
			}
		}
	}
}
 
Example 35
Project: Slimefun4   File: PostSetup.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void registerMachineRecipe(String machine, int seconds, ItemStack[] input, ItemStack[] output) {
    for (SlimefunItem item : SlimefunPlugin.getRegistry().getEnabledSlimefunItems()) {
        if (item instanceof AContainer && ((AContainer) item).getMachineIdentifier().equals(machine)) {
            ((AContainer) item).registerRecipe(seconds, input, output);
        }
    }
}
 
Example 36
Project: ProRecipes   File: RecipeShapeless.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean moreThanOne(){
	for(ItemStack i : items){
		if(i.getAmount() > 1){
			return true;
		}
	}
	return false;
}
 
Example 37
Project: PGM   File: ScoreMatchModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private double redeemItems(ScoreBox box, ItemStack stack) {
  if (stack == null) return 0;
  double points = 0;
  for (Entry<SingleMaterialMatcher, Double> entry : box.getRedeemables().entrySet()) {
    if (entry.getKey().matches(stack.getData())) {
      points += entry.getValue() * stack.getAmount();
      stack.setAmount(0);
    }
  }
  return points;
}
 
Example 38
Project: Kettle   File: CraftShapelessRecipe.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static CraftShapelessRecipe fromBukkitRecipe(ShapelessRecipe recipe) {
    if (recipe instanceof CraftShapelessRecipe) {
        return (CraftShapelessRecipe) recipe;
    }
    CraftShapelessRecipe ret = new CraftShapelessRecipe(recipe.getKey(), recipe.getResult());
    for (ItemStack ingred : recipe.getIngredientList()) {
        ret.addIngredient(ingred.getType(), ingred.getDurability());
    }
    return ret;
}
 
Example 39
Project: ExoticGarden   File: ExoticGarden.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void registerBerry(String name, ChatColor color, Color potionColor, PlantType type, String texture) {
	String upperCase = name.toUpperCase(Locale.ROOT);
	Berry berry = new Berry(upperCase, type, texture);
	berries.add(berry);

	SlimefunItemStack sfi = new SlimefunItemStack(upperCase + "_BUSH", Material.OAK_SAPLING, color + name + " Bush");

	items.put(upperCase + "_BUSH", sfi);

	new SlimefunItem(mainCategory, sfi, ExoticGardenRecipeTypes.BREAKING_GRASS,
	new ItemStack[] {null, null, null, null, new ItemStack(Material.GRASS), null, null, null, null})
	.register(this);

	new ExoticGardenFruit(mainCategory, new SlimefunItemStack(upperCase, texture, color + name), ExoticGardenRecipeTypes.HARVEST_BUSH, true,
	new ItemStack[] {null, null, null, null, getItem(upperCase + "_BUSH"), null, null, null, null})
	.register(this);

	new Juice(drinksCategory, new SlimefunItemStack(upperCase + "_JUICE", new CustomPotion(color + name + " Juice", potionColor, new PotionEffect(PotionEffectType.SATURATION, 6, 0), "", "&7&oRestores &b&o" + "3.0" + " &7&oHunger")), RecipeType.JUICER,
	new ItemStack[] {getItem(upperCase), null, null, null, null, null, null, null, null})
	.register(this);

	new Juice(drinksCategory, new SlimefunItemStack(upperCase + "_SMOOTHIE", new CustomPotion(color + name + " Smoothie", potionColor, new PotionEffect(PotionEffectType.SATURATION, 10, 0), "", "&7&oRestores &b&o" + "5.0" + " &7&oHunger")), RecipeType.ENHANCED_CRAFTING_TABLE,
	new ItemStack[] {getItem(upperCase + "_JUICE"), getItem("ICE_CUBE"), null, null, null, null, null, null, null})
	.register(this);

	new CustomFood(foodCategory, new SlimefunItemStack(upperCase + "_JELLY_SANDWICH", "8c8a939093ab1cde6677faf7481f311e5f17f63d58825f0e0c174631fb0439", color + name + " Jelly Sandwich", "", "&7&oRestores &b&o" + "8.0" + " &7&oHunger"),
	new ItemStack[] {null, new ItemStack(Material.BREAD), null, null, getItem(upperCase + "_JUICE"), null, null, new ItemStack(Material.BREAD), null},
	16)
	.register(this);

	new CustomFood(foodCategory, new SlimefunItemStack(upperCase + "_PIE", "3418c6b0a29fc1fe791c89774d828ff63d2a9fa6c83373ef3aa47bf3eb79", color + name + " Pie", "", "&7&oRestores &b&o" + "6.5" + " &7&oHunger"),
	new ItemStack[] {getItem(upperCase), new ItemStack(Material.EGG), new ItemStack(Material.SUGAR), new ItemStack(Material.MILK_BUCKET), SlimefunItems.WHEAT_FLOUR, null, null, null, null},
	13)
	.register(this);
}
 
Example 40
Project: FunnyGuilds   File: ItemUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String translateTextPlaceholder(String message, Collection<ItemStack> items, ItemStack item) {
    StringBuilder contentBuilder = new StringBuilder();

    if (message.contains("{ITEM}")) {
        contentBuilder.append(item.getAmount());
        contentBuilder.append(" ");
        contentBuilder.append(item.getType().toString().toLowerCase());

        message = StringUtils.replace(message, "{ITEM}", contentBuilder.toString());
    }

    if (message.contains("{ITEMS}")) {
        Collection<String> translatedItems = new ArrayList<>();

        for (ItemStack itemStack : items) {
            contentBuilder.setLength(0);

            contentBuilder.append(itemStack.getAmount());
            contentBuilder.append(" ");
            contentBuilder.append(itemStack.getType().toString().toLowerCase());

            translatedItems.add(contentBuilder.toString());
        }

        message = StringUtils.replace(message, "{ITEMS}", ChatUtils.toString(translatedItems, true));
    }

    return message;
}