Skip to content

Commit

Permalink
Merge pull request #11 from Polymeta/feature/player-compare-predicate
Browse files Browse the repository at this point in the history
introduce new player compare predicate
  • Loading branch information
Wesley1808 authored Jun 30, 2024
2 parents 9b7182a + e9369ec commit bb61581
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package me.wesley1808.advancedchat.impl.predicates;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import eu.pb4.predicate.api.MinecraftPredicate;
import eu.pb4.predicate.api.PredicateContext;
import eu.pb4.predicate.api.PredicateResult;
import eu.pb4.predicate.impl.predicates.GenericObject;
import me.wesley1808.advancedchat.api.AbstractChatPredicate;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;

import java.util.Objects;

public class PlayerPredicateCompare extends AbstractChatPredicate {
public static final ResourceLocation ID = ResourceLocation.tryBuild("advancedchat", "compare");
public static final MapCodec<PlayerPredicateCompare> CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group(
GenericObject.CODEC.fieldOf("compare_predicate").forGetter((x) -> x.predicateObj)
).apply(instance, PlayerPredicateCompare::new));

private final Object predicateObj;
private final MinecraftPredicate predicate;

public PlayerPredicateCompare(Object predicateObj) {
super(ID, CODEC);

this.predicateObj = predicateObj;
this.predicate = GenericObject.toPredicate(predicateObj);
}

@Override
public PredicateResult<?> test(ServerPlayer sender, ServerPlayer target) {
var val1 = this.predicate.test(PredicateContext.of(sender));
var val2 = this.predicate.test(PredicateContext.of(target));

if (val1.value() instanceof Component text && val2.value() instanceof String string) {
return PredicateResult.ofBoolean(text.getString().equals(string));
} else if (val2.value() instanceof Component text && val1.value() instanceof String string) {
return PredicateResult.ofBoolean(text.getString().equals(string));
} else {
return PredicateResult.ofBoolean(val1.success() == val2.success() && Objects.equals(val1.value(), val2.value()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ public class Predicates {
public static void register() {
PredicateRegistry.register(CustomDistancePredicate.ID, CustomDistancePredicate.CODEC);
PredicateRegistry.register(ChannelPredicate.ID, ChannelPredicate.CODEC);
PredicateRegistry.register(PlayerPredicateCompare.ID, PlayerPredicateCompare.CODEC);
}
}

0 comments on commit bb61581

Please sign in to comment.