random enchantment on an item

Discussion in 'Plugin Development' started by 15987632, Jun 17, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    15987632

    How would i get a random enchantment on an item. How would i get all the possible enchantments for an item and apply one of them and after that get all the different levels of that enchantment and apply that one
     
  2. Offline

    cs475x

    Code:java
    1. public ItemStack randomEnchantment(ItemStack item) {
    2. // Store all possible enchantments for the item
    3. List<Enchantment> possible = new ArrayList<Enchantment>();
    4.  
    5. // Loop through all enchantemnts
    6. for (Enchantment ench : Enchantment.values()) {
    7. // Check if the enchantment can be applied to the item, save it if it can
    8. if (ench.canEnchantItem(item)) {
    9. possible.add(ench);
    10. }
    11. }
    12.  
    13. // If we have at least one possible enchantment
    14. if (possible.size() >= 1) {
    15. // Randomize the enchantments
    16. Collections.shuffle(possible);
    17. // Get the first enchantment in the shuffled list
    18. Enchantment chosen = possible.get(0);
    19. // Apply the enchantment with a random level between 1 and the max level
    20. item.addEnchantment(chosen, 1 + (int) (Math.random() * ((chosen.getMaxLevel() - 1) + 1)));
    21. }
    22.  
    23. // Return the item even if it doesn't have any enchantments
    24. return item;
    25. }
     
Thread Status:
Not open for further replies.

Share This Page