Beispiel #1
0
 public String getEnchantmentTypeName(ItemStack itemStack) {
   Enchantment enchantment = null;
   Integer level = 0;
   for (Map.Entry<Enchantment, Integer> e : itemStack.getEnchantments().entrySet()) {
     if (e.getValue() > level) {
       enchantment = e.getKey();
       level = e.getValue();
     }
   }
   if (enchantment == null) {
     return getPlugin()
         .getConfigurationManager()
         .getConfiguration(MythicConfigurationFile.LANGUAGE)
         .getString("Ordinary");
   }
   String ench =
       getPlugin()
           .getConfigurationManager()
           .getConfiguration(MythicConfigurationFile.LANGUAGE)
           .getString(enchantment.getName());
   if (ench != null) {
     return ench;
   }
   return "Ordinary";
 }
Beispiel #2
0
  /**
   * Registers an enchantment with the given ID and object.
   *
   * <p>Generally not to be used from within a plugin.
   *
   * @param id ID of the enchantment
   * @param enchantment Enchantment to register
   */
  public static void registerEnchantment(Enchantment enchantment) {
    if (byId.containsKey(enchantment.id) || byName.containsKey(enchantment.getName())) {
      throw new IllegalArgumentException("Cannot set already-set enchantment");
    } else if (!isAcceptingRegistrations()) {
      throw new IllegalStateException(
          "No longer accepting new enchantments (can only be done by the server implementation)");
    }

    byId.put(enchantment.id, enchantment);
    byName.put(enchantment.getName(), enchantment);
  }
Beispiel #3
0
 ItemStack updateEnchants(ItemStack item) {
   ArrayList<String> enchants = new ArrayList<String>();
   for (Enchantment ench : item.getEnchantments().keySet()) {
     if (!isNatural(ench)) {
       enchants.add(
           ChatColor.GRAY + ench.getName() + " " + toRoman(item.getEnchantments().get(ench)));
     }
   }
   ItemMeta meta = item.getItemMeta();
   meta.setLore(enchants);
   item.setItemMeta(meta);
   return item;
 }
	public static Enchantment getEnchantment(final String name, final IUser user) throws Exception
	{

		final Enchantment enchantment = Enchantments.getByName(name);
		if (enchantment == null)
		{
			throw new Exception(_("enchantmentNotFound"));
		}
		final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
		if (user != null && !Permissions.ENCHANT.isAuthorized(user, enchantmentName))
		{
			throw new Exception(_("enchantmentPerm", enchantmentName));
		}
		return enchantment;
	}
 @SuppressWarnings("deprecation")
 public ArrayList<ItemStack> getInventory(String id) {
   FileConfiguration c = SettingsManager.getInstance().getClasses();
   ArrayList<ItemStack> inv = new ArrayList<ItemStack>();
   for (String item : c.getConfigurationSection(id + ".items").getKeys(false)) {
     try {
       Material m = Material.getMaterial(c.getInt(id + ".items." + item + ".id"));
       int amount = c.getInt(id + ".items." + item + ".amount");
       ItemStack is = new ItemStack(m, amount);
       if (c.contains(id + ".items." + item + ".id-modifier")) {
         int idm = c.getInt(id + ".items." + item + ".id-modifier");
         is.setDurability((short) idm);
       }
       if (c.contains(id + ".items." + item + ".enchantments")) {
         for (String e :
             c.getConfigurationSection(id + ".items." + item + ".enchantments").getKeys(false)) {
           Enchantment enchant = Enchantment.getByName(e);
           int level = Integer.parseInt(c.getString(id + ".items." + item + ".enchantments." + e));
           is.addUnsafeEnchantment(enchant, level);
         }
       }
       inv.add(is);
     } catch (Exception e) {
       System.out.println(
           "Error adding item " + item + " for class " + id + ", please check the yml file.");
     }
   }
   return inv;
 }
 @SuppressWarnings("deprecation")
 public String getName() {
   if (e != null)
     return String.valueOf(e.getId())
         .replace("16", "Sharpness")
         .replace("17", "Smite")
         .replace("18", "Bane of Arthropods")
         .replace("19", "Knockback")
         .replace("20", "Fire Aspect")
         .replace("21", "Looting")
         .replace("32", "Efficiency")
         .replace("33", "Silk Touch")
         .replace("34", "Unbreaking")
         .replace("35", "Fortune")
         .replace("48", "Power")
         .replace("49", "Punch")
         .replace("50", "Flame")
         .replace("51", "Infinity")
         .replace("0", "Protection")
         .replace("1", "Fire Protection")
         .replace("2", "Feather Falling")
         .replace("3", "Blast Protection")
         .replace("4", "Projectile Protection")
         .replace("5", "Respiration")
         .replace("6", "Aqua Afinity")
         .replace("7", "Thorns");
   if (ce != null) return ce.getName();
   return null;
 }
