Skip to content

Instantly share code, notes, and snippets.

@Moulberry
Created October 18, 2021 07:03
Show Gist options
  • Save Moulberry/d04bc326e5e2c5a189c4a894f96383e2 to your computer and use it in GitHub Desktop.
Save Moulberry/d04bc326e5e2c5a189c4a894f96383e2 to your computer and use it in GitHub Desktop.
Traits
public void one() {
EntityBuilder builder = Entity.builder();
builder.makeTrait(EntityTraits.HEALTH, 20); // Stores data
builder.makeTrait(EntityTraits.ENTITY_TYPE, EntityType.ZOMBIE); // Implements create, destroy, meta functions
Entity entity = builder.build();
// Damage the entity with a method specific to EntityTraits.HEALTH
EntityTraits.HEALTH.damage(entity, 5);
}
// EntityBuilder implementation
public class EntityBuilder {
private static final Object PRESENT = new Object();
private Object[] traitData = new Object[64];
public void makeTrait(EntityTrait<Void> trait) {
traitData[trait.id()] = PRESENT; // Very weird? Not sure if we should use a separate bitset or something
}
public <T> void makeTrait(EntityTrait<T> trait, T object) {
traitData[trait.id()] = object;
}
public <T> void ifTraitPresent(EntityTrait<T> trait, UnaryOperator<T> operator) {
T data = traitData[trait.id()];
if(data != null) {
traitData[trait.id()] = operator.apply(data);
}
}
}
// Health implementation
public class EntityTraits {
public static final EntityTrait<Integer> HEALTH = new EntityTrait<Integer>() {
public boolean damage(Entity entity, int damage) {
entity.ifTraitPresent(this, (health) -> health - damage);
}
public int id() {
return 0; // Should probably be handled by some registry?
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment