Entity Component System

Pros

  • e

Cons

  • e

Example Explanation

[UML]

import java.util.*;

class Main {
  public static void main(String[] args) {
    Collection vase = new Collection();

    vase.add(new CeramicMaterial());
    vase.getDescription();
    System.out.println("---");
    vase.add(new Killable(10));
    vase.getDescription();

    Killable k = (Killable) vase.act("Killable");
    k.damage(3);
    vase.getDescription();

    System.out.println("---");
    vase.add(new Movable(3, 3));
    vase.getDescription();
    Movable c = (Movable) vase.act("Movable");
    c.moveUp();
    c.moveUp();
    vase.getDescription();

    //{CeramicMaterial}
    //---
    //{CeramicMaterial}, {Killable: 10/10}
    //damaged for 3
    //{CeramicMaterial}, {Killable: 7/10}
    //---
    //{CeramicMaterial}, {Killable: 7/10}, {Movable: 3, 3}
    //moves up
    //moves up
    //{CeramicMaterial}, {Killable: 7/10}, {Movable: 3, 5}

  }
}

abstract class Component{
  public String actionName;

  public Component(String actionName){
    this.actionName = actionName;
  }
  public String getDescription(){return "";}
}

class Collection
{
  List<Component> list;

  public Collection(){ list = new ArrayList<Component>();}

  public void add(Component c){ list.add(c); }

  public Component act(String actionName){
    for(Component c : list){
      if(c.actionName.equals(actionName)){
        return c;
      }
    }
    return null;
  }
  public void getDescription(){
    String description= "";
    for(Component c : list){
      description+=c.getDescription()+", ";
    }
    System.out.println(description.substring(0, description.length()-2));
  }
}

class CeramicMaterial extends Component{

  public CeramicMaterial(){
    super("CeramicMaterial");
  }

  public String getDescription(){ return "{CeramicMaterial}"; }
}

class Killable extends Component
{
  public int maxLife;
  public int currentLife;

  public Killable(int startingLife){
    super("Killable");
    this.maxLife = currentLife = startingLife;
  }

  public void damage(int dmg){
    currentLife -= dmg;
    System.out.println("damaged for "+dmg);
    if(currentLife <= 0){
      currentLife = 0;
      System.out.println("Entity killed");
    }
    if(currentLife > maxLife){
      currentLife = maxLife;
    }
  }
  public String getDescription(){ return "{Killable: "+currentLife+"/"+maxLife+"}"; }
}
class Movable extends Component
{
  public int x;
  public int y;

  public Movable(int x, int y){
    super("Movable");
    this.x = x; 
    this.y = y; 
  }

  public void moveUp(){ y++; System.out.println("moves up");}
  public void moveDown(){ y--; }
  public void moveLeft(){ x--; }
  public void moveRight(){ x++; }
  private void displayPos(){ System.out.println(x+", "+y); }
  public String getDescription(){ return "{Movable: "+x+", "+y+"}"; }
}

Extra Resources

results matching ""

    No results matching ""