This site requires JavaScript, please enable it in your browser!
Greenfoot back
bleeblob43
bleeblob43 wrote ...

2016/11/14

Trade Help

bleeblob43 bleeblob43

2016/11/14

#
I am making a game and would like to implement trading. What is the best way to do this? Should I have an inventory class with integers for each number of items Or should each item be its own object Or what other way can it be done
danpost danpost

2016/11/14

#
bleeblob43 wrote...
Should I have an inventory class with integers for each number of items
An inventory is just a list of items. Java already has an extensive supply of classes that create all kinds of lists. However, you might want some extra methods that are not readily available (like getting the number of objects of a specific type in the list; or, getting one or all objects of a specific type from the list). It would make sense then to create a subclass of the ArrayList class to add those methods that deal with Class types. Something like this:
import java.util.List;
import java.util.ArrayList;

public class InventoryList extends ArrayList
{
    // method to return a list of all objects of a specific type (or all item in the list if 'null' is given for the class type)
    public<T> List<T> getAll(Class clss)
    {
        List<T> objs = new ArrayList<T>();
        for (int i=0; i<size(); i++) if (clss == null || clss == get(i).getClass()) objs.add((T)get(i));
        return objs;
    }

    // method to return one object of a specific type from the list ('null' returned if none are found in the list)
    // (the first item in the list is returned if 'null' is given for the class type)
    public <T>T get(Class clss)
    {
        if (getAll(clss).isEmpty()) return null;
        return (T)getAll(clss).get(0);
    }
    
    // method to return the number of objects of a specific type (or the size of the inventory if 'null' is given for the class type)
    public int numberOfType(Class clss)
    {
        return getAll(clss).size();
    }
}
Now, you can just create an InventoryList (List) object:
public InventoryList inv = new InventoryList();
for each actor, chest or trading post that needs one. As far as what I quoted above, just put the objects themselves in the list. No sense in converting back and forth using integer values. Objects from the same class can vary from one another and that would then need to be tracked. If you did, it might take extensive coding and the class would not be portable (used, as is, in other projects).
You need to login to post a reply.