Beispiel #7
0
 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;
 }
 public ItemStack getBoots(String id) {
   FileConfiguration c = SettingsManager.getInstance().getClasses();
   if (c.contains(id + ".boots")) {
     Material m = Material.getMaterial(c.getInt(id + ".boots.id"));
     ItemStack is = new ItemStack(m, 1);
     if (m == Material.LEATHER_BOOTS && c.contains(id + ".boots.color")) {
       String color = c.getString(id + ".boots.color");
       String[] rgb = color.split(",");
       int r = Integer.parseInt(rgb[0]);
       int g = Integer.parseInt(rgb[1]);
       int b = Integer.parseInt(rgb[2]);
       is = Colorizer.setColor(is, r, g, b);
     }
     if (c.contains(id + ".boots.enchantments")) {
       for (String e : c.getConfigurationSection(id + ".boots.enchantments").getKeys(false)) {
         Enchantment enchant = Enchantment.getByName(e);
         int level = Integer.parseInt(c.getString(id + ".boots.enchantments." + e));
         is.addUnsafeEnchantment(enchant, level);
       }
     }
     return is;
   } else {
     return new ItemStack(Material.AIR);
   }
 }
Beispiel #9
0
 private double getEnchantmentBonus(ItemStack item, Stat stat) {
   double bonus = 0D;
   if (item.hasItemMeta()) {
     ItemMeta meta = item.getItemMeta();
     if (meta.hasEnchants()) {
       for (Enchantment enchantment : meta.getEnchants().keySet()) {
         bonus +=
             meta.getEnchants().get(enchantment)
                 * plugin
                     .getConfig()
                     .getDouble("rolls.enchants." + enchantment.getName() + "." + stat.toString());
       }
     }
   }
   return bonus;
 }
Beispiel #10
0
  public boolean addEnchantmentsToPlayerInventorySlot(
      String playerName, int slot, List<Object> enchantments) {
    try {
      Player p = getPlayerExact(playerName);
      PlayerInventory inv = p.getInventory();
      ItemStack it;

      if (slot == inv.getHeldItemSlot()) it = inv.getHelmet();
      else if (slot == 102) it = inv.getChestplate();
      else if (slot == 101) it = inv.getLeggings();
      else if (slot == 100) it = inv.getBoots();
      else it = inv.getItem(slot);

      for (int i = 0; i < enchantments.size(); i++) {
        JSONObject o = (JSONObject) enchantments.get(i);
        it.addEnchantment(
            Enchantment.getById(Integer.valueOf(o.get("enchantment").toString())),
            Integer.valueOf(o.get("level").toString()));
      }

      p.saveData();

      return true;
    } catch (NullPointerException e) {
      return false;
    }
  }
Beispiel #11
0
  public static void enchantValidate(Player p, String e, int rlvl) { // shut up for now :P
    HashMap<Enchantment, Integer> fen = new HashMap<Enchantment, Integer>();
    ItemStack i = null;
    int lvl = 0;
    Enchantment en = Enchantment.getById(getEnchantId(e));

    if (p.getItemInHand().getTypeId() == ((ItemStack) item.get(p.getName())).getTypeId()) {
      i = p.getItemInHand();
      if (i.getAmount() == 1) {
        if (i.containsEnchantment(en)) {
          int plvl = i.getEnchantmentLevel(en);
          lvl = plvl + rlvl;
        } else {
          lvl = rlvl;
        }
        fen.put(en, lvl);
        enchants.put(p.getName(), fen);
        ChatListener.add(p, 2);
        p.sendMessage(
            "The enchant will cost you: "
                + getEnchantCost(p, e.toLowerCase(), rlvl)
                + "! Should I continue? Please type \"yes\" or \"no\"!");
      } else {
        p.sendMessage(
            ChatColor.RED + "You have more then one item in your slot, please try again!");
      }
    }
  }
Beispiel #12
0
  /**
   * parse through dat to create a new item with enchantments, quantity, and damage value
   *
   * @param cfg to parse through
   * @return the new ItemStack
   */
  private ItemStack parseItem(ConfigurationSection cfg) {
    Map<String, Object> vals = cfg.getValues(true);
    ItemStack newItem;
    // check material
    newItem =
        new ItemStack(Material.getMaterial((cfg.getString("material", "stone")).toUpperCase()));

    // check damage value

    newItem.setDurability((short) (cfg.getInt("damage", 0)));

    // check quantity

    newItem.setAmount(cfg.getInt("amount", 1));

    // enchantment parsing
    for (String s : cfg.getStringList("enchantments")) {
      String[] parts = s.split(":");
      String enchant = parts[0];
      int level = 1;

      if (parts.length > 1) {
        level = Integer.parseInt(parts[1]);
      }
      newItem.addUnsafeEnchantment(Enchantment.getByName(enchant.toUpperCase()), level);
    }

    // System.out.println("Item: "+ newItem.toString());
    return newItem;

    // ItemStack is = new ItemStack(Material.);
  }
Beispiel #13
0
  public static void enchantInventory(Player player) {
    ItemStack[] itemStack = player.getInventory().getContents();
    Enchantment[] enchantments = Enchantment.values();

    for (ItemStack item : itemStack) {
      if (item != null) {
        for (Enchantment enchantment : enchantments) {
          if (enchantment != null) {
            try {
              item.addEnchantment(enchantment, enchantment.getMaxLevel());
            } catch (Exception ex) {
            } // Ignore
          }
        }
      }
    }
  }
  /**
   * Add an enchantment.
   *
   * @param level The enchantment level.
   * @param enchantmentName The enchantment name.
   * @return Self for chaining.
   * @throws IllegalArgumentException if the enchantment name is not recognized.
   */
  public ItemStackBuilder enchant(int level, String enchantmentName) {
    PreCon.notNull(enchantmentName);

    Enchantment enchantment = Enchantment.getByName(enchantmentName);
    if (enchantment == null)
      throw new IllegalArgumentException("Cannot find an enchantment named " + enchantmentName);

    return enchant(level, enchantment);
  }
 @Override
 public String toString() {
   if (ce != null) {
     return ce.getName() + "-" + level;
   } else if (e != null) {
     return e.getName() + "-" + level;
   } else {
     return null;
   }
 }
Beispiel #16
0
  /**
   * Adds the specified {@link Enchantment} to this item stack.
   *
   * <p>If this item stack already contained the given enchantment (at any level), it will be
   * replaced.
   *
   * @param ench Enchantment to add
   * @param level Level of the enchantment
   * @throws IllegalArgumentException if enchantment null, or enchantment is not applicable
   */
  @Utility
  public void addEnchantment(Enchantment ench, int level) {
    Validate.notNull(ench, "Enchantment cannot be null");
    if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) {
      throw new IllegalArgumentException(
          "Enchantment level is either too low or too high (given "
              + level
              + ", bounds are "
              + ench.getStartLevel()
              + " to "
              + ench.getMaxLevel()
              + ")");
    } else if (!ench.canEnchantItem(this)) {
      throw new IllegalArgumentException(
          "Specified enchantment cannot be applied to this itemstack");
    }

    addUnsafeEnchantment(ench, level);
  }
Beispiel #17
0
 public static Map<Enchantment, Integer> convertEnchantLevelMap(JsonElement jsonElement) {
   JsonObject json = jsonElement.getAsJsonObject();
   Map<Enchantment, Integer> ret = new HashMap<Enchantment, Integer>();
   for (Entry<String, JsonElement> entry : json.entrySet()) {
     int id = Integer.valueOf(entry.getKey());
     Enchantment ench = Enchantment.getById(id);
     int lvl = entry.getValue().getAsInt();
     ret.put(ench, lvl);
   }
   return ret;
 }
Beispiel #18
0
 public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
   if (sender.hasPermission("bukkit.command.enchant")) {
     Player p = Bukkit.getPlayerExact(sender.getName());
     if (args.length == 0) {
       List<String> names = new ArrayList<String>();
       for (Enchantment enchant : Enchantment.values()) names.add(enchant.getName().toUpperCase());
       sender.sendMessage(
           ChatColor.GREEN
               + "Enchants: |"
               + ChatColor.RED
               + StringUtils.join(names, ChatColor.GREEN + "|  |" + ChatColor.RED)
               + ChatColor.GREEN
               + "|");
     } else {
       Enchantment enchant = Enchantment.getByName(args[0].toUpperCase());
       if (enchant == null) {
         for (Enchantment enchantment : Enchantment.values())
           if (enchantment.getName().equalsIgnoreCase(args[0])) enchant = enchantment;
         if (enchant == null) {
           sender.sendMessage(ChatColor.GREEN + "Enchant: " + args[0] + " - Not found");
           return true;
         }
       }
       int level = enchant.getMaxLevel();
       if (args.length > 1) {
         if (lib.isNumeric(args[1])) level = Integer.parseInt(args[1]);
       }
       if (p.getItemInHand() != null && p.getItemInHand().getType() != Material.AIR) {
         p.getItemInHand().addUnsafeEnchantment(enchant, level);
         p.sendMessage(
             ChatColor.GREEN
                 + "Item enchanted with "
                 + enchant.getName()
                 + " with level "
                 + level);
         updateEnchants(p.getItemInHand());
       } else p.sendMessage(ChatColor.GREEN + "Unable to enchant item");
     }
   } else sender.sendMessage(ChatColor.RED + "You do not have permission to use this command");
   return true;
 }
  @Override
  public void onEnable() {

    main = this;
    TITAN_POTION = new TitanPotion();
    setupConfigs();
    ;
    registerCommands();
    registerListeners();
    setupInSigns();

    // Glow Enchantment
    if (ml.moduleList.contains("ThunderAbilities")) {
      TSEnchantmentWrapper ench = new TSEnchantmentWrapper(69);
      try {
        try {
          Field f = Enchantment.class.getDeclaredField("acceptingNew");
          f.setAccessible(true);
          f.set(null, true);
        } catch (Exception e) {
          e.printStackTrace();
        }
        try {
          Enchantment.registerEnchantment(ench);
        } catch (IllegalArgumentException e) {
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    // Cooldowns
    if (ml.moduleList.contains("ThunderAbilities")) {
      Bukkit.getServer()
          .getScheduler()
          .scheduleSyncRepeatingTask(
              this,
              new Runnable() {
                @Override
                public void run() {
                  AbilityCooldown.handleCooldowns();
                }
              },
              1L,
              1L);
    }

    // Vault hooks
    setupPermissions();
    setupEconomy();
    getLogger().info("Successfully Enabled");
  }
Beispiel #20
0
  /**
   * Process results from Fishing.
   *
   * @param event The event to modify
   */
  public static void processResults(PlayerFishEvent event) {
    Player player = event.getPlayer();
    PlayerProfile PP = Users.getProfile(player);

    getFishingResults(player, event);
    Item theCatch = (Item) event.getCaught();

    if (theCatch.getItemStack().getType() != Material.RAW_FISH) {
      final int ENCHANTMENT_CHANCE = 10;
      boolean enchanted = false;
      ItemStack fishingResults = theCatch.getItemStack();

      player.sendMessage(mcLocale.getString("Fishing.ItemFound"));
      if (ItemChecks.isArmor(fishingResults) || ItemChecks.isTool(fishingResults)) {
        if (random.nextInt(100) <= ENCHANTMENT_CHANCE) {
          for (Enchantment newEnchant : Enchantment.values()) {
            if (newEnchant.canEnchantItem(fishingResults)) {
              Map<Enchantment, Integer> resultEnchantments = fishingResults.getEnchantments();

              for (Enchantment oldEnchant : resultEnchantments.keySet()) {
                if (oldEnchant.conflictsWith(newEnchant)) {
                  return;
                }
              }

              /* Actual chance to have an enchantment is related to your fishing skill */
              if (random.nextInt(15) < Fishing.getFishingLootTier(PP)) {
                enchanted = true;
                int randomEnchantLevel = random.nextInt(newEnchant.getMaxLevel()) + 1;

                if (randomEnchantLevel < newEnchant.getStartLevel()) {
                  randomEnchantLevel = newEnchant.getStartLevel();
                }

                fishingResults.addEnchantment(newEnchant, randomEnchantLevel);
              }
            }
          }
        }
      }

      if (enchanted) {
        player.sendMessage(mcLocale.getString("Fishing.MagicFound"));
      }
    }
  }
 @Override
 public ItemStack getItemStack(final String path) {
   final ItemStack stack =
       new ItemStack(
           Material.valueOf(getString(path + ".type", "AIR")),
           getInt(path + ".amount", 1),
           (short) getInt(path + ".damage", 0));
   final ConfigurationSection enchants = getConfigurationSection(path + ".enchant");
   if (enchants != null) {
     for (String enchant : enchants.getKeys(false)) {
       final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH));
       if (enchantment == null) {
         continue;
       }
       final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel());
       stack.addUnsafeEnchantment(enchantment, level);
     }
   }
   return stack;
   /*
    * ,
    * (byte)getInt(path + ".data", 0)
    */
 }
  public static CustomEnchantment valueOf(String s) {
    String[] name = s.split("-");
    int lvl = 1;
    if (name.length > 1 && !name[1].isEmpty()) {
      lvl = Integer.valueOf(name[1]);
    }

    Enchantment en = Enchantment.getByName(name[0]);
    CustomEnchantment ce = enchants.get(name[0]);

    if (en != null) {
      return new CustomEnchantment(en, lvl);
    } else if (ce != null) {
      return new CustomEnchantment(ce, lvl);
    } else {
      return null;
    }
  }
