Skip to content

Instantly share code, notes, and snippets.

@kravchik
Created September 27, 2016 10:10
Show Gist options
  • Save kravchik/b1ccaca2c4c02951b1456dfc38942eae to your computer and use it in GitHub Desktop.
Save kravchik/b1ccaca2c4c02951b1456dfc38942eae to your computer and use it in GitHub Desktop.
public class FloatValue {
public boolean dirty = true;
public float baseValue; //before any buffs
public float value; //with all buffs
transient private YSet<FloatAffector> affectors = hs();
public void recalc() {
float mul = affectors.reduce(0f, (cur, affector) -> cur + affector.mul);
float add = affectors.reduce(0f, (cur, affector) -> cur + affector.add);
value = baseValue * mul + add;
dirty = false;
}
public void addAffect(FloatAffector af) {
if (affectors.contains(af)) BadException.die("already contains " + af);
affectors.add(af);
dirty = true;
}
public void removeAffect(FloatAffector af) {
if (!affectors.contains(af)) BadException.die("trying to remove, but not contained " + af);
affectors.remove(af);
dirty = true;
}
public static class FloatAffector {
public float mul;
public float add;
public YList<String> valuePath;
public FloatAffector(float mul, float add) {
this.mul = mul;
this.add = add;
}
public void addTo(Object o) {
FloatValue.<FloatValue>get(o, valuePath).addAffect(this);
}
public void removeFrom(Object o) {
FloatValue.<FloatValue>get(o, valuePath).removeAffect(this);
}
}
public static <T> T get(Object target, List<String> path) {
Object curObj = target;
for (String fieldName : path) curObj = Reflector.get(curObj, fieldName);
return (T) curObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment