Predicate tips
In our example for creating a party system, we ended up having lots of code repetition. In our party creation command, we had the following code:
List<Argument<?>> arguments = new ArrayList<>();
// The "create" literal, with a requirement that a player must have a party
arguments.add(new LiteralArgument("create")
.withRequirement(sender -> !partyMembers.containsKey(((Player) sender).getUniqueId()))
);
arguments.add(new StringArgument("partyName"));
var arguments = mutableListOf<Argument<*>>()
// The "create" literal, with a requirement that a player must have a party
arguments.add(LiteralArgument("create")
.withRequirement { !partyMembers.containsKey((it as Player).uniqueId) }
)
arguments.add(StringArgument("partyName"))
And for our party teleportation command, we had the following code:
arguments = new ArrayList<>();
arguments.add(new LiteralArgument("tp")
.withRequirement(sender -> partyMembers.containsKey(((Player) sender).getUniqueId()))
);
arguments = mutableListOf<Argument<*>>()
arguments.add(LiteralArgument("tp")
.withRequirement { partyMembers.containsKey((it as Player).uniqueId) })
We can simplify this code by declaring the predicate:
Predicate<CommandSender> testIfPlayerHasParty = sender -> {
return partyMembers.containsKey(((Player) sender).getUniqueId());
};
val testIfPlayerHasParty = Predicate { sender: CommandSender ->
partyMembers.containsKey((sender as Player).uniqueId)
}
Now, we can use the predicate testIfPlayerHasParty
in our code for creating a party. Since we want to apply the "not" (!
) operator to this predicate, we can use .negate()
to invert the result of our predicate:
List<Argument<?>> args = new ArrayList<>();
args.add(new LiteralArgument("create").withRequirement(testIfPlayerHasParty.negate()));
args.add(new StringArgument("partyName"));
var args = listOf<Argument<*>>(
LiteralArgument("create").withRequirement(testIfPlayerHasParty.negate()),
StringArgument("partyName")
)
And we can use it again for our code for teleporting to party members:
args = new ArrayList<>();
args.add(new LiteralArgument("tp").withRequirement(testIfPlayerHasParty));
args = listOf<Argument<*>>(LiteralArgument("tp").withRequirement(testIfPlayerHasParty))