Skip to content

Instantly share code, notes, and snippets.

@TechnicianLP
Created July 23, 2017 17:00
Show Gist options
  • Save TechnicianLP/3838d477c8fe51c37e599e92c7495429 to your computer and use it in GitHub Desktop.
Save TechnicianLP/3838d477c8fe51c37e599e92c7495429 to your computer and use it in GitHub Desktop.
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.util.ResourceLocation;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
public abstract class AbstractCriterionTrigger<I extends ICriterionInstance> implements ICriterionTrigger<I> {
private final ResourceLocation ID;
private final Map<PlayerAdvancements, Set<ICriterionTrigger.Listener<I>>> listeners = Maps.newHashMap();
public AbstractCriterionTrigger(ResourceLocation id) {
this.ID = id;
}
@Override
public ResourceLocation getId() {
return ID;
}
@Override
public void addListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<I> listener) {
this.listeners.computeIfAbsent(playerAdvancementsIn, k -> Sets.newHashSet()).add(listener);
}
@Override
public void removeListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<I> listener) {
Set<ICriterionTrigger.Listener<I>> set = this.listeners.get(playerAdvancementsIn);
if (set != null) {
set.remove(listener);
if (set.isEmpty()) {
this.listeners.remove(playerAdvancementsIn);
}
}
}
@Override
public void removeAllListeners(PlayerAdvancements playerAdvancementsIn) {
this.listeners.remove(playerAdvancementsIn);
}
/**
* public void trigger(EntityPlayerMP player) {trigger(player.getAdvancements(), instance -> instance.test(player));}
* (ICreterionInstance class needs a respective test(EntityPlayerMP) method in this case)
*/
protected void trigger(PlayerAdvancements player, Predicate<I> predicate) {
List<ICriterionTrigger.Listener<I>> list = Lists.newArrayList();
listeners.getOrDefault(player, ImmutableSet.of()).forEach((listener) -> {
if (predicate.test(listener.getCriterionInstance())) {
list.add(listener);
}
});
list.forEach(i -> i.grantCriterion(player));
}
protected void triggerAll(Predicate<I> predicate) {
listeners.forEach((key, value) -> {
List<ICriterionTrigger.Listener<I>> list = Lists.newArrayList();
for (ICriterionTrigger.Listener<I> listener : value) {
if (predicate.test(listener.getCriterionInstance())) {
list.add(listener);
}
}
list.forEach(i -> i.grantCriterion(key));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment