zh_cn:tutorial:commands
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
zh_cn:tutorial:commands [2021/09/17 05:00] – ↷ Links adapted because of a move operation 54.161.41.102 | zh_cn:tutorial:commands [2023/11/19 02:02] (current) – [可以注册客户端命令吗?] solidblock | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | |||
条款:本文中的代码适用于“Creative Commons Zero v1.0 Universial”条款,允许您将文中的代码示例用于自己的模组中。 | 条款:本文中的代码适用于“Creative Commons Zero v1.0 Universial”条款,允许您将文中的代码示例用于自己的模组中。 | ||
- | 注: 本文翻译自英文版[[tutorial: | + | 注: 本文翻译自英文版[[tutorial: |
====== 创建命令 ====== | ====== 创建命令 ====== | ||
- | 创建命令允许模组开发者添加可以使用命令实现的功能。本教程将会教你如何注册命令,以及Brigadier的基本命令结构。 | + | 创建命令允许模组开发者添加可以使用命令实现的功能。本教程将会教你如何注册命令,以及 Brigadier 的基本命令结构。 |
- | 注意:本文的所有代码都是用于1.14.4的。部分yarn映射可能改变了,不过代码应该可用。 | + | ===== Brigadier |
- | ===== Brigadier是什么? ===== | + | Brigadier 是由 Mojang 写的用于 Minecraft 的命令解析器和派发器。Brigadier 是基于树的命令库,可以建立参数和命令的树。 |
- | Brigadier是由Mojang写的用于Minecraft的命令解析器和派发器。Brigadier是基于树的命令库,可以建立参数与命令的数。 | + | 这是 Brigadier 的源代码:https:// |
- | 这是Brigadier的源代码:https:// | + | ===== Command 接口 ===== |
- | ===== 命令是什么? ===== | + | 在 Minecraft 中,'' |
- | Brigadier需要你指定'' | + | '' |
- | 命令'' | + | 就像其他的函数型接口那样,命令通常用于匿名函数或者方法引用: |
- | 命令可以通过以下方式实现: | + | <code java> |
- | + | Command<ServerCommandSource> command = context -> { | |
- | **__作为匿名函数__** | + | |
- | <code java [enable_line_numbers=" | + | |
- | Command<Object> command = context -> { | + | |
return 0; | return 0; | ||
}; | }; | ||
</ | </ | ||
- | **__作为匿名类__** | + | 这个整数相当于命令的结果。在 Minecraft 中。通常来说,负值表示命令执行失败,什么也不做,'' |
- | <code java [enable_line_numbers=" | + | |
- | Command< | + | |
- | @Override | + | |
- | public int run(CommandContext< | + | |
- | return | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | **__作为类来实现__** | + | ==== ServerCommandSource 是做什么的? ==== |
- | <code java [enable_line_numbers=" | + | |
- | final class XYZCommand implements Command< | + | '' |
- | | + | |
- | public int run(CommandContext< | + | |
- | return 0; | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | **__作为方法引用__** | ||
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | void registerCommand() { | + | // 获取命令源。这总是生效。 |
- | | + | final ServerCommandSource source = ctx.getSource(); |
- | | + | |
- | .executes(this:: | + | |
- | } | + | |
- | private int execute(CommandContext< | + | // 未经检查,如果是由控制台或命令方块执行的,则会是 null。 |
- | return 0; | + | final @Nullable Entity sender = source.getEntity(); |
- | } | + | |
- | </ | + | |
+ | // 如果命令执行者不是实体,就会抛出错误。 | ||
+ | // 这个的结果可能包含玩家,并且会发送反馈,告诉命令的发送者必须有一个实体。 | ||
+ | // 这个方法会要求你的方法能够抛出 CommandSyntaxException。 | ||
+ | // ServerCommandSource 中的 entity 选项可以返回一个 CommandBlock 实体、生物实体或者玩家。 | ||
+ | final @NotNull Entity sender2 = source.getEntityOrThrow(); | ||
- | '' | + | // 如果命令执行者不是玩家,则为 null。 |
+ | final @Nullable ServerPlayerEntity player = source.getPlayer(): | ||
- | 可以认为命令的结果是个整数。在Minecraft中,这个结果代表红石中继器从命令方块得到的红石信号强度,或者连锁型命令方块传递给其面向的方块的值。一般地,负值意味着命令失败,不执行操作。结果为0表示命令被忽略(pass)。正值表示命令成功执行。 | + | // 如果命令执行者不是玩家,抛出错误,并向命令的发送者发送反馈,告诉他必须有一个玩家。这个方法会要求你的方法能够抛出 CommandSyntaxException。 |
+ | final @NotNull ServerPlayerEntity player = source.getPlayerOrThrow(); | ||
- | ===== 基本命令 ===== | + | // 获取命令发送时发送者的坐标,以 Vec3d 的形式。这可以是实体或命令方块的位置,若为控制台则为世界重生点。 |
+ | final Vec3d position | ||
- | 下面是个不含参数的命令: | + | // 获取命令发送者所在的世界。控制台的世界就是默认重生的世界。 |
+ | final ServerWorld world = source.getWorld(); | ||
- | <code java [enable_line_numbers=" | + | // 获取发送者的旋转角度,以 Vec2f 的形式。 |
- | dispatcher.register(CommandManager.literal(" | + | final Vec2f rotation |
- | System.out.println(" | + | |
- | return 1; | + | // 访问命令运行时的 MinecraftServer 实例。 |
- | })); | + | final MinecraftServer server = source.getServer(); |
- | </ | + | |
- | '' | + | // 命令源的名称,可以是实体、玩家、命令方块的名称,命令方块可以在放置之前命令,若为控制台则为“Console” |
+ | final String name = source.getName(); | ||
- | ===== 静态导入 ===== | + | // 如果命令源拥有特定的权限等级,则返回 true,这基于发送者的管理员级别。(在内置服务器上,玩家必须启用了作弊才能执行这些命令。) |
- | 每次输入'' | + | final boolean b = source.hasPermissionLevel(int level); |
- | + | ||
- | 下面是静态导入的一些例子: | + | |
- | <code java [enable_line_numbers=" | + | |
- | // getString(ctx, | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.getString; | + | |
- | // word() | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.word; | + | |
- | // literal(" | + | |
- | import static net.minecraft.server.command.CommandManager.literal; | + | |
- | // argument(" | + | |
- | import static net.minecraft.server.command.CommandManager.argument; | + | |
- | // Import everything | + | |
- | import static net.minecraft.server.command.CommandManager.*; | + | |
</ | </ | ||
- | 注意:请确保你用的是CommandManager中的'' | + | ===== 注册一个基本的命令 ===== |
- | Brigadier的默认参数位于'' | + | 命令可以通过 Fabric API 的 '' |
- | Minecraft的默认参数位于'' | + | 这个事件必须在你的模组的初始化器中注册。这个回调有三个参数。'' |
- | ==== 子命令 ==== | + | 为简化代码,建议静态导入 '' |
+ | <code java> | ||
+ | import static net.minecraft.server.command.CommandManager.*; | ||
+ | </ | ||
- | 要添加子命令(sub command),你需要先注册命令的第一个文字节点。 | + | 在模组初始化器中,注册最简单的命令: |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | dispatcher.register(CommandManager.literal(" | + | public class ExampleMod implements ModInitializer { |
- | </ | + | |
- | + | | |
- | 要有子命令,需要将下一个节点附着于已有的节点之后。通过'' | + | |
- | + | ||
- | 创建如下所示的命令'' | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | dispatcher.register(literal(" | + | |
- | .then(literal(" | + | |
- | ); | + | |
- | </ | + | |
- | + | ||
- | 建议你为命令添加节点时将代码缩进。通常缩进意味着命令树的节点有多深。新行也可以使得另一个节点加入时清晰明了。本教程后面会展示的命令中有不同的节点风格。 | + | |
- | + | ||
- | **现在,尝试运行命令** | + | |
- | + | ||
- | Most likely if you typed ''/ | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | dispatcher.register(literal(" | + | |
- | .then(literal(" | + | |
.executes(context -> { | .executes(context -> { | ||
- | System.out.println("Called | + | // 对于 1.19 之前的版本,把“Text.literal”替换为“new LiteralText”。 |
+ | // 对于 1.20 之前的版本,请移除“() -> | ||
+ | context.getSource().sendFeedback(() -> Text.literal("调用 /foo,不带参数"), false); | ||
- | | + | |
- | }) | + | }))); |
- | | + | } |
- | ); | + | |
- | </ | + | |
- | + | ||
- | ===== 注册命令 ===== | + | |
- | + | ||
- | 可以使用'' | + | |
- | + | ||
- | 事件需要在mod的初始化器(initializer)中注册。callback有两个参数:'' | + | |
- | + | ||
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | public class ExampleCommandMod implements ModInitializer { | + | |
- | @Override | + | |
- | public void onInitialize() { | + | |
- | CommandRegistrationCallback.EVENT.register((dispatcher, | + | |
- | ... | + | |
- | }); | + | |
- | | + | |
} | } | ||
</ | </ | ||
- | 在你的匿名函数中,方法引用或者不管你选的什么,你都会注册命令。 | + | **请确保你导入了正确的静态方法。**方法 '' |
- | <code java [enable_line_numbers=" | + | 在 '' |
- | public class ExampleCommandMod implements ModInitializer { | + | |
- | @Override | + | |
- | public void onInitialize() { | + | |
- | CommandRegistrationCallback.EVENT.register((dispatcher, | + | |
- | dispatcher.register(literal(" | + | |
- | System.out.println(" | + | |
- | return 1; | + | |
- | })); | + | |
- | }); | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | 如有需要,可以通过检查'' | + | 如果命令失败,可以不必调用 |
+ | 要执行命令,必须输入 ''/ | ||
- | <code java [enable_line_numbers=" | + | ===== 注册环境 ===== |
- | public class ExampleCommandMod implements ModInitializer { | + | 如有需要,你可以确保命令仅在一些特定情形下注册,例如仅在专用服务器上: |
- | @Override | + | |
- | public void onInitialize() { | + | |
- | CommandRegistrationCallback.EVENT.register((dispatcher, | + | |
- | if (dedicated) { | + | |
- | TestDedicatedCommand.register(dispatcher); | + | |
- | } | + | |
- | }); | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | 类似地, | + | |
- | <code java [enable_line_numbers=" | + | <yarncode |
public class ExampleCommandMod implements ModInitializer { | public class ExampleCommandMod implements ModInitializer { | ||
@Override | @Override | ||
public void onInitialize() { | public void onInitialize() { | ||
- | CommandRegistrationCallback.EVENT.register((dispatcher, | + | CommandRegistrationCallback.EVENT.register((dispatcher, |
- | if (!dedicated) { | + | if (environment.field_25423) { |
- | | + | ...; |
} | } | ||
}); | }); | ||
} | } | ||
} | } | ||
- | </code> | + | </yarncode> |
- | ===== 参数 | + | ===== 静态导入 |
- | + | 在上面的例子中,使用了静态导入以简化代码。对于字面值,语句会简化为 | |
- | Brigadier中的参数会解析并检查输入的参数中的错误。Minecraft创建了一些特殊的参数用于其自身的使用,比如'' | + | |
- | + | ||
- | 关于参数的更多叙述,请关于[[tutorial: | + | |
- | + | ||
- | ====== 高级概念 ====== | + | |
- | + | ||
- | Below are links to the articles about more complex concepts used in brigadier. | + | |
- | + | ||
- | ^ Page ^ Description | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorial: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | | [[tutorials: | + | |
- | + | ||
- | **TODO:** Sections are being moved to sub categories and will be added to their respective articles as they are migrated. | + | |
- | + | ||
- | ====== 常见问题 ====== | + | |
- | + | ||
- | ===== 为什么我的命令不编译 ===== | + | |
- | + | ||
- | There are two immediate possibilities for why this could occur. | + | |
- | + | ||
- | ==== Catch or throw a CommandSyntaxException ==== | + | |
- | + | ||
- | The solution to this issue is to make the '' | + | |
- | + | ||
- | ==== 通用问题 ==== | + | |
- | + | ||
- | You may have an issue with generic types once in a while. Verify you are using '' | + | |
- | + | ||
- | ===== 可以注册客户端命令吗? ===== | + | |
- | + | ||
- | Fabric doesn' | + | |
- | There is an open pull request to fabric api which adds this. That will be documented on this page in the future. | + | |
- | + | ||
- | ===== 不建议的操作 ===== | + | |
- | + | ||
- | A few things we don't recommend, but are possible. | + | |
- | + | ||
- | ==== 可以在运行时注册命令吗? ==== | + | |
- | + | ||
- | You can do this but it is not recommended. You would get the '' | + | |
- | + | ||
- | After that you need to send the command tree to every player again using '' | + | |
- | + | ||
- | ==== 可以在运行时取消注册命令吗? ==== | + | |
- | + | ||
- | You can also do this, however it is much less stable than registering commands and could cause unwanted side effects. To keep things simple, you need to use reflection on brigadier and remove the nodes. After this, you need to send the command tree to every player again using '' | + | |
- | + | ||
- | ---- | + | |
- | + | ||
- | ====== Sorry for the mess ====== | + | |
- | + | ||
- | **__Currently this article is being migrated, so things may be a mess. Below is are the parts of the article that are yet to be migrated to the new format.__** | + | |
- | + | ||
- | Licensing from below onwards is available under the "CC Attribution-Noncommercial-Share Alike 4.0 International" | + | |
- | + | ||
- | ===== Requirements ===== | + | |
- | + | ||
- | Lets say you have a command you only want operators to be able to execute. This is where the '' | + | |
- | + | ||
- | For example this may look like the following: | + | |
+ | 以下是一些静态导入的例子。 | ||
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | dispatcher.register(literal("foo") | + | // getString(ctx, "string") |
- | .requires(source -> source.hasPermissionLevel(4)) | + | import static com.mojang.brigadier.arguments.StringArgumentType.getString; |
- | .executes(ctx -> { | + | // word() |
- | ctx.getSource().sendFeedback(new LiteralText("You are an operator"), false); | + | import static com.mojang.brigadier.arguments.StringArgumentType.word; |
- | return 1; | + | // literal(" |
- | }); | + | import static net.minecraft.server.command.CommandManager.literal; |
+ | // argument("bar", | ||
+ | import static net.minecraft.server.command.CommandManager.argument; | ||
+ | // Import everything in the CommandManager | ||
+ | import static net.minecraft.server.command.CommandManager.*; | ||
</ | </ | ||
- | This command will only execute if the Source of the command is a level 4 operator at minimum. If the predicate returns false, then the command will not execute. Also this has the side effect of not showing this command in tab completion to anyone who is not a level 4 operator. | + | 注意:请确保使用了 '' |
- | Nothing prevents someone from specifying calls to permissions implementations within the '' | + | Brigadier 的默认参数位于 |
- | ===== Exceptions ===== | + | Minecraft 的参数位于 '' |
- | Brigadier supports command exceptions which can be used to end a command such as if an argument didn't parse properly or the command failed to execute, as well as including richer details of the failure. | + | ===== 添加条件 ===== |
- | All the exceptions from Brigadier are based on the CommandSyntaxException. The two main types of exceptions Brigadier provides are Dynamic and Simple exception types, of which you must '' | + | 有时你希望命令只有管理员(OP)可以执行,这时就要用到 |
- | Below is a coin flip command to show an example of exceptions in use. | + | |
- | <code java [enable_line_numbers=" | + | 例如: |
- | dispatcher.register(CommandManager.literal(" | + | |
- | .executes(ctx -> { | + | |
- | Random random = new Random(); | + | |
- | + | ||
- | if(random.nextBoolean()) { // If heads succeed. | + | |
- | ctx.getSource().sendMessage(new TranslateableText(" | + | |
- | return Command.SINGLE_SUCCESS; | + | |
- | } | + | |
- | + | ||
- | throw new SimpleCommandExceptionType(new TranslateableText(" | + | |
- | })); | + | |
- | </ | + | |
- | + | ||
- | Though you are not just limited to a single type of exception as Brigadier also supplies Dynamic exceptions which take additional parameters for context. | + | |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { | + | dispatcher.register(literal(" |
- | | + | .requires(source -> source.hasPermissionLevel(2)) |
- | }); | + | .executes(ctx |
+ | | ||
+ | return 1; | ||
+ | }); | ||
</ | </ | ||
+ | 此时命令只会在命令源为 2 级以上(包括命令方块)时运行,否则命令不会被注册。这样做的副作用就是,非 2 级管理员会看到命令不会被 tab 补全,这也就是为什么没有启用作弊时不能够 tab 补全大多数命令。 | ||
- | There are more Dynamic exception types which each take a different amount of arguments into account ('' | + | 要创建只有 4 级管理员(不包括命令方块)可以执行的命令,请使用 |
- | You should remember that the Dynamic exceptions takes an object as an argument so you may have to cast the argument for your use. | + | |
- | ===== Redirects (Aliases) | + | ===== 参数 |
- | Redirects are Brigadier' | + | 大多数命令都使用了参数。一些参数是可选的,也就是说如果你不提供此参数,命令仍能运行。一个节点可以有多个参数类型,但是注意有可能出现二义性,这是需要避免的。 |
- | <code java [enable_line_numbers=" | + | 在这个例子中。我们添加一个整数参数。并计算整数的平方。 |
- | public static void register(CommandDispatcher< | + | |
- | LiteralCommandNode node = registerMain(dispatcher); | + | |
- | dispatcher.register(literal(" | + | |
- | .redirect(node)); | + | |
- | dispatcher.register(literal(" | + | |
- | .redirect(node)); | + | |
- | } | + | |
- | public static LiteralCommandNode registerMain(CommandDispatcher<ServerCommandSource> dispatcher) { | + | <code java> |
- | | + | dispatcher.register(literal(" |
- | .then(argument(" | + | .then(argument(" |
- | .then(argument(" | + | .executes(context |
- | .executes(ctx -> { | + | final int value = IntegerArgumentType.getInteger(context, " |
- | | + | final int result = value * value; |
- | })))); | + | context.getSource().sendFeedback(() -> Text.literal("%s × %s = %s".formatted(value, value, result)), false); |
- | } | + | return result; |
+ | }))); | ||
</ | </ | ||
- | The redirect tells brigadier to continue parsing the command at another command node. | + | 在这个例子中,在 ''/ |
- | ===== Redirects (Chainable Commands) ===== | + | 注意:为了简便,'' |
- | Commands such as '' | + | |
- | <code java [enable_line_numbers=" | + | 然后我们添加可选的第二个参数: |
- | LiteralCommandNode< | + | <code java> |
- | LiteralCommandNode< | + | dispatcher.register(literal(" |
- | // You can register under the same literal more than once, it will just register new parts of the branch as shown below if you register a duplicate branch an error will popup in console warning of conflicting commands but one will still work. | + | .then(argument("value", |
- | .then(literal(" | + | .executes(context -> { |
- | .then(literal("long") | + | final int value = IntegerArgumentType.getInteger(context, |
- | .redirect(root, this:: | + | final int result = value * value; |
- | | + | context.getSource().sendFeedback(() -> Text.literal(" |
- | | + | |
- | .then(literal("command") | + | }) |
- | .executes(ctx -> { | + | |
- | ctx.getSource().sendFeedback(new LiteralText("Chainable Command"), false); | + | .executes(context |
- | return | + | final int value = IntegerArgumentType.getInteger(context, |
- | }))); | + | final int value2 = IntegerArgumentType.getInteger(context, |
+ | final int result = value * value2; | ||
+ | context.getSource().sendFeedback(() -> Text.literal("%s × %s = %s".formatted(value, | ||
+ | return | ||
+ | })))); | ||
</ | </ | ||
- | The redirect can also modify the CommandSource by use of a '' | ||
- | <code java [enable_line_numbers=" | + | 现在你可以输入一个或者两个整数了。如果给一个整数,会计算这个整数的平方。如果提供两个整数,会计算这两个整数的积。你可能发现,两次指定类似的执行内容有些不太必要。因此,我们可以创建一个在两个执行中都使用的方法。 |
- | .redirect(rootNode, | + | |
- | return ((ServerCommandSource) context.getSource()).withLookingAt(Vec3ArgumentType.getVec3(context, | + | |
- | }) | + | |
- | </ | + | |
- | ===== What can the ServerCommandSource do? ===== | + | <code java> |
+ | public class ExampleMod implements ModInitializer { | ||
+ | @Override | ||
+ | public void onInitialize() { | ||
+ | CommandRegistrationCallback.EVENT.register((dispatcher, | ||
+ | .then(argument(" | ||
+ | .executes(context -> executeMultiply(IntegerArgumentType.getInteger(context, | ||
+ | .then(argument(" | ||
+ | .executes(context -> executeMultiply(IntegerArgumentType.getInteger(context, | ||
+ | } | ||
- | A server command source provides some additional implementation specific context when a command is run. This includes the ability to get the entity that executed the command, the world the command was ran in or the server the command was run on. | + | private static int executeMultiply(int value, int value2, CommandContext< |
- | + | | |
- | <code java [enable_line_numbers=" | + | |
- | final ServerCommandSource source = ctx.getSource(); | + | return |
- | // Get the source. This will always work. | + | } |
- | + | ||
- | final Entity sender = source.getEntity(); | + | |
- | // Unchecked, may be null if the sender was the console. | + | |
- | + | ||
- | final Entity sender2 = source.getEntityOrThrow(); | + | |
- | // Will end the command if the source of the command was not an Entity. | + | |
- | // The result of this could contain a player. Also will send feedback telling the sender of the command that they must be an entity. | + | |
- | // This method will require your methods to throw a CommandSyntaxException. | + | |
- | // The entity options in ServerCommandSource could return a CommandBlock entity, any living entity or a player. | + | |
- | + | ||
- | final ServerPlayerEntity player = source.getPlayer(); | + | |
- | // Will end the command if the source of the command was not explicitly a Player. Also will send feedback telling the sender of the command that they must be a player. | + | |
- | + | ||
- | source.getPosition(); | + | |
- | // Get's the sender' | + | |
- | + | ||
- | source.getWorld(); | + | |
- | // Get's the world the sender is within. The console' | + | |
- | + | ||
- | source.getRotation(); | + | |
- | // Get's the sender' | + | |
- | + | ||
- | source.getMinecraftServer(); | + | |
- | // Access to the instance of the MinecraftServer this command was ran on. | + | |
- | + | ||
- | source.getName(); | + | |
- | // The name of the command source. This could be the name of the entity, player, the name of a CommandBlock that has been renamed before being placed down or in the case of the Console, " | + | |
- | + | ||
- | source.hasPermissionLevel(int level); | + | |
- | // Returns true if the source of the command has a certain permission level. This is based on the operator status of the sender. (On an integrated server, the player must have cheats enabled to execute these commands) | + | |
- | </ | + | |
- | + | ||
- | ===== Some example commands examples ===== | + | |
- | + | ||
- | === Broadcast a message === | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | public static void register(CommandDispatcher< | + | |
- | | + | |
- | .requires(source -> source.hasPermissionLevel(2)) // Must be a game master to use the command. Command will not show up in tab completion or execute to non operators or any operator that is permission level 1. | + | |
- | .then(argument(" | + | |
- | .then(argument(" | + | |
- | .executes(ctx | + | |
- | } | + | |
- | + | ||
- | public static int broadcast(ServerCommandSource source, Formatting formatting, String message) { | + | |
- | final Text text = new LiteralText(message).formatted(formatting); | + | |
- | + | ||
- | source.getMinecraftServer().getPlayerManager().broadcastChatMessage(text, MessageType.CHAT, | + | |
- | return | + | |
} | } | ||
</ | </ | ||
- | ==== / | + | ===== 子命令 ===== |
- | First the basic code where we register " | + | 要添加子命令,你需要先照常注册第一个字面节点。 |
- | < | + | < |
- | public static LiteralCommandNode register(CommandDispatcher< | + | dispatcher.register(literal(" |
- | return | + | |
- | .executes(ctx -> giveDiamond(ctx))); | + | |
- | } | + | |
</ | </ | ||
- | Then since we only want to give to players, we check if the CommandSource is a player. But we can use '' | + | 为拥有子命令,需要把下一个节点追加到已经存在的节点后面。 |
- | <code java [enable_line_numbers=" | + | 如下所示,创建命令 '' |
- | public static int giveDiamond(CommandContext< | + | |
- | final ServerCommandSource source = ctx.getSource(); | + | |
- | + | ||
- | final PlayerEntity self = source.getPlayer(); | + | |
- | </code> | + | |
- | Then we add to the player's inventory, with a check to see if the inventory is full: | + | <code java [enable_line_numbers=" |
+ | dispatcher.register(literal(" | ||
+ | .then(literal(" | ||
+ | .executes(context -> { | ||
+ | // 对于 1.19 以下的版本,使用 '' | ||
+ | // 对于 1.20 以下的版本,直接使用 '' | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
- | <code java [enable_line_numbers=" | + | return 1; |
- | if(!player.inventory.insertStack(new ItemStack(Items.DIAMOND))){ | + | |
- | | + | |
- | | + | ); |
- | + | ||
- | return 1; | + | |
- | } | + | |
</ | </ | ||
- | ==== Antioch ==== | + | 建议给命令添加节点时缩进你的代码,通常来说缩进对应了命令树中有多少节点的深度,每一次换行也可以看出添加了一个节点。本教程后面会展示格式化树状命令的几种可选样式。 |
- | ...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe. | + | |
- | who being naughty in My sight, shall snuff it. | + | |
- | + | ||
- | Aside from the joke this command summons a primed TNT to a specified location or the location of the sender' | + | |
- | + | ||
- | First create an entry into the CommandDispatcher that takes a literal of antioch with an optional argument of the location to summon the entity at. | + | |
+ | 类似于参数,子命令节点也可以设置为可选的。在下面这个例子中,''/ | ||
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | public static void register(CommandDispatcher< | + | dispatcher.register(literal(" |
- | | + | .executes(context -> { |
- | .then(required(" | + | context.getSource().sendFeedback(() -> Text.literal(" |
- | | + | return 1; |
- | .executes(ctx -> antioch(ctx.getSource(), null))); | + | }) |
- | } | + | |
+ | .executes(context | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | | ||
+ | | ||
+ | ) | ||
+ | ); | ||
</ | </ | ||
- | Then the creation and messages behind the joke. | + | ====== 高级概念 ====== |
- | <code java [enable_line_numbers=" | + | 以下是 brigadier 使用的更加复杂的概念的文章链接。 |
- | public static int antioch(ServerCommandSource source, BlockPos blockPos) throws CommandSyntaxException { | + | |
- | if(blockPos == null) { | + | |
- | // For the case of no inputted argument we calculate the cursor position of the player or throw an error if the nearest position is too far or is outside of the world. | + | |
- | // This class is used as an example and actually doesn' | + | |
- | blockPos = LocationUtil.calculateCursorOrThrow(source, | + | |
- | } | + | |
- | final TntEntity tnt = new TntEntity(source.getWorld(), | + | ^ 页面 ^ 描述 ^ |
- | | + | | [[command_exceptions |
- | + | | [[command_suggestions|Suggestions]] | |
- | | + | | [[command_redirects|Redirects]] |
- | | + | | [[command_argument_types|Custom Argument Types]] |
- | source.getWorld().spawnEntity(tnt); | + | | [[command_examples|Examples]] | 一些示例命令 | |
- | return 1; | + | |
- | } | + | |
- | </ | + | |
- | ==== More examples coming soon ==== | + | ====== 常见问题 ====== |
- | ===== Custom Argument Types ===== | + | ===== 代码为什么不编译 |
+ | 此问题可能有一些常见的原因。 | ||
- | Brigadier | + | * **捕获或抛出 CommandSyntaxException:**'' |
+ | * **泛型问题:**你可能遇到了泛型问题。如果你在注册服务器命令(大多数情况都是如此),确保你在静态导入中使用 '' | ||
+ | * **检查 '' | ||
+ | * **'' | ||
- | Warning: Custom arguments require client mod installation to be registered correctly! If you are making a server plugin, consider using existing argument type and a custom suggestions provider instead. | + | ===== 可以注册客户端命令吗? ===== |
- | For this example we will create a UuidArgumentType. | + | Fabric API 有个 '' |
- | First create a class which extends '' | ||
- | |||
- | <code java [enable_line_numbers=" | ||
- | public class UuidArgumentType implements ArgumentType< | ||
- | </ | ||
- | |||
- | ArgumentType requires you to implement the '' | ||
<code java> | <code java> | ||
- | @Override | + | ClientCommandRegistrationCallback.EVENT.register((dispatcher, |
- | public UUID parse(StringReader reader) throws CommandSyntaxException | + | .executes(context -> { |
+ | context.getSource().sendFeedback(Text.literal(" | ||
+ | return 1; | ||
+ | } | ||
+ | ))); | ||
</ | </ | ||
- | This method is where all of your parsing will occur. Either this method will return the object based on the arguments provided in the command line or throw a CommandSyntaxException and parsing will fail. | + | 如果你需要在客户端命令执行过程中打开屏幕,不要直接调用 '' |
- | Next you will store the current position of the cursor, this is so you can substring out only the specific argument. This will always be at the beginning of where your argument appears on the command line. | + | ===== 可以运行时注册命令吗? ===== |
- | <code java [enable_line_numbers=" | + | 可以这么做但是不推荐,你可以从服务器中获取 '' |
- | int argBeginning = reader.getCursor(); | + | |
- | if (!reader.canRead()) { | + | |
- | reader.skip(); | + | |
- | } | + | |
- | </ | + | |
- | Now we grab the entire argument. Depending on your argument type, you may have a different criteria or be similar to some arguments where detecting a '' | + | 然后你需要通过 |
- | <code java [enable_line_numbers=" | + | ===== 可以在运行时取消注册命令吗? ===== |
- | while (reader.canRead() && reader.peek() != ' ') { // peek provides the character at the current cursor position. | + | |
- | reader.skip(); | + | |
- | } | + | |
- | </ | + | |
- | Then we will ask the StringReader what the current position of the cursor is an substring our argument out of the command line. | + | 可以这么做,但是这更不稳定,并且可能造成未预料的副作用。为简化事情,你需要在 brigadier 中使用反射并移除这个节点,然后还需要再次使用 '' |
- | <code java [enable_line_numbers=" | ||
- | |||
- | Now finally we check if our argument is correct and parse the specific argument to our liking, and throwing an exception if the parsing fails. | ||
- | |||
- | <code java [enable_line_numbers=" | ||
- | try { | ||
- | UUID uuid = UUID.fromString(uuidString); | ||
- | return uuid; // And we return our type, in this case the parser will consider this argument to have parsed properly and then move on. | ||
- | } catch (Exception ex) { | ||
- | // UUIDs can throw an exception when made by a string, so we catch the exception and repackage it into a CommandSyntaxException type. | ||
- | // Create with context tells Brigadier to supply some context to tell the user where the command failed at. | ||
- | // Though normal create method could be used. | ||
- | throw new SimpleCommandExceptionType(new LiteralText(ex.getMessage())).createWithContext(reader); | ||
- | } | ||
- | </ | ||
- | |||
- | The ArgumentType is done, however your client will refuse the parse the argument and throw an error. This is because the server will tell the client what argument type the command node is. And the client will not parse any argument types it does not know how to parse. To fix this we need to register an ArgumentSerializer. | ||
- | Within your ModInitializer. For more complex argument types, you may need to create your own ArgumentSerializer. | ||
- | |||
- | <code java [enable_line_numbers=" | ||
- | ArgumentTypes.register(" | ||
- | // The argument should be what will create the ArgumentType. | ||
- | </ | ||
- | |||
- | And here is the whole ArgumentType: | ||
- | |||
- | <file java UuidArgumentType.java [enable_line_numbers=" | ||
- | |||
- | import com.mojang.brigadier.StringReader; | ||
- | import com.mojang.brigadier.arguments.ArgumentType; | ||
- | import com.mojang.brigadier.context.CommandContext; | ||
- | import com.mojang.brigadier.exceptions.CommandSyntaxException; | ||
- | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; | ||
- | import net.minecraft.text.LiteralText; | ||
- | import net.minecraft.util.SystemUtil; | ||
- | |||
- | import java.util.ArrayList; | ||
- | import java.util.Collection; | ||
- | import java.util.UUID; | ||
- | |||
- | /** | ||
- | * Represents an ArgumentType that will return a UUID. | ||
- | */ | ||
- | public class UuidArgumentType implements ArgumentType< | ||
- | public static UuidArgumentType uuid() { | ||
- | return new UuidArgumentType(); | ||
- | } | ||
- | |||
- | public static <S> UUID getUuid(String name, CommandContext< | ||
- | // Note that you should assume the CommandSource wrapped inside of the CommandContext will always be a generic type. | ||
- | // If you need to access the ServerCommandSource make sure you verify the source is a server command source before casting. | ||
- | return context.getArgument(name, | ||
- | } | ||
- | |||
- | private static final Collection< | ||
- | list.add(" | ||
- | list.add(" | ||
- | list.add(" | ||
- | }); | ||
- | |||
- | @Override | ||
- | public UUID parse(StringReader reader) throws CommandSyntaxException { | ||
- | int argBeginning = reader.getCursor(); | ||
- | if (!reader.canRead()) { | ||
- | reader.skip(); | ||
- | } | ||
- | |||
- | // Now we check the contents of the argument till either we hit the end of the command line (When canRead becomes false) | ||
- | // Otherwise we go till reach reach a space, which signifies the next argument | ||
- | while (reader.canRead() && reader.peek() != ' ') { // peek provides the character at the current cursor position. | ||
- | reader.skip(); | ||
- | } | ||
- | |||
- | // Now we substring the specific part we want to see using the starting cursor position and the ends where the next argument starts. | ||
- | String uuidString = reader.getString().substring(argBeginning, | ||
- | try { | ||
- | UUID uuid = UUID.fromString(uuidString); | ||
- | return uuid; // And we return our type, in this case the parser will consider this argument to have parsed properly and then move on. | ||
- | } catch (Exception ex) { | ||
- | // UUIDs can throw an exception when made by a string, so we catch the exception and repackage it into a CommandSyntaxException type. | ||
- | // Create with context tells Brigadier to supply some context to tell the user where the command failed at. | ||
- | // Though normal create method could be used. | ||
- | throw new SimpleCommandExceptionType(new LiteralText(ex.getMessage())).createWithContext(reader); | ||
- | } | ||
- | } | ||
- | |||
- | @Override | ||
- | public Collection< | ||
- | return EXAMPLES; | ||
- | } | ||
- | } | ||
- | </ |
zh_cn/tutorial/commands.1631854831.txt.gz · Last modified: 2021/09/17 05:00 by 54.161.41.102