Java is an object-oriented language, so the usual approach to this would be a class hierarchy.
Create a class for each of the entity types mentioned in the question. Then represent those entities at runtime with instances of those classes.
Objects which have the same functionality but have different numbers should be instances of the same class which differ by their data:
HealthPotion smallHealthPotion = new HealthPotion(20);
HealthPotion mediumHealthPotion = new HealthPotion(50);
HealthPotion largeHealthPotion = new HealthPotion(250);
Objects which share most of their logic but also have some different game mechanics should be represented by classes inheriting from the same base class. For example, healing potions and damaging potions might inherit from the same base class Potion
. Potion
would implement the functionality and carry the data you have in all potions, while the classes HealthPotion
and DamagePotion
would have the logic and data specific to the more specialized potion types.
Potion smallHealthPotion = new HealthPotion(20);
Potion smallPoisonBottle = new DamagePotion(20);
The nice thing about class inheritance is that you can have code like this:
Potion potion = GetPotionFromInventorySlot(31);
potion.drink(selectedPlayer);
The method drink(PlayerCharacter drinker)
would be declared in Potion
but implemented in both HealthPotion
and DamagePotion
in different ways (one doing good stuff to the drinker, the other bad stuff). Depending on what type of potion is in inventory slot 31, the Java runtime environment would either run the method HealthPotion.drink
or DamagePotion.drink
. No if(typeof(potion) == ...)
required. This is called polymorphism.
Caveats:
- The above code samples are grossly oversimplified. Real-world code would pass a lot more data to those constructors than just a single number, or would use a creational pattern like a Factory or Builder.
- If you want to take this project serious, then you might also want to consider reading item names and stats from a configuration file instead of hardcoding them.
- There is no "right" or "wrong" way to design your games software architecture. Just ways which work for you or ways which don't work for you.