Beispiel #23
0
  public static SwagStack stringToSwagStack(String swagString) {
    String[] swagPieces = swagString.split(",");

    SwagStack swagStack = new SwagStack(Integer.valueOf(swagPieces[0]));

    if (!swagPieces[1].equals("0")) {
      if (swagPieces[1].contains("-")) {
        String[] dmg = swagPieces[1].split("-");
        swagStack.setMinDmg(Short.valueOf(dmg[0]));
        swagStack.setMaxDmg(Short.valueOf(dmg[1]));
      } else {
        swagStack.setMinDmg(Short.valueOf(swagPieces[1]));
        swagStack.setMaxDmg(Short.valueOf(swagPieces[1]));
      }
    }

    if (swagPieces[2].contains("-")) {
      String[] amnt = swagPieces[2].split("-");
      swagStack.setMinAmnt(Integer.valueOf(amnt[0]));
      swagStack.setMaxAmnt(Integer.valueOf(amnt[1]));
    } else {
      swagStack.setMinAmnt(Integer.valueOf(swagPieces[2]));
      swagStack.setMaxAmnt(Integer.valueOf(swagPieces[2]));
    }

    if (!swagPieces[3].equals("0")) {
      Map<Enchantment, Integer> enchantMap = new HashMap<Enchantment, Integer>();

      String[] enchants = swagPieces[3].split("&");

      for (String enchant : enchants) {
        String[] fullEnchant = enchant.split("#");
        enchantMap.put(
            Enchantment.getById(Integer.valueOf(fullEnchant[0])), Integer.valueOf(fullEnchant[1]));
      }

      swagStack.setEnchants(enchantMap);
    }

    return swagStack;
  }
Beispiel #24
0
 public static ArrayList<ItemStack> getFinalItems(String reward, Player player) {
   ArrayList<ItemStack> items = new ArrayList<ItemStack>();
   for (String l : Main.settings.getFile(GUI.Crate.get(player)).getStringList(reward + ".Items")) {
     ArrayList<String> lore = new ArrayList<String>();
     HashMap<Enchantment, Integer> enchs = new HashMap<Enchantment, Integer>();
     String name = "";
     int amount = 1;
     String m = "Stone";
     for (String i : l.split(", ")) {
       if (i.contains("Item:")) {
         i = i.replaceAll("Item:", "");
         m = i;
       }
       if (i.contains("Name:")) {
         i = i.replaceAll("Name:", "");
         i = i.replaceAll("_", " ");
         name = color(i);
       }
       if (i.contains("Amount:")) {
         i = i.replaceAll("Amount:", "");
         amount = Integer.parseInt(i);
       }
       if (i.contains("Lore:")) {
         i = i.replaceAll("Lore:", "");
         for (String L : i.split(",")) {
           L = color(L);
           lore.add(L);
         }
       }
       for (String enc : getEnchants()) {
         if (i.contains(enc + ":")) {
           String[] breakdown = i.split(":");
           int lvl = Integer.parseInt(breakdown[1]);
           enchs.put(Enchantment.getByName(enc), lvl);
         }
       }
     }
     items.add(makeItem(m, amount, name, lore, enchs));
   }
   return items;
 }
Beispiel #25
0
  /**
   * Required method for configuration serialization
   *
   * @param args map to deserialize
   * @return deserialized item stack
   * @see ConfigurationSerializable
   */
  public static ItemStack deserialize(Map<String, Object> args) {
    Material type = Material.getMaterial((String) args.get("type"));
    short damage = 0;
    int amount = 1;

    if (args.containsKey("damage")) {
      damage = ((Number) args.get("damage")).shortValue();
    }

    if (args.containsKey("amount")) {
      amount = ((Number) args.get("amount")).intValue();
    }

    ItemStack result = new ItemStack(type, amount, damage);

    if (args.containsKey("enchantments")) { // Backward compatiblity, @deprecated
      Object raw = args.get("enchantments");

      if (raw instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) raw;

        for (Map.Entry<?, ?> entry : map.entrySet()) {
          Enchantment enchantment = Enchantment.getByName(entry.getKey().toString());

          if ((enchantment != null) && (entry.getValue() instanceof Integer)) {
            result.addUnsafeEnchantment(enchantment, (Integer) entry.getValue());
          }
        }
      }
    } else if (args.containsKey(
        "meta")) { // We cannot and will not have meta when enchantments (pre-ItemMeta) exist
      Object raw = args.get("meta");
      if (raw instanceof ItemMeta) {
        result.setItemMeta((ItemMeta) raw);
      }
    }

    return result;
  }
Beispiel #26
0
  public boolean addEnchantmentToPlayerInventorySlot(
      String playerName, int slot, int enchantmentID, int level) {
    try {
      Player p = getPlayerExact(playerName);
      PlayerInventory inv = p.getInventory();
      ItemStack it;

      if (slot == 103) it = inv.getHelmet();
      else if (slot == 102) it = inv.getChestplate();
      else if (slot == 101) it = inv.getLeggings();
      else if (slot == 100) it = inv.getBoots();
      else it = inv.getItem(slot);

      it.addEnchantment(Enchantment.getById(enchantmentID), level);

      p.saveData();

      return true;
    } catch (NullPointerException e) {
      return false;
    }
  }
Beispiel #27
0
  public void spawnChest(Location l) {
    l.getBlock().setType(Material.CHEST);
    Chest c = (Chest) l.getBlock().getState();

    List<String> items = BGFiles.chestconf.getStringList("ITEMS");
    for (String item : items) {
      Random r = new Random();
      String[] oneitem = item.split(",");
      if (Boolean.parseBoolean(oneitem[3]) || r.nextBoolean()) {
        ItemStack i;

        Integer id = Integer.valueOf(Integer.parseInt(oneitem[0]));
        Integer minAmount = Integer.valueOf(Integer.parseInt(oneitem[1]));
        Integer maxAmount = Integer.valueOf(Integer.parseInt(oneitem[2]));

        Integer amount = r.nextInt((maxAmount + 1) - minAmount) + minAmount;

        i = new ItemStack(id.intValue(), amount.intValue());

        if (oneitem.length == 6) {
          i.addUnsafeEnchantment(
              Enchantment.getById(Integer.parseInt(oneitem[4])), Integer.parseInt(oneitem[5]));
        }

        c.getInventory().addItem(new ItemStack[] {i});
      }
    }

    c.update(true);
    DecimalFormat df = new DecimalFormat("##.#");
    BGChat.printInfoChat(
        "Chest spawned at X: "
            + df.format(l.getX())
            + " | Y: "
            + df.format(l.getY())
            + " | Z: "
            + df.format(l.getZ()));
  }
