Created
October 18, 2021 07:03
-
-
Save Moulberry/d04bc326e5e2c5a189c4a894f96383e2 to your computer and use it in GitHub Desktop.
Traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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