0
\$\begingroup\$

I'm developing a little game that has a bunch of different items. I categorize the items in separate classes (consumables, armor, weapons) that all extend Item.class. Then I use one main Items class where I basically initialize all items and give them their values and spritefile. I also want to give some items different behavior. For example a potion that teleports you or a potion that makes you stronger. I don't want to make separate classes for every item with different behavior so that's why I'm now thinking of using an anonymous inner class. The class will only be instantiated once.

This is what my simple Items class looks like:

public class Items implements Iterable<Item>{
    private static ArrayList<Item> items = new ArrayList<Item>();

    @Override
    public Iterator<Item> iterator() {
        return items.iterator();
    }

    public static Item getItem(int id) {
        return items.get(id).clone();
    }

    public static void initialize() {
        addItem(new Armor(0, 1, "Leather Helmet", "Leather_Helmet.png", 30));
        addItem(new Consumable(1, 16, "Apple", "Apple.png", 30));
        addItem(new Consumable(2, 1, "Strength Potion", "Strength_Potion.png", 0) {
            @Override
            public void consume(Player player) {
                // Do potion stuff
            }
        });
    }

    public static void addItem(Item item) {
        items.add(item.getId(), item);
    }
}

The initialize() method is basically where I load in all the different items to the game. The third item is where I use an anonymous inner class. Is this the "right" way of handling things? Let me know how I could handle this differently.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ There are no right or wrong ways to do things in software development. Just solutions which work for you or don't work for you. Personally I would not like to hard-code all the items in a big initialize-method. I would try to move the item data to an external configuration file. But whatever works for you. \$\endgroup\$
    – Philipp
    Mar 30, 2020 at 9:14
  • \$\begingroup\$ @Philipp Yes I know, I probably should've phrased it differently. I wanted to know whether this method was maintainable and easy to extend. Or if there are any roadblocks that I can expect. Thanks for your comment, your suggestion sounds like a good idea. Although I'm not really sure how I would handle specific item behavior that way. \$\endgroup\$
    – TJRC
    Mar 31, 2020 at 0:39
  • 1
    \$\begingroup\$ if you want a code review you can post your Question on codereview.stackexchange.com \$\endgroup\$ Mar 31, 2020 at 5:07

0

You must log in to answer this question.

Browse other questions tagged .