@Override
 protected void saveEditor(Inventory inventory, Player player) {
   for (int i = 0; i < 8; i++) {
     ItemStack item = inventory.getItem(i);
     if (item != null && item.getType() != Material.AIR) {
       ItemStack cost1 = null, cost2 = null;
       ItemStack item1 = inventory.getItem(i + 9);
       ItemStack item2 = inventory.getItem(i + 18);
       if (item1 != null && item1.getType() != Material.AIR) {
         cost1 = item1;
         if (item2 != null && item2.getType() != Material.AIR) {
           cost2 = item2;
         }
       } else if (item2 != null && item2.getType() != Material.AIR) {
         cost1 = item2;
       }
       if (cost1 != null) {
         Cost cost = new Cost();
         cost.amount = item.getAmount();
         cost.item1 = cost1;
         cost.item2 = cost2;
         ItemStack saleItem = item.clone();
         saleItem.setAmount(1);
         ((TradingPlayerShopkeeper) shopkeeper).costs.put(saleItem, cost);
       } else {
         ItemStack saleItem = item.clone();
         saleItem.setAmount(1);
         ((TradingPlayerShopkeeper) shopkeeper).costs.remove(saleItem);
       }
     }
   }
   ((TradingPlayerShopkeeper) shopkeeper).clickedItem = null;
 }
 private ItemStack getValidBook(Player player) {
   if (!spellSelection.containsKey(player)) return defaultSpell.clone();
   OfflinePlayer op = spellSelection.get(player);
   if (!op.isOnline()) return defaultSpell.clone();
   return customStack(
       Material.REDSTONE,
       ChatColor.RED + "HeartRipping",
       ChatColor.GOLD + "Currently bound to:",
       spellSelection.get(player).getName());
 }
 public ItemStack setEnchantments(ItemStack item, String enchants) {
   ItemStack i = item.clone();
   if (enchants.isEmpty()) return i;
   String[] ln = enchants.split(",");
   for (String ec : ln) {
     if (ec.isEmpty()) continue;
     Color clr = colorByName(ec);
     if (clr != null) {
       if (isIdInList(item.getTypeId(), "298,299,300,301")) {
         LeatherArmorMeta meta = (LeatherArmorMeta) i.getItemMeta();
         meta.setColor(clr);
         i.setItemMeta(meta);
       }
     } else {
       String ench = ec;
       int level = 1;
       if (ec.contains(":")) {
         ench = ec.substring(0, ec.indexOf(":"));
         level = Math.max(1, getMinMaxRandom(ec.substring(ench.length() + 1)));
       }
       Enchantment e = Enchantment.getByName(ench.toUpperCase());
       if (e == null) continue;
       i.addUnsafeEnchantment(e, level);
     }
   }
   return i;
 }
 @Override
 public List<ItemStack[]> getRecipes() {
   List<ItemStack[]> recipes = new ArrayList<ItemStack[]>();
   Map<ItemStack, Integer> chestItems = this.getItemsFromChest();
   for (ItemStack item : costs.keySet()) {
     if (chestItems.containsKey(item)) {
       Cost cost = costs.get(item);
       int chestAmt = chestItems.get(item);
       if (chestAmt >= cost.amount) {
         ItemStack[] recipe = new ItemStack[3];
         int slot = 0;
         if (cost.item1 != null
             && cost.item1.getType() != Material.AIR
             && cost.item1.getAmount() > 0) {
           recipe[slot++] = cost.item1;
         }
         if (cost.item2 != null
             && cost.item2.getType() != Material.AIR
             && cost.item2.getAmount() > 0) {
           recipe[slot] = cost.item2;
         }
         ItemStack saleItem = item.clone();
         saleItem.setAmount(cost.amount);
         recipe[2] = saleItem;
         recipes.add(recipe);
       }
     }
   }
   return recipes;
 }
