I've been trying to implement a component-based entity system for my game items. I'm not sure if I'm doing it correctly and if there's a better way. I'll post some code, can you guys help me improve my current design?
ItemCreator Class:
import java.io.IOException;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.XmlReader;
import com.badlogic.gdx.utils.XmlReader.Element;
public class ItemCreator {
XmlReader reader;
Element root;
int i = 0;
ArrayList<Item> items;
public ItemCreator(){
items = new ArrayList<Item>();
reader = new XmlReader();
try {
root = reader.parse(Gdx.files.internal("items/Items.xml"));
} catch (IOException e) {
e.printStackTrace();
}
Array<Element> items = root.getChildrenByName("item");
//Loop through each "Item"
for (Element child : items){
int ID = Integer.parseInt(child.getAttribute("id"));
String name = child.getAttribute("name");
//Loop through each Item's components
int numberOfChildren = child.getChildCount();
Array<Element> components = new Array<Element>();
for(int i = 0; i < numberOfChildren; i++){
components.add(child.getChild(i));
}
createItem(components,ID,name);
}
}
public void createItem(Array<Element> components, int ID, String name){
Item item = new Item();
item.setID(ID);
item.setName(name);
//add components
for(Element component : components){
if(component.getName().equals("description")){item.addComponent(new ItemDescription(component.getAttribute("text")));}
if(component.getName().equals("wieldable")){item.addComponent(new ItemWieldable(component.getAttribute("slot")));}
if(component.getName().equals("weapon")){item.addComponent(new ItemWeapon(component.getAttribute("damage")));}
}
//Add item to itemList
items.add(item.ID,item);
}
}
Item Class:
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
public class Item {
ArrayList<ItemComponent> components;
String name;
int ID;
public Item() {
components = new ArrayList<ItemComponent>();
}
public void addComponent(ItemComponent component){
components.add(component);
}
public void printItem(){
Gdx.app.log("ID",String.valueOf(ID));
Gdx.app.log("Name", name);
for(ItemComponent c : components){
Gdx.app.log("Component",c.toString());
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
}
Thanks for any suggestions.