Beispiel #28
0
  public boolean setPlayerInventorySlotWithDataDamageAndEnchantments(
      String playerName,
      int slot,
      int blockID,
      final int data,
      int damage,
      int quantity,
      Object[] enchantments) {
    try {
      if (blockID == 0) {
        return clearPlayerInventorySlot(playerName, slot);
      }

      Player p = getPlayerExact(playerName);
      PlayerInventory inv = p.getInventory();
      ItemStack it = (new MaterialData(blockID, (byte) data)).toItemStack(quantity);
      it.setDurability((short) data);

      for (int i = 0; i < enchantments.length; i++) {
        JSONObject o = (JSONObject) enchantments[i];
        it.addEnchantment(
            Enchantment.getById(Integer.valueOf(o.get("enchantment").toString())),
            Integer.valueOf(o.get("level").toString()));
      }

      if (slot == 103) inv.setHelmet(it);
      else if (slot == 102) inv.setChestplate(it);
      else if (slot == 101) inv.setLeggings(it);
      else if (slot == 100) inv.setBoots(it);
      else inv.setItem(slot, it);

      p.saveData();

      return true;
    } catch (NullPointerException e) {
      return false;
    }
  }
  /**
   * Checks if the item can have this enchant and whether it is upgradable via this object
   *
   * @param stack the stack to check
   * @return true if it is enchantable and upgradable
   */
  public boolean canEnchant(ItemStack stack) {
    if (stack == null) return false;

    if (!enchantment.canEnchantItem(stack)) return false;

    // check each enchant on the item
    Map<Enchantment, Integer> current = stack.getEnchantments();
    for (Map.Entry<Enchantment, Integer> e : current.entrySet()) {

      // if it's the same enchantment
      if (e.getKey().equals(enchantment)) {
        // check if we can up a level
        return canEnchantAtLevel(e.getValue() + 1);
      }

      // check for conflicts with existing enchant
      if (e.getKey().conflictsWith(enchantment)) {
        return false;
      }
    }

    return true;
  }
  public static Inventory StringToInventory(String invString) {
    String[] serializedBlocks = invString.split(";");
    String invInfo = serializedBlocks[0];
    Inventory deserializedInventory =
        Bukkit.getServer().createInventory(null, Integer.valueOf(invInfo));

    for (int i = 1; i < serializedBlocks.length; i++) {
      String[] serializedBlock = serializedBlocks[i].split("#");
      int stackPosition = Integer.valueOf(serializedBlock[0]);

      if (stackPosition >= deserializedInventory.getSize()) {
        continue;
      }

      ItemStack is = null;
      Boolean createdItemStack = false;

      String[] serializedItemStack = serializedBlock[1].split(":");
      for (String itemInfo : serializedItemStack) {
        String[] itemAttribute = itemInfo.split("@");
        if (itemAttribute[0].equals("t")) {
          is = new ItemStack(Material.getMaterial(Integer.valueOf(itemAttribute[1])));
          createdItemStack = true;
        } else if (itemAttribute[0].equals("d") && createdItemStack) {
          is.setDurability(Short.valueOf(itemAttribute[1]));
        } else if (itemAttribute[0].equals("a") && createdItemStack) {
          is.setAmount(Integer.valueOf(itemAttribute[1]));
        } else if (itemAttribute[0].equals("e") && createdItemStack) {
          is.addEnchantment(
              Enchantment.getById(Integer.valueOf(itemAttribute[1])),
              Integer.valueOf(itemAttribute[2]));
        }
      }
      deserializedInventory.setItem(stackPosition, is);
    }
    return deserializedInventory;
  }