Exemple #5
0
  @Override
  public boolean effect(Event event, Player player) {
    int slot = player.getInventory().getHeldItemSlot();

    ItemStack potion = player.getInventory().getItem(slot + 1);
    Location loc = player.getLocation();
    if (potion != null && potion.getType().toString().contains("POTION")) {
      ThrownPotion tp = player.launchProjectile(ThrownPotion.class);
      EffectManager.playSound(loc, "ENTITY_GENERIC_EXPLODE", 0.5f, 2f);

      try {
        tp.setItem(potion);
      } catch (IllegalArgumentException ex) {
        ItemStack pt = potion.clone();
        if (potion.getType().equals(Material.POTION)
            || potion.getType().equals(Material.LINGERING_POTION))
          pt.setType(Material.SPLASH_POTION);
        tp.setItem(pt);
      }

      tp.setBounce(false);
      tp.setVelocity(loc.getDirection().multiply(ProjectileSpeedMultiplier));
      if (!player.getGameMode().equals(GameMode.CREATIVE)) {
        potion.setAmount(potion.getAmount() - 1);
        player.getInventory().setItem(slot + 1, potion);
        player.updateInventory();
      }
      return true;
    } else {
      player.sendMessage(
          ChatColor.RED + "You need a Potion in the slot to the right of the Potion Launcher!");
      player.getWorld().playEffect(loc, Effect.CLICK1, 5);
    }
    return false;
  }
 public ItemStack[] getCalculatedItem(Voter voter) {
   ItemStack item = this.clone();
   if (!hasVariableAmount()) return new ItemStack[] {item};
   int sum = this.getCalculatedAmount(voter);
   if (sum < 1) {
     item.setAmount(1);
   } else {
     if (VoteRoulette.HAS_ITEM_LIMIT) {
       if (sum > VoteRoulette.VARIABLE_ITEM_LIMIT) {
         item.setAmount(VoteRoulette.VARIABLE_ITEM_LIMIT);
         return new ItemStack[] {item};
       }
     }
     if (sum > 64) {
       List<ItemStack> items = new ArrayList<ItemStack>();
       while (sum > 64) {
         ItemStack newItem = item.clone();
         newItem.setAmount(64);
         items.add(newItem);
         sum -= 64;
       }
       if (sum > 0) {
         item.setAmount(sum);
         items.add(item);
       }
       ItemStack[] array = new ItemStack[items.size()];
       items.toArray(array);
       return array;
     } else {
       item.setAmount(sum);
     }
   }
   return new ItemStack[] {item};
 }
  private ItemStack playerKilled(EntityType type) {
    if (!dropChances.containsKey(type)) return null;
    double percent = dropChances.get(type);
    if (Math.random() * 100d > percent) return null;

    return item.clone();
  }
  @Override
  public boolean finalizeTransaction(TransactionInfo info) {
    String stock = info.getStock().name().toLowerCase();
    Player player = info.getPlayerParticipant();
    int amount = info.getAmount();

    boolean result = false;
    int endAmount = amount * this.amount;
    ItemStack clone = is.clone();
    clone.setAmount(endAmount);

    if (stock == "sell") {
      ItemStack[] contents = player.getInventory().getContents();
      for (int i = 0; i < contents.length && endAmount > 0; ++i) {
        ItemStack nItem = contents[i];
        if (nItem != null && nItem.isSimilar(clone)) {
          int diff = endAmount - nItem.getAmount();
          if (diff < 0) nItem.setAmount(-diff);
          else player.getInventory().setItem(i, null);
          endAmount = diff;
        }
      }
      result = true;
    } else if (stock == "buy") {
      player.getInventory().addItem(clone);
      result = true;
    }
    return result;
  }
Exemple #9
0
 public void jobOrientation(Player p) {
   p.setGameMode(GameMode.SURVIVAL);
   if (this.equals(TimeProfession.OFFICER)) {
     PlayerInventory pi = p.getInventory();
     ItemStack inv_item = pi.getItem(0);
     String display_name = "";
     if (inv_item != null) {
       display_name = inv_item.getItemMeta().getDisplayName();
       if (display_name == null) display_name = "";
     }
     if (inv_item == null
         || !inv_item.getType().equals(Material.STICK)
         || !display_name.equals("Baton")) {
       ItemStack is = new ItemStack(Material.STICK, 1);
       ItemStack is_backup = null;
       if (inv_item != null) is_backup = inv_item.clone();
       ItemMeta im = is.getItemMeta();
       im.setDisplayName("Baton");
       ArrayList<String> lore = new ArrayList();
       lore.add("Arrests bountied players");
       im.setLore(lore);
       is.setItemMeta(im);
       pi.setItem(0, is);
       if (inv_item != null) pi.addItem(is_backup);
       p.updateInventory();
     }
   }
 }
 @Override
 protected void onInventoryClick(InventoryClickEvent event, Player player) {
   event.setCancelled(true);
   final int slot = event.getRawSlot();
   if (slot >= 0 && slot <= 7) {
     // handle changing sell stack size
     ItemStack item = event.getCurrentItem();
     if (item != null && item.getType() != Material.AIR) {
       int amount = item.getAmount();
       amount = this.getNewAmountAfterEditorClick(event, amount);
       if (amount <= 0) amount = 1;
       if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize();
       item.setAmount(amount);
     }
   } else if ((slot >= 9 && slot <= 16) || (slot >= 18 && slot <= 25)) {
     if (((TradingPlayerShopkeeper) shopkeeper).clickedItem != null) {
       // placing item
       final Inventory inventory = event.getInventory();
       Bukkit.getScheduler()
           .runTaskLater(
               ShopkeepersPlugin.getInstance(),
               new Runnable() {
                 public void run() {
                   inventory.setItem(slot, ((TradingPlayerShopkeeper) shopkeeper).clickedItem);
                   ((TradingPlayerShopkeeper) shopkeeper).clickedItem = null;
                 }
               },
               1);
     } else {
       // changing stack size
       ItemStack item = event.getCurrentItem();
       if (item != null && item.getType() != Material.AIR) {
         int amount = item.getAmount();
         amount = this.getNewAmountAfterEditorClick(event, amount);
         if (amount <= 0) {
           event.getInventory().setItem(slot, null);
         } else {
           if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize();
           item.setAmount(amount);
         }
       }
     }
   } else if (slot >= 27) {
     // clicking in player inventory
     if (event.isShiftClick() || !event.isLeftClick()) {
       return;
     }
     ItemStack cursor = event.getCursor();
     if (cursor != null && cursor.getType() != Material.AIR) {
       return;
     }
     ItemStack current = event.getCurrentItem();
     if (current != null && current.getType() != Material.AIR) {
       ((TradingPlayerShopkeeper) shopkeeper).clickedItem = current.clone();
       ((TradingPlayerShopkeeper) shopkeeper).clickedItem.setAmount(1);
     }
   } else {
     super.onInventoryClick(event, player);
   }
 }
 private void dropItem(ItemStack itemStack, List<ItemStack> itemDrops) {
   if (itemStack == null) {
     plugin.logDebug("Ignoring null item");
     return;
   }
   plugin.logDebug("Dropping item " + itemStack.getType());
   itemDrops.add(itemStack.clone());
   itemStack.setAmount(0);
 }
 public Slot setItem(ItemStack item) {
   if (item == null || item.getAmount() == 0) {
     stack = new ItemStack(Material.AIR);
     return this;
   }
   stack = item.clone();
   setDirty(true);
   return this;
 }
  protected static List<Entry<ItemStack, Integer>> getChangesClick(InventoryClickEvent event) {
    // Create
    List<Entry<ItemStack, Integer>> ret = new MassiveList<>();

    // Fill
    final InventoryAlter alter = InventoryUtil.getAlter(event);
    final InventoryAction action = event.getAction();
    ItemStack item;
    int amount;

    // Give
    if (alter.isGiving()) {
      // Special > MOVE_TO_OTHER_INVENTORY
      if (action == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
        item = event.getCurrentItem();

        ItemStack compare = item.clone();
        compare.setAmount(1);
        amount = InventoryUtil.roomLeft(event.getInventory(), compare, item.getAmount());
      }
      // Special > HOTBAR_SWAP
      else if (action == InventoryAction.HOTBAR_SWAP) {
        item = event.getView().getBottomInventory().getItem(event.getHotbarButton());

        amount = item.getAmount();
      }
      // Normal
      else {
        item = event.getCursor();

        amount = item.getAmount();
        if (action == InventoryAction.PLACE_ONE) {
          amount = 1;
        } else if (action == InventoryAction.PLACE_SOME) {
          int max = event.getCurrentItem().getType().getMaxStackSize();
          amount = max - event.getCurrentItem().getAmount();
        }
      }

      amount *= -1;
      ret.add(new SimpleEntry<ItemStack, Integer>(item, amount));
    }

    // Take
    if (alter.isTaking()) {
      item = event.getCurrentItem();

      amount = item.getAmount();
      if (action == InventoryAction.PICKUP_ONE) amount = 1;
      if (action == InventoryAction.PICKUP_HALF) amount = (int) Math.ceil(amount / 2.0);

      ret.add(new SimpleEntry<ItemStack, Integer>(item, amount));
    }

    // Return
    return ret;
  }
Exemple #14
0
  public ItemList<NamedItemStack> getOutputs() {
    ItemList<NamedItemStack> outputs = new ItemList<NamedItemStack>();
    Inventory inv = getInventory();
    if (mode.equals(CompactorMode.DECOMPACT)) {
      for (ItemStack is : inv.getContents()) {
        if (canDecompact(is)) {
          NamedItemStack clone =
              new NamedItemStack(
                  is.clone(),
                  is.getItemMeta().hasDisplayName()
                      ? is.getItemMeta().getDisplayName()
                      : is.getType().toString());
          clone.setAmount(clone.getMaxStackSize());
          ItemMeta cloneMeta = clone.getItemMeta();
          cloneMeta.setLore(null);
          clone.setItemMeta(cloneMeta);
          outputs.add(clone);

          return outputs;
        }
      }
    } else if (mode.equals(CompactorMode.COMPACT)) {
      for (ItemStack is : inv.getContents()) {
        if (canCompact(is)) {
          NamedItemStack clone =
              new NamedItemStack(
                  is.clone(),
                  is.getItemMeta().hasDisplayName()
                      ? is.getItemMeta().getDisplayName()
                      : is.getType().toString());
          clone.setAmount(1);
          ItemMeta cloneMeta = clone.getItemMeta();
          List<String> lore = new ArrayList<String>();
          lore.add(cp.getCompactLore());
          cloneMeta.setLore(lore);
          clone.setItemMeta(cloneMeta);

          outputs.add(clone);
          return outputs;
        }
      }
    }
    return outputs;
  }
  @Override
  public HashMap<Integer, ItemStack> addItem(ItemStack... items) {
    HashMap<Integer, ItemStack> result = new HashMap<>();

    for (int i = 0; i < items.length; ++i) {
      ItemStack item = ItemIds.sanitize(items[i]);
      if (item == null) continue; // invalid items fail silently
      int maxStackSize = item.getType() == null ? 64 : item.getType().getMaxStackSize();
      int toAdd = item.getAmount();

      for (int j = 0; toAdd > 0 && j < getSize(); ++j) {
        // Look for existing stacks to add to
        if (slots[j] != null && slots[j].isSimilar(item)) {
          int space = maxStackSize - slots[j].getAmount();
          if (space < 0) continue;
          if (space > toAdd) space = toAdd;

          slots[j].setAmount(slots[j].getAmount() + space);
          toAdd -= space;
        }
      }

      if (toAdd > 0) {
        // Look for empty slots to add to
        for (int j = 0; toAdd > 0 && j < getSize(); ++j) {
          if (slots[j] == null) {
            int num = toAdd > maxStackSize ? maxStackSize : toAdd;
            slots[j] = item.clone();
            slots[j].setAmount(num);
            toAdd -= num;
          }
        }
      }

      if (toAdd > 0) {
        // Still couldn't stash them all.
        ItemStack remaining = item.clone();
        remaining.setAmount(toAdd);
        result.put(i, remaining);
      }
    }

    return result;
  }
  public void input(int slot, ClickType action) {
    ItemStack is = null;
    if (slot >= 0 && slot <= 8) {
      if (slot == 8) {
        this.sfx(Sound.CLICK);
        this.close(true);
        return;
      }
      is = this.inventory.getItem(slot);
      if (is != null) {
        String s = Main.getItemData(is, 0);
        if (!s.isEmpty()) {
          if (s.startsWith("#")) {
            try {
              int id = Integer.parseInt(s.substring(1));
              this.sfx(Sound.CLICK);
              this.recipe.remove((Object) id);
              Main.giveReward(this.editing, id);
            } catch (NumberFormatException e) {

            }
          }
        }
      }
    } else if (slot >= 9 && slot <= 45) {
      if (slot >= 9 && slot <= 35) {
        is = this.editing.getInventory().getItem(slot);
      } else if (slot >= 36 && slot <= 45) {
        is = this.editing.getInventory().getItem(slot - 36);
      }
      if (is != null) {
        String s = Main.getItemData(is, 0);
        if (!s.isEmpty()) {
          if (s.startsWith("#")) {
            try {
              int id = Integer.parseInt(s.substring(1));
              if (this.recipe.size() >= 4) {
                this.editing.sendMessage("Cannot fuse more than 4 cards.");
                this.sfx(Sound.FIRE_IGNITE);
                return;
              }
              this.recipe.add(id);
              this.sfx(Sound.CLICK);
              is = is.clone();
              is.setAmount(1);
              this.editing.getInventory().removeItem(is);
            } catch (NumberFormatException e) {

            }
          }
        }
      }
    }
    this.updateInterface();
  }
Exemple #17
0
 public ItemStack toItemStack(String locale) {
   ItemStack rStack = item.clone();
   RPGMetadata rpgMeta = new RPGMetadata();
   ItemMeta meta = getLocaleMeta(locale);
   List<String> lore = meta.getLore();
   lore.set(0, meta.getLore().get(0) + rpgMeta.toMCString());
   addExtra(rpgMeta, rStack, lore);
   meta.setLore(lore);
   rStack.setItemMeta(meta);
   return rStack;
 }
 // Calculate how many times you could add this item to the inventory.
 // NOTE: This method does not alter the inventory.
 public static int roomLeft(Inventory inventory, ItemStack item, int limit) {
   // NOTE: We can not afford to clone player inventories here.
   inventory = clone(inventory, false);
   int ret = 0;
   while (limit <= 0 || ret < limit) {
     HashMap<Integer, ItemStack> result = inventory.addItem(item.clone());
     if (result.size() != 0) return ret;
     ret++;
   }
   return ret;
 }
  public boolean stock() {

    if (offset.getBlock().getState() instanceof InventoryHolder) {

      Chest c = (Chest) offset.getBlock().getState();
      if (c.getInventory().addItem(item.clone()).isEmpty()) {
        c.update();
        return true;
      }
    }
    return false;
  }
Exemple #20
0
 @SuppressWarnings("deprecation")
 public static void setTeamHead(ItemStack item, Player p) {
   if (p.isOnline() && !p.isDead()) {
     ItemStack is = p.getInventory().getHelmet();
     try {
       p.getInventory().setHelmet(item);
       if (is != null && is.getType() != Material.AIR && is.getType() != Material.WOOL) {
         InventoryUtil.addItemToInventory(p, is.clone(), is.getAmount(), true, true);
       }
       p.updateInventory();
     } catch (Exception e) {
       if (!Defaults.DEBUG_VIRTUAL) Log.printStackTrace(e);
     }
   }
 }
Exemple #21
0
  public ItemList<NamedItemStack> getInputs() {
    ItemList<NamedItemStack> inputs = new ItemList<NamedItemStack>();
    Inventory inv = getInventory();
    if (mode.equals(CompactorMode.DECOMPACT)) {
      for (ItemStack is : inv.getContents()) {
        if (canDecompact(is)) {
          NamedItemStack clone =
              new NamedItemStack(
                  is.clone(),
                  is.getItemMeta().hasDisplayName()
                      ? is.getItemMeta().getDisplayName()
                      : is.getType().toString());
          clone.setAmount(1);
          inputs.add(clone);

          return inputs;
        }
      }
    } else if (mode.equals(CompactorMode.COMPACT)) {
      for (ItemStack is : inv.getContents()) {
        if (canCompact(is)) {
          NamedItemStack clone =
              new NamedItemStack(
                  is.clone(),
                  is.getItemMeta().hasDisplayName()
                      ? is.getItemMeta().getDisplayName()
                      : is.getType().toString());
          inputs.add(clone);

          inputs.addAll(cp.getRecipeMaterials());
          return inputs;
        }
      }
    }
    return inputs;
  }
Exemple #22
0
  public void setBlock(ItemStack block) {
    if (block != null) {
      this.block = block.clone();
      this.block.setAmount(1);

      if (status == PetState.Here) {
        ((EntityMyEnderman) getCraftPet().getHandle())
            .setBlock(this.block.getTypeId(), this.block.getData().getData());
      }
    } else {
      if (status == PetState.Here) {
        ((EntityMyEnderman) getCraftPet().getHandle()).setBlock(0, 0);
      }
      this.block = null;
    }
  }
Exemple #23
0
 @Override
 protected void execute(Event event) {
   Location l = location.getSingle(event);
   Player p = player.getSingle(event);
   if (l == null) {
     return;
   } else if (p == null) {
     return;
   }
   Location loc = p.getLocation().clone();
   Inventory inv = p.getInventory();
   for (ItemStack item : inv.getContents()) {
     if (item != null) {
       loc.getWorld().dropItem(l, item.clone());
     }
   }
   inv.clear();
 }
 private Map<ItemStack, Integer> getItemsFromChest() {
   Map<ItemStack, Integer> map = new LinkedHashMap<ItemStack, Integer>();
   Block chest = this.getChest();
   if (Utils.isChest(chest.getType())) {
     Inventory inv = ((Chest) chest.getState()).getInventory();
     ItemStack[] contents = inv.getContents();
     for (ItemStack item : contents) {
       if (item != null && item.getType() != Material.AIR) {
         ItemStack i = item.clone();
         i.setAmount(1);
         if (map.containsKey(i)) {
           map.put(i, map.get(i) + item.getAmount());
         } else {
           map.put(i, item.getAmount());
         }
       }
     }
   }
   return map;
 }
 @Override
 public List<ItemStack[]> getRecipes() {
   List<ItemStack[]> recipes = new ArrayList<ItemStack[]>();
   if (this.chestHasBlankBooks()) {
     List<ItemStack> books = this.getBooksFromChest();
     for (ItemStack book : books) {
       if (book != null) {
         String title = getTitleOfBook(book);
         if (title != null && offers.containsKey(title)) {
           int price = offers.get(title);
           ItemStack[] recipe = new ItemStack[3];
           this.setRecipeCost(recipe, price);
           recipe[2] = book.clone();
           recipes.add(recipe);
         }
       }
     }
   }
   return recipes;
 }
Exemple #26
0
  // Create a Potion from this Recipe with best values. Quality can be set, but will reset to 10 if
  // put in a barrel
  public ItemStack create(int quality) {
    ItemStack potion = new ItemStack(Material.POTION);
    PotionMeta potionMeta = (PotionMeta) potion.getItemMeta();

    int uid = Brew.generateUID();

    ArrayList<ItemStack> list = new ArrayList<ItemStack>(ingredients.size());
    for (ItemStack item : ingredients) {
      if (item.getDurability() == -1) {
        list.add(new ItemStack(item.getType(), item.getAmount()));
      } else {
        list.add(item.clone());
      }
    }

    BIngredients bIngredients = new BIngredients(list, cookingTime);

    Brew brew =
        new Brew(
            uid,
            bIngredients,
            quality,
            distillruns,
            getAge(),
            wood,
            getName(5),
            false,
            false,
            true);

    potion.setDurability(Brew.PotionColor.valueOf(getColor()).getColorId(false));
    potionMeta.setDisplayName(P.p.color("&f" + getName(quality)));
    // This effect stores the UID in its Duration
    potionMeta.addCustomEffect((PotionEffectType.REGENERATION).createEffect((uid * 4), 0), true);

    brew.convertLore(potionMeta, false);
    Brew.addOrReplaceEffects(potionMeta, effects, quality);

    potion.setItemMeta(potionMeta);
    return potion;
  }
Exemple #27
0
  /**
   * Clones and compresses an inventory for storage
   *
   * @param items The inventory contents to be compressed and cloned
   * @return The compressed cloned inventory
   */
  public static List<ItemStack> compressInventory(ItemStack[] items) {
    ArrayList<ItemStack> comItems = new ArrayList<>(items.length);

    for (ItemStack item : items) {

      if (item != null) {

        item = item.clone();

        ItemStack similarItem = findSimilarItemStack(comItems, item);

        if (similarItem != null) {
          similarItem.setAmount(similarItem.getAmount() + item.getAmount());
        } else {
          comItems.add(item);
        }
      }
    }

    return comItems;
  }
 /**
  * add an ItemStack to an array
  *
  * @param items
  * @param toAdd
  * @param extraStack whether to allow some nonstackable items to stack
  * @return
  */
 public static ItemStack add(ItemStack[] items, ItemStack toAdd, boolean extraStack) {
   ItemStack ret = toAdd.clone();
   int mx = !extraStack || noStack.contains(toAdd.getTypeId()) ? JItems.getMaxStack(toAdd) : 64;
   boolean firstRun = true;
   for (int i = 0; i < items.length; ++i) {
     if (!firstRun && (items[i] == null || items[i].getAmount() == 0)) {
       if (items[i] == null) {
         items[i] = toAdd;
       } else {
         items[i].setTypeId(toAdd.getTypeId());
         items[i].setDurability(toAdd.getDurability());
         items[i].addEnchantments(toAdd.getEnchantments());
       }
       items[i].setAmount(ret.getAmount());
       ret.setAmount(0);
       return ret;
     } else if (items[i] != null
         && items[i].getTypeId() == toAdd.getTypeId()
         && items[i].getDurability()
             == toAdd
                 .getDurability() // (!JItems.hasData(toAdd.getTypeId()) ||
                                  // items[i].getData().getData() == toAdd.getData().getData())
         && sameEnchants(items[i], toAdd)
         && items[i].getAmount() < mx) {
       // on first run, look for other stacks in array that could be incremented instead
       if (items[i].getAmount() + ret.getAmount() <= mx) {
         items[i].setAmount(items[i].getAmount() + ret.getAmount());
         ret.setAmount(0);
         return ret;
       } else {
         ret.setAmount(ret.getAmount() - (mx - items[i].getAmount()));
         items[i].setAmount(mx);
       }
     } else if (firstRun && i + 1 >= items.length) {
       firstRun = false;
       i = -1; // negative, because gets incremented again
     }
   }
   return ret;
 }
Exemple #29
0
  protected PedestalBase(ItemStack pedistalType, ItemStack hoverItem, Location pedestalLocation) {
    mIsLoaded = true;
    mLocation = pedestalLocation.clone();
    mLocation
        .getBlock()
        .setTypeIdAndData(pedistalType.getTypeId(), pedistalType.getData().getData(), true);

    mHoverItemTemplate = hoverItem.clone();

    // Check for existing item
    Collection<Item> items = mLocation.getWorld().getEntitiesByClass(Item.class);
    Location loc = mLocation.clone().add(0, 1, 0);

    for (Item item : items) {
      if (item.getItemStack().equals(hoverItem)
          && item.getLocation().distanceSquared(loc) < 1D
          && !item.isDead()) {
        // Reattach the item
        mHoveringItem = item;
        SkyQuestPlugin.instance.getLogger().fine("Attaching old item");
        break;
      }
    }
    // Spawn a new item if needed
    if (mHoveringItem == null) {
      SkyQuestPlugin.instance.getLogger().fine("Spawning new item");
      mHoveringItem =
          mLocation.getWorld().dropItem(mLocation.clone().add(0.5, 1, 0.5), mHoverItemTemplate);
      mHoveringItem.setVelocity(new Vector(0, 0, 0));
    }

    // Register the event listener
    mEventListener = new PedestalListener();
    SkyQuestPlugin.instance
        .getServer()
        .getPluginManager()
        .registerEvents(mEventListener, SkyQuestPlugin.instance);
  }
Exemple #30
0
	private Trade rechargeSign(final ISign sign, final IEssentials ess, final IUser player) throws SignException, ChargeException
	{
		final Trade trade = getTrade(sign, 2, false, false, ess);
		ItemStack itemInHand = player.getPlayer().getItemInHand();
		if (trade.getItemStack() != null && itemInHand != null
			&& trade.getItemStack().getTypeId() == itemInHand.getTypeId()
			&& trade.getItemStack().getDurability() == itemInHand.getDurability()
			&& trade.getItemStack().getEnchantments().equals(itemInHand.getEnchantments()))
		{
			int amount = itemInHand.getAmount();
			amount -= amount % trade.getItemStack().getAmount();
			if (amount > 0)
			{
				final ItemStack stack = itemInHand.clone();
				stack.setAmount(amount);
				final Trade store = new Trade(stack, ess);
				addAmount(sign, 2, store, ess);
				store.charge(player);
				return store;
			}
		}
		return null;
	}