Items in Java
"The Java Roguelike Development Guide"
Issue Two - Items in Java
andrew.d.joiner@googlemail.com
One of the core features of any roguelike game are Items. Things you can pickup, use, drink, equip, drop, etc... In Java, using the OO inheritance model, we can create elegant, efficient and very easy to use Item classes. Start by deciding the types of Item that will be available in the game. More can be added easily later on. For this example, the following Item types will be used:
- Food
- Potion
- Weapon
- Armour
- Junk
Each of these items will have shared properties, and unique properties. The key is to determine which properties are common for all items, and which are unique to just a single item. To keep this simple, we will take the following properties to be common for every item type;
- Name (String)
- Colour (int)
- Symbol (char)
- Weight (int)
- Value (int)
The root class for all of these items will be called Item, and contains the common properties for every item type, as listed above.
public class Item { // class data public String name; public int color; public char symbol; public int weight; public int value; // constructor() public Item() { } }
Using inheritence, we can create sub-classes of Item, for each of our item types;
public class Food extends Item { } public class Potion extends Item { } public class Weapon extends Item { } public class Armour extends Item { } public class Junk extends Item { }
Each of these classes contain their own data, relevant for just that item type. We can improve the model further by realising that Food and Potion are similar item types. An intermediate class called Consumable could be used, to represent the common features of both food and potion classes (if any exist)
public class Consumable extends Item { } public class Food extends Consumable { } public class Potion extends Consumable { }
An improvement to the Item class at this point can be made. A series of macro methods to determine what Item type we are dealing with;
// item methods public boolean isConsumable() { return this instanceof Comsumable; } public boolean isFood() { return this instanceof Food; } public boolean isPotion() { return this instanceof Potion; } public boolean isWeapon() { return this instanceof Weapon; } public boolean isArmour() { return this instanceof Armour; } public boolean isJunk() { return this instanceof Junk; }