Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package game.items;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * User: geekocioso
- * Date: 4/17/13
- * Time: 5:46 AM
- */
- public class Inventory {
- private int size;
- /**
- * We'll use this data structure to store the items and how many of them we have
- */
- private List<String> contents = new ArrayList<String>();
- /**
- * Constructor. Will need to specify the size of inventory to create it.
- * @param size Slots in the inventory
- */
- public Inventory(int size) {
- this.size = size;
- }
- /**
- * Checks how many of an item we have
- * @param name Item name
- * @return true if in inventory, false if not
- */
- public Boolean checkForItem(String name) {
- return contents.contains(name);
- }
- /**
- * Adds an item to the inventory
- * @param name Item to add
- * @return true if added successfully, false if not (cannot add when inventor is full)
- */
- public Boolean addItem(String name) {
- // do not add if inventory is null
- if (isFull()) return false;
- try {
- contents.add(name);
- System.out.println("Item " + name + " added to your inventory!");
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * Removes an item from inventory
- * @param name Item to remove
- * @return true if removed, false if not
- */
- public Boolean removeItem(String name) {
- if (contents.contains(name)) {
- try {
- contents.remove(name);
- } catch (Exception e) {
- return false;
- }
- } else {
- return false;
- }
- return true;
- }
- /**
- * Checks if inventory is full
- * @return true if full, false if not full
- */
- public Boolean isFull() {
- return contents.size() >= size;
- }
- /**
- * Queries for the number of empty slots left
- * @return number of empty slots in inventory
- */
- public Integer numberOfFreeSlots() {
- return size - contents.size();
- }
- /**
- * Writes a list of your inventory to the console
- */
- public void listContents() {
- if (contents.size() == 0) {
- System.out.println("Empty.");
- } else {
- System.out.println("Here's what you have:");
- for (String s: contents) {
- System.out.println("* " + s);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement