changed removeItem(). no longer throws NPE's

This commit is contained in:
Blackvein 2012-10-10 12:19:05 -07:00
parent ece0a2b69b
commit f65831d6fd
2 changed files with 41 additions and 28 deletions

View File

@ -62,7 +62,7 @@ public class NpcListener implements Listener{
for(int i : q.itemIds){
if (q.removeItems.get(i) == true)
Quests.removeItem(player, new ItemStack(Material.getMaterial(i), q.itemAmounts.get(q.itemIds.indexOf(i))));
Quests.removeItem(player.getInventory(), Material.getMaterial(i), q.itemAmounts.get(q.itemIds.indexOf(i)));
}
player.sendMessage(ChatColor.GREEN + "Quest accepted: " + q.name);

View File

@ -579,7 +579,7 @@ public class Quests extends JavaPlugin {
for(int i : quest.itemIds){
if (quest.removeItems.get(quest.itemIds.indexOf(i)) == true)
removeItem(((Player) sender), new ItemStack(Material.getMaterial(i), quest.itemAmounts.get(quest.itemIds.indexOf(i))));
removeItem(((Player) sender).getInventory(), Material.getMaterial(i), quest.itemAmounts.get(quest.itemIds.indexOf(i)));
}
sender.sendMessage(ChatColor.GREEN + "Quest accepted: " + quest.name);
@ -2682,30 +2682,43 @@ public class Quests extends JavaPlugin {
}
public static void removeItem(Player p, ItemStack i){
public static boolean removeItem(Inventory inventory, Material type, int amount) {
PlayerInventory inv = p.getInventory();
int amountLeft = i.getAmount();
HashMap<Integer, ? extends ItemStack> allItems = inventory.all(type);
HashMap<Integer, Integer> removeFrom = new HashMap<Integer, Integer>();
int foundAmount = 0;
for (Map.Entry<Integer, ? extends ItemStack> item : allItems.entrySet()) {
for(ItemStack stack : inv.getContents()){
if(stack.getType().equals(i.getType())){
if(stack.getAmount() <= i.getAmount()){
amountLeft -= stack.getAmount();
i.setType(null);
if (item.getValue().getAmount() >= amount - foundAmount) {
removeFrom.put(item.getKey(), amount - foundAmount);
foundAmount = amount;
} else {
i.setAmount(stack.getAmount() - amountLeft);
amountLeft = 0;
foundAmount += item.getValue().getAmount();
removeFrom.put(item.getKey(), item.getValue().getAmount());
}
if(amountLeft == 0)
if (foundAmount >= amount) {
break;
}
}
if (foundAmount == amount) {
for (Map.Entry<Integer, Integer> toRemove : removeFrom.entrySet()) {
ItemStack item = inventory.getItem(toRemove.getKey());
if (item.getAmount() - toRemove.getValue() <= 0) {
inventory.clear(toRemove.getKey());
} else {
item.setAmount(item.getAmount() - toRemove.getValue());
inventory.setItem(toRemove.getKey(), item);
}
}
return true;
}
return false;
}
}