Essentially it boils down to HashMaps and GUIDs. Each Entity is nothing more than a Globally Unique Identifier (GUID) which serves as the key in each HashMap. A HashMap exists for every ComponentType in your game. There are ways to make this more general purpose, but I'm going with the naivenaïve solution for simplicity of argument.
public class EntityEntityManager
{
HashMap<GUID,boolean> entities =new HashMap<GUID,boolean>();
public EntityEntityManager()
{
}
public GUID createcreateEntity()
{
GUID entity= new GUID();
entities.put(entity,false);
return entity;
}
public HashMap<GUID,boolean> getAll()
{
return entities;
}
public void markPurge(GUID entity)
{
entities.put(entity, true);
}
public void purgeReady()
{
//removes all entities that have a value of true,
//only called once all other purges have been called
for(GUID entity : entities)
{
if(entities.get(entity))
entities.remove(entity);
}
}
}
Lets say the object needs health, lets start with creating a Health component. During the initialization of your game, you'd create a HashMap to register Entities that have the HealthComponentHealth Component.
public class HealthHealthComponentRegistry
{
private HashMap<GUID,int> healths=new HashMap<GUID,int>();
public HealthHealthComponentRegistry(){}
public void set(GUID entity, int health)
{
healths.put(entity, health);
}
public int get(GUID entity)
{
return healths.get(entity);
}
public void remove(GUID entity)
{
healths.remove(entity);
}
public void add(GUID entity)
{
healths.put(entity, 100);
}
public void add(GUID entity, int health)
{
healths.put(entity, health);
}
public void purge(ArrayList<GUID> entities)
{
for(GUID entity : entities)
healths.remove(entity);
}
}
public void setup()
{
//spawn an entity, and add a Health component in one step
HealthHealthComponentRegistry.add(EntityEntityManager.CreatecreateEntity());
}
public class DeathSystem
{
EntityEntityManager entities;
HealthHealthComponentRegistry healths;
public DeathSystem(EntityEntityManager e, HealthHealthComponentRegistry h)
{
entities=e;
healths=h;
}
public void update()
{
for(GUID entity : health.keySet())
{
if(healths.get(entity)==0)
entities.markPurge(entity);
}
}
}
EntityEntityManager entities;
HealthHealthComponentRegistry healthComps;
DeathSystem deathSystem;
GUID player;
boolean run = true;
public void main(String args)
{
setup();
while(run)
{
update();
}
}
public void setup()
{
entities= new EntityEntityManager();
healthComps = new HealthHealthComponentRegistry();
deathSystem = new DeathSystem(entities, healthComps);
player=entities.create();
healthComps.add(player);
}
public void update()
{
handleInput();
//attackSystem.update();
//healSystem.update();
deathSystem.update();
//finally, call the function that calls purge on all the component registries to remove any destroyed objects
purgeAll();
if(entities.getAll().size()==0)
run=false;
}