/* Inventory.java * allows for storing some number of items for the player */ import java.util.ArrayList; import java.util.Scanner; class Inventory { /* the actual list of items */ private ArrayList items; /* which item is equipped, if any */ private Item equippedArmor; private Item equippedWeapon; /* the max weight limit for the player to hold */ private int maxWeight; public Inventory(int maxWeight) { items = new ArrayList(); this.maxWeight = maxWeight; equippedWeapon = null; equippedArmor = null; } /* returns true on success, false when full */ public boolean add(Item item) { if ((item.getWeight() + totalWeight()) > maxWeight) { return false; } else { items.add(item); System.out.println("The " + item.getName() + " was added to your inventory."); return true; } } /* returns the total weight of all items stored */ public int totalWeight() { int total = 0; for (Item i : items) { total += i.getWeight(); } return total; } /* print all of the items in the list */ public void print() { System.out.println(String.format("%-25s %10s %10s %10s", "Item", "Weight", "Value", "Strength")); for (Item i : items) { System.out.print(i.toString()); if (i == equippedArmor) { System.out.println(" (equipped armor)"); } else if (i == equippedWeapon) { System.out.println(" (equipped weapon)"); } else { System.out.println(); } } } /* drop an item from the inventory */ public void drop() { System.out.println("Drop an item"); Item toDrop = pickItem(null); if (toDrop != null) { items.remove(toDrop); System.out.println("You dropped the " + toDrop.getName()); } } /* equip a weapon */ public void equipWeapon() { System.out.println("Equip a Weapon"); Item weapon = pickItem(ItemType.Weapon); if (weapon != null) { equippedWeapon = weapon; System.out.println("You equipped the " + equippedWeapon.getName()); } } /* equip a piece of armor */ public void equipArmor() { System.out.println("Equip Armor"); Item armor = pickItem(ItemType.Armor); if (armor != null) { equippedArmor = armor; System.out.println("You equipped the " + equippedArmor.getName()); } } /* a method which allows users to choose an item * this is private - only called by drop and equip */ private Item pickItem(ItemType type) { int options = 1; System.out.println(String.format(" %-25s %10s %10s %10s", "Item", "Weight", "Value", "Strength")); for (Item i : items) { if (type == null || i.getType() == type) { System.out.println(options + ". " + i); options++; } } if (options == 1) { System.out.println("No appropriate items!"); return null; } System.out.println(options + ". Cancel"); System.out.print(": "); Scanner in = new Scanner(System.in); int choice = in. nextInt() - 1; // go through and skip items until we reach this one int realIndex = 0; for (Item i : items) { if (type == null || i.getType() == type) { if (choice == 0) { break; } choice--; } realIndex++; } if (realIndex < 0 || realIndex >= items.size()) { return null; } else { return items.get(realIndex); } } }