Solved Check if there is enough space in inventory

Discussion in 'Plugin Development' started by Sydcul, Mar 15, 2013.

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

    Sydcul

    Hello,

    I am making an ATM system. It checks if you have enough balance on your account, and if you have, it should give you some coins (gold nuggets). However, I don't want to give the gold nuggets if you don't have enough free space in your inventory. I heard something about Player.getInventory().addItem() returning a hashmap of items that don't fit in. Actually I've never used Java before and I have no idea what a haspmap is, sort of an array or something?
    Anyway, how can I determine if there is enough space in the player's inventory?

    My current code:
    Code:
    package com.sydcul.malubas.atm;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.block.Sign;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.block.SignChangeEvent;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.economy.EconomyResponse;
     
    import java.util.HashMap;
    import java.util.logging.Logger;
     
    public class Main extends JavaPlugin implements Listener{
        private static final Logger log = Logger.getLogger("Minecraft");
        public static Economy econ = null;
       
        public void onEnable() {
            if (!setupEconomy() ) {
                log.severe(String.format("[%s] - Disabled due to no Vault dependency found!", getDescription().getName()));
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
            getServer().getPluginManager().registerEvents(this, this);
        }
       
        private boolean setupEconomy() {
            if (getServer().getPluginManager().getPlugin("Vault") == null) {
                return false;
            }
            RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
            if (rsp == null) {
                return false;
            }
            econ = rsp.getProvider();
            return econ != null;
        }
       
        @EventHandler
        public void onPlayerInteract(PlayerInteractEvent event) {
            Player player = event.getPlayer();
            if(event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                if(event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN_POST) {
                Sign s = (Sign) event.getClickedBlock().getState();
                if(s.getLine(0).equals(ChatColor.DARK_GREEN + "[MaluATM]")) {
                    //MaluATM sign detected
                    if(s.getLine(1).equals(ChatColor.BLUE + "Withdraw")) {
                        //Withdraw sign detected
                        int amount = Integer.parseInt(ChatColor.stripColor(s.getLine(2)));
                        EconomyResponse r = econ.withdrawPlayer(player.getName(), amount);
                        if(r.transactionSuccess()) {
                            //OVER HERE!!! BUKKIT FORUMS LOOK!!!
                            ItemStack coin = new ItemStack(Material.GOLD_NUGGET, amount);
                            player.getInventory().addItem(coin);
                            player.sendMessage(String.format(ChatColor.DARK_GREEN + "[MaluATM]" + ChatColor.GREEN + " %s has been taken from your account!", r.amount));
                        } else {
                            player.sendMessage(String.format(ChatColor.DARK_GREEN + "[MaluATM]" + ChatColor.RED + " Could not withdraw: %s", r.errorMessage));
                        }
                    }
                }
                }
            }
        }
       
        @EventHandler
        public void onPlayerInteract(SignChangeEvent event) {
            Player player = event.getPlayer();
            if(event.getBlock().getType() == Material.WALL_SIGN || event.getBlock().getType() == Material.SIGN_POST) {
                if(event.getLine(0).equals("[MaluATM]")) {
                    //Possible MaluATM sign
                    event.setLine(0, ChatColor.DARK_GREEN + "[MaluATM]");
                    if(event.getLine(1).equals("Withdraw")) {
                        //MaluATM withdraw sign created
                        event.setLine(1, ChatColor.BLUE + "Withdraw");
                        //Check for amount
                        try{
                              int amount = Integer.parseInt(event.getLine(2));
                              //Valid 3rd line (amount)
                              event.setLine(2, ChatColor.BLUE + Integer.toString(amount));
                            } catch (NumberFormatException e) {
                                //Invalid 3rd line (amound), using default (1)
                                event.setLine(2, ChatColor.BLUE + "1");
                            }
                        player.sendMessage(ChatColor.DARK_GREEN + "[MaluATM]" + ChatColor.GREEN + " Withdraw sign created!");
                    }
                    else {
                        //Invalid MaluATM sign
                        event.setLine(1, ChatColor.DARK_RED + "INVALID");
                        player.sendMessage(ChatColor.DARK_GREEN + "[MaluATM]" + ChatColor.RED + "Invalid sign!");
                    }
                }
            }
        }
    }
    
    Bump

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
  2. Offline

    raGan.

    Bumping after 50 minutes is not cool. You can iterate through player.getInventory().getContents() and find out how much space there is.
     
    TheTinySpider likes this.
  3. Offline

    Sydcul

    Hi,

    Sorry for the bump. However, I am not entirely sure how to look how much space there is. The best thing I can do with loops is let my server crash. Could you please give me an example or could someone explain how to use the hashmap returned by addItem? That looks to a less dirty way of doing this to me.
     
  4. Offline

    minoneer

  5. Offline

    raGan.

  6. Offline

    minoneer

  7. Offline

    raGan.

  8. Offline

    Sydcul

    Sorry. You love Java or you hate it. I hate it, but I still like Bukkit. I shall have a look at the javadoc (again).
     
  9. Offline

    Barinade

    int count = 0;
    for (ItemStack i : player.getInventory()) {
    if (i == null) {
    count++;
    }
    }
    //count = empty slots
     
    Sydcul likes this.
  10. Sydcul
    Apart from what Barinade you must also check the type of the item if its the type you want to add and see its available stack amount ( the type.getMaxStackSize() minus amount ).

    You can also just avoid doing this and drop the items if the player has full inventory, the addItem() automatically checks if there is room and adds as much as it can and it returns a Map object containing what couldn't fit, you can loop through that map and drop those items.
     
    angelofdev and Sydcul like this.
  11. Offline

    Barinade

    Explaining Digi

    HashMap<Integer, ItemStack> excess = player.getInventory().addItem(itemstack));
    for (Map.Entry<Integer, ItemStack> me : excess.entrySet()) {
    p.getWorld().dropItem(p.getLocation(), me.getValue());
    }

    This will give the players whatever he can hold, then drop the rest.

    And extending my previous post as Digi said,

    ItemStack itemToAdd = new ItemStack(Material.DIRT, 64);
    int freeSpace = 0;
    for (ItemStack i : player.getInventory()) {
    if (i == null) {
    freeSpace+=itemToAdd.getType().getMaxStackSize();
    } else if (i.getType() == itemToAdd.getType()) {
    freeSpace+=i.getType().getMaxStackSize() - i.getAmount();
    }
    }
    if (itemToAdd.getAmount() >= freeSpace) {
    //add items
    } else {
    //not enough space, tell the player and abort mission
    }
     
    angelofdev and Sydcul like this.
  12. Offline

    Sydcul

    Barinade, your first bit of code works like a charm. I might change to method 2 later because that's a bit more what I wanted. I'm currently working on the deposit signs, I'll post when I did that.
     
  13. Offline

    Barinade

    Add me on Skype if you need anything else, ira.sancti
    I'll be up for a few more hours, I can help you out when you need it.
    Currently updating my server to 1.5 though, got a lot of work on my hands and a lot of people waiting.
     
  14. Offline

    Sydcul

    Woo, solved it using Barinade's second code fragment!
    Thanks!
     
Thread Status:
Not open for further replies.

Share This Page