User Tools

Site Tools


zh_cn:tutorial:command_redirects

This is an old revision of the document!


命令重定向

重定向是 Brigadier 的一种别称和子命令的形式。redirect 方法接收一个命令节点和一个可选的环境修饰。命令节点可以是在派发器注册后的一个特定的节点,或者就是根节点。

别称

在原版的 Minecraft 中,/tell/w 会重定向到 /msg,可以在 MessageCommand 中看到。

这个例子显示了如何将 /foo2 重定向到 /foo

  1. public class ExampleMod implements ModInitializer {
  2. @Override
  3. public void onInitialize() {
  4. CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
  5. final LiteralCommandNode<ServerCommandSource> fooNode = dispatcher.register(literal("foo")
  6. .executes(context -> {
  7. // 对于 1.19 以下的版本,请将“Text.literal”替换为“new LiteralText”。
  8. context.getSource().sendMessage(Text.literal("调用了 /foo,不带参数"));
  9.  
  10. return 1;
  11. }));
  12. dispatcher.register(literal("foo2").redirect(fooNode));
  13. });
  14. }
  15. }

redirect 会告诉 birgadier,在另一个命令节点之后解析命令。

Chainable Commands

Commands such as /execute as @e[type=player] in the_end run tp ~ ~ ~ are also possible because of redirects.

Let's first consider the vanilla /execute command. There is a node after the literal("execute"). After dispatching subcommands, the dispatcher is redirected to that node (with some modifiers), making you possible to, after completing sub-command arguments, type whatever can be typed directly after /execute. In the sub-command run, the dispatcher is redirected to the root node (dispatcher.getRoot()), allowing you to type another complete command after the word “run”.

Below is an example of a chainable command:

  1. LiteralCommandNode<ServerCommandSource> rootNode = dispatcher.register(literal("fabric_test"));
  2. LiteralCommandNode<ServerCommandSource> root1 = dispatcher.register(literal("fabric_test")
  3. // You can register under the same literal more than once, it will just register new parts
  4. // of the branch as shown below if you register a duplicate branch an error will popup in
  5. // console warning of conflicting commands but one will still work.
  6. .then(literal("extra")
  7. .then(literal("long")
  8. .redirect(rootNode, this::lengthen)) // Return to root for chaining
  9. .then(literal("short")
  10. .redirect(rootNode, this::shorten))) // Return to root for chaining
  11. .then(literal("command")
  12. .executes(ctx -> {
  13. ctx.getSource().sendFeedback(Text.literal("Chainable Command"), false);
  14. return Command.SINGLE_SUCCESS;
  15. })));

The redirect can also modify the CommandSource by use of a “redirect modifier” (SingleRedirectModifier<S>), which is used as a lambda.

  1. .redirect(rootNode, context -> {
  2. // When redirecting, modify the looking direction of the command source.
  3. return ((ServerCommandSource) context.getSource()).withLookingAt(Vec3ArgumentType.getVec3(context, "pos"));
  4. })
zh_cn/tutorial/command_redirects.1681986614.txt.gz · Last modified: 2023/04/20 10:30 by solidblock