How to go about giving players random items?

Discussion in 'Plugin Development' started by hankered, Jun 7, 2014.

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

    hankered

    Hey I need to give players random items and a random amount when they die, best way to do this?
     
  2. Offline

    Compressions

    hankered
    Code:
    Material material = Material.values()[new Random().nextInt(Material.values().length)];
    int amount = new Random().nextInt(63)+1;
    ItemStack item = new ItemStack(material, amount);
     
  3. Offline

    hankered

    Compressions
    Thanks :)
    Should I use a config for specific items that should be random
     
  4. Offline

    Compressions

    hankered Well, that gets a random material from a group of every material and a random amount between 1 and 64.
     
  5. Offline

    NathanWolf

    If suggest you make a config-driven set of the items you want to pick from instead of doing it on ALL items.
     
  6. Offline

    Compressions

    Yeah, I mean it's your choice.
     
  7. hankered
    In addition to Compressions 's suggestion, you can also do something like this:

    Code:java
    1. public class RandomItem {
    2.  
    3. /**
    4.   * Gets a random item based on the size of an ItemStack array that holds all the items
    5.   *
    6.   * @param itemstack : The array that holds all the items
    7.   * @return A random item from the array
    8.   */
    9. public ItemStack getRandomItem(ItemStack[] itemstack){
    10. int random = new Random().nextInt(itemstack.length);
    11.  
    12. return itemstack[random];
    13. }
    14.  
    15. /**
    16.   * Drops a random item at the players location
    17.   *
    18.   * @param p : The player
    19.   * @param itemstack : The array containing a list of possible items that can be dropped
    20.   */
    21. public void dropRandomItem(Player p, ItemStack...itemstack){
    22. Location loc = p.getLocation();
    23. ItemStack item = getRandomItem(itemstack);
    24.  
    25. loc.getWorld().dropItem(loc, item);
    26. }
    27. }
     
  8. Offline

    hankered

    Alright, I'm probably going to make a list somehow in a config and choose from there.
     
    NathanWolf likes this.
Thread Status:
Not open for further replies.

Share This Page