Payment/Inventory item removal method for you to use.

Discussion in 'Resources' started by MakerofRobots, Jul 31, 2013.

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

    MakerofRobots

    I see this problem crop up all the time on the forum, so here is a nice little method that:

    A. Checks that the inventory can supply the amount
    B. Returns true/false based on A.
    C. Removes the item(s)

    Code:java
    1. public boolean payment(int amount, Material payment,Inventory inv) {
    2. if (!inv.contains(payment))return false; else {
    3. for (ItemStack i : inv.getContents()) {
    4. if (i.getType().equals(payment)) {
    5. if (i.getAmount()==amount) {
    6. inv.remove(i);
    7. return true;
    8. } else if (i.getAmount()>amount) {
    9. ItemStack replacement = new ItemStack(i.getType(),i.getAmount()-amount);
    10. inv.setItem(inv.first(i), replacement);
    11. return true;
    12. }
    13. }
    14. }
    15. }
    16. return false;
    17. }


    Heres it in action (edit):
    Code:java
    1.  
    2. //This is assumed to be somewhere useful.
    3. if (payment(3,Material.DIAMOND,player.getInventory()) {
    4. player.getInventory().addItem(new ItemStack(Material.DIAMOND_PICKAXE))
    5. }
    6.  


    Enjoy!
     
    microgeek likes this.
  2. Offline

    Necrodoom

    moved to resources forum.
     
  3. Offline

    seang96


    I am getting an error "Cannot resolve symbol "Class Inventory", how would I go about fixing this?
     
  4. Offline

    MakerofRobots

    Show me code, stack trace, etc if you want any help from me.
     
  5. Offline

    macguy8

    This wouldn't work for checking if they can pay and taking the item if you take more than the max stack size of the item. You could just use .getInventory().removeItem(), which return what items were not removed. You could then return if the size of this isn't zero (therefor all items were removed)
     
  6. Offline

    seang96

    I am using something different from your code but I got the problem using yours too. I just get the error on the first line on Inventory. There is no stack trace since its a error that prevents compiling.



    Code:java
    1. private boolean inventoryContains(Inventory inventory, ItemStack item) {
    2. int count = 0;
    3. ItemStack[] items = inventory.getContents();
    4. for (int i = 0; i < items.length; i++) {
    5. if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) {
    6. count += items[i].getAmount();
    7. }
    8. if (count >= item.getAmount()) {
    9. return true;
    10. }
    11. }
    12. return false;
    13. }[/i][/i][/i][/i]
     
Thread Status:
Not open for further replies.

Share This Page