Plasmid
Plasmid 是一个用于使用 Fabric 创建服务端小游戏的库。
Plasmid 处理所有与小游戏实现相关的繁琐工作,从而让你能够专注于游戏本身。
Plasmid 是 Nucleoid Project 的核心,该项目旨在为服务端 Minecraft 小游戏构建一个开源生态系统。
你可以在 Nucleoid GitHub 组织 上查看许多使用 Plasmid 实现的游戏示例。
如果你感兴趣,甚至可以在我们的测试 Minecraft 服务器 nucleoid.xyz 上体验其中一些游戏!
如果你遇到任何问题或疑问,或者希望参与其中,也可以在 Discord 上找到我们。
使用指南
这是我们的 入门指南 Wiki 页面的镜像,提供了对 Plasmid 概念的基本介绍。
你可以访问我们的 Wiki 站点 以获取更详细的信息。
如果你想快速上手并设置基本游戏框架,请克隆 plasmid-starter 仓库,运行 init.py,然后删除 .git、README.md 和 init.py。另外,如果你正在寻找现有已实现游戏的示例,可以浏览 Nucleoid Organisation 的仓库。
添加到 Gradle
假设你 已经设置了 Fabric 工作区,设置 Plasmid 的第一步是将其添加到你的 gradle 构建脚本中。你需要同时添加 maven 仓库以及 plasmid 依赖项。PLASMID_VERSION 应替换为 Maven 上的最新版本。
本教程当前针对 Plasmid 0.5.x 版本进行了更新。
repositories {
maven { url = 'https://maven.nucleoid.xyz/' }
}
dependencies {
// ...
modImplementation 'xyz.nucleoid:plasmid:PLASMID_VERSION'
}
创建游戏类型
“游戏类型”(GameType)是使用 Plasmid 创建游戏的入口点:它们为你的游戏提供唯一标识符,以及在游戏启动时调用你代码所需的所有信息。
Plasmid 的设计鼓励数据驱动型游戏,并使用“游戏配置”的概念。游戏配置本质上是一种特定类型的游戏变体!这可能涉及不同的地图,或者完全不同的游戏规则。游戏配置只需在数据包中以 JSON 文件的形式定义,引用你的 GameType 并传递任何可能对配置游戏有用的额外数据。虽然这起初可能稍显复杂,但它非常强大,允许在不重复代码的情况下更容易地调整游戏或生成多个变体。关于配置的更多内容稍后介绍!
要注册一个 GameType,你需要在你的 ModInitializer 类中调用 GameType.register()。注册 GameType 的调用可能如下所示:
GameType.register(
new Identifier("plasmid_example", "example"),
ExampleGameConfig.CODEC,
ExampleGame::open
);
让我们分解一下这里发生了什么:
new Identifier("plasmid_example", "example")
- 声明此 游戏类型 的唯一标识符,供游戏配置文件 JSON 引用
ExampleGameConfig.CODEC
- 一个
Codec,将用于从 JSON 文件加载游戏配置(稍后详细介绍!)
ExampleGame::open
- 一个方法引用,指向当玩家请求启动时将用于开始你游戏的功能
这目前尚无法编译:因为 ExampleGame 和 ExampleGameConfig 都不存在!让我们来解决这个问题。
在代码中创建配置
首先,我们将创建 ExampleGameConfig 类,该类将包含一个 String 字段,该字段将用作向加入的玩家发送的消息。Java 的新 Records(记录) 非常适合用于配置,但并非必需!
public record ExampleGameConfig(String greeting) {
}
很简单吧?但我们缺少之前引用的 CODEC 字段。这是什么东西呢?
Codec 是 Mojang 的 DataFixerUpper 库实现的一个非常有用的工具,它本质上允许方便地将 Java 对象序列化和反序列化到 JSON 文件中。Drullkus 对 Codecs 的详细解释可以在 这里 找到,但对于简单用途,你只需要知道如何将它们组合在一起的模式即可。
本质上,Codec 描述了 对象如何被序列化和反序列化。简单来说,它们可以从字段列表以及这些字段应如何序列化来创建。过程如下:
public record ExampleGameConfig(String greeting) {
public static final Codec<ExampleGameConfig> CODEC = RecordCodecBuilder.create(instance -> {
return instance.group(
Codec.STRING.fieldOf("greeting").forGetter(ExampleGameConfig::greeting)
).apply(instance, ExampleGameConfig::new);
});
}
这将对应于如下所示的 JSON 文件:
{
"greeting": "Hello World!"
}
这里的大部分内容你可以忽略:你真正需要关注的只是 instance.group(...) 调用中的内容以及 Codec 上的泛型。为了更具体地查看每个相关部分:
Codec<ExampleGameConfig>
- 被反序列化的类类型作为泛型参数传递给
Codec。
Codec.STRING.fieldOf(...).forGetter(...)
- 这会添加一个具有给定名称和类型的字段,该字段将从 JSON 中读取。
- 你会注意到
Codec.STRING 本身就是一个 Codec<String>!你声明的每个字段都需要一个 Codec 来描述如何处理该字段。在这种情况下,我们指示 greeting 字段应使用 Codec.STRING 加载。同样,我们可以引用我们创建的任何其他 Codec 并将其作为字段添加!这在允许组合 Codec 以创建复杂结构方面非常有用!
- Codec 提示:大多数可序列化的 Minecraft 类型都会持有一个静态
CODEC 字段供使用(例如 BlockPos.CODEC 或 Identifier.CODEC)。如果没有,我们会提供一个 MoreCodecs 类型,其中包含一些未包含在原版代码库中的常用 Codec(例如 MoreCodecs.TEXT)。
.fieldOf() 的参数指定了将从其读取此值的字段的名称(在 JSON 中)。
.forGetter() 指定了如何从我们的配置对象中读取字段的值。这很有用,因为 Codec 允许序列化和反序列化,而 getter 是必需的吗,用于将对象转回数据。由于我们使用的是记录(record),我们可以在此处使用方法引用。
ExampleGameConfig::new
- 这告诉 Codec 如何在所有字段反序列化后创建对象。这需要对该给定对象的构造函数的方法引用,且所有字段必须按照它们指定的顺序排列!。
- 例如,如果我们先传递
Codec.STRING.fieldOf("foo"),然后传递 Codec.INT.fieldOf("bar"),构造函数将接受 (String, int)。
- 但在这里我们接收一个
String 字段,而我们引用的构造函数也接受单个 String 参数。
所有这些 Codec 工作的最终结果是,当我们创建游戏配置时,所有这些数据都将从我们的 JSON 文件中自动解析并传递给我们的游戏代码!
创建配置
现在我们知道配置应该包含哪些数据,我们可以为 Plasmid 创建一个实际的游戏配置 JSON。
所有游戏配置都必须位于你的模组资源(或 数据包!)中,路径为 data/<namespace>/games/<id>.json。对于模组而言,namespace 应该是你的模组 ID,而 id 可以是任何唯一的名称,稍后将在 Minecraft 内部用于引用你的游戏配置。
Plasmid 仅需要从配置中获取 1 个 JSON 字段,其余部分则根据你设置的配置 Codec 加载。不过,还有一些额外的可选字段可能有助于定义。唯一必需的字段是 type,它指的是你在 namespace:path 格式之前创建的 GameType(例如,在我们的案例中,为 plasmid_example:example)。
出于我们的目的,我们在 data/plasmid_example/games/hello_world_example.json 处的游戏配置如下所示:
{
"type": "plasmid_example:example",
"greeting": "Hello, World!"
}
我们还可以向我们的 JSON 中添加一些额外的内置字段,如 name、short_name、description 和 icon。
这可能看起来像这样:
{
"type": "plasmid_example:example",
"name": "Hello World Example!",
"description": ["Look at my cool game!", "It greets you when you join."],
"icon": "minecraft:apple"
// ...
}
name 和 description 也可以引用翻译键,因为它们属于 JSON 文本组件。例如,这可能是:"name": {"translation": "game.plasmid_example.hello_world_example"}。
关于翻译的说明
由于 Plasmid 完全是服务器端的,因此其翻译方式有些非标准!通常翻译存储在客户端,而服务器仅发送 翻译键,然后在客户端将其转换为相关的可读文本。然而,在这里我们需要通过更改发送给玩家的数据包来处理翻译,以便在客户端甚至接收到之前就正确翻译。这是一项繁重的工作!幸运的是,这由 Server Translations 处理,我们无需担心!
这对你来说实际上意味着你的语言文件需要放在 data 文件夹中而不是 assets 文件夹中(例如 data/<namespace>/lang/en_us.json)。
如果我们没有手动定义名称,那么我们应该注意一些默认的语言键:gameType.<namespace>.<id> 和 game.<namespace>.<id>。这些键分别应用于游戏 类型 和游戏 配置。当解析游戏配置的可读名称时,将测试配置翻译和类型翻译,并将类型作为后备。这意味着只有游戏类型翻译是严格必要的。
例如,我们可以将我们的 data/plasmid_example/lang/en_us.json 定义为:
{
"gameType.plasmid_example.example": "Plasmid Example!",
"game.plasmid_example.hello_world_example": "Hello World Example!"
}
编写启动游戏的代码
现在我们已经设置了配置,并告诉 Plasmid 如何从中读取数据,我们现在终于可以编写实际启动游戏的代码了。
出于本示例的目的,让我们创建一个 ExampleGame 类。我们将使用此类来保存游戏的状态以及加载的 ExampleGameConfig。不过现在,我们只需要创建这个我们引用到 GameType 的 open 函数即可。
这应该看起来像这样:
public class ExampleGame {
public static GameOpenProcedure open(GameOpenContext<ExampleGameConfig> context) {
// 获取由 Plasmid 加载的配置
ExampleGameConfig config = context.config();
// 创建一个非常简单的地图模板,在 (0; 64; 0) 处放置一个石头方块
MapTemplate template = MapTemplate.createEmpty();
template.setBlockState(new BlockPos(0, 64, 0), Blocks.STONE.getDefaultState());
// 创建一个将从我们刚刚创建的模板中生成世界的区块生成器
TemplateChunkGenerator generator = new TemplateChunkGenerator(context.server(), template);
// 设置这个迷你游戏所在的世界应如何构建
RuntimeWorldConfig worldConfig = new RuntimeWorldConfig()
.setGenerator(generator)
.setTimeOfDay(6000);
return context.openWithWorld(worldConfig, (activity, world) -> {
// 待实现
});
}
}
这里有很多内容需要梳理,但如果将其分解,其实并不复杂。每当玩家开始此游戏时,我们的 open 方法就会被调用。该函数接收一个 GameOpenContext,其中包含来自 JSON 配置的数据(通过 context.config() 获取),并且必须返回一个 GameOpenProcedure,用于指示 Plasmid 应如何继续设置游戏。值得注意的是,此函数在线程池上异步运行,因此在游戏开始前在此处运行任何缓慢的代码都是安全的。
GameOpenProcedure 是由 GameOpenContext.openWithWorld 函数创建的,它接收一个 RuntimeWorldConfig 以及一个接受 GameActivity 和 ServerWorld 的 lambda 表达式。运行时世界是 Plasmid 中的一个概念,代表游戏发生的完全隔离且临时的世界。当游戏结束时,它会被自动删除。当玩家加入游戏时,他们的物品栏将被清空;当他们离开时,物品栏将恢复给他们。游戏活动是指在游戏内运行的特定逻辑集合:我们将通过配置它来改变游戏行为。我们可以在游戏中的任何时候切换活动。
RuntimeWorldConfig 描述了这个世界应如何创建。其中最重要的配置项是区块生成器:它告诉游戏世界应如何生成。例如,我们可以传递主世界(Overworld)的区块生成器,但出于我们的目的,我们创建了一个仅包含单个石头方块的空白世界。这是通过便捷的 TemplateChunkGenerator 处理的:它接收一个 MapTemplate,这只是一个包含一些方块的非常基础的世界!然后,生成器从该模板加载数据到世界本身中。
最后,我们需要处理带有 GameActivity 参数的 lambda 中的内容。此 lambda 内部的代码将在主服务器线程上运行,用于运行实际的游戏设置代码。这主要涉及注册事件监听器或设置全局规则。
事件提示:我们使用 Stimuli 来处理游戏中的许多事件,因此 Stimuli 中的任何事件都可以在 Plasmid 中使用。
例如:
return context.openWithWorld(worldConfig, (activity, world) -> {
activity.deny(GameRuleType.FALL_DAMAGE);
activity.listen(GamePlayerEvents.ADD, player -> {
// 一名玩家已加入!
});
});
这段代码将为所有玩家禁用摔落伤害,并注册一个事件监听器,每当有玩家加入此游戏时就会调用该监听器。
然而!在我们赋予这个出色的示例游戏功能之前,我们需要响应玩家邀请事件监听器。它在任何玩家加入游戏之前被调用,并且可以接受或拒绝该加入请求。最关键的是,监听器定义了玩家应如何以及在哪里生成到我们的游戏世界中。
一个示例邀请监听器可能如下所示:
activity.listen(GamePlayerEvents.OFFER, offer -> {
ServerPlayerEntity player = offer.player();
return offer.accept(world, new Vec3d(0.0, 64.0, 0.0))
.and(() -> {
player.changeGameMode(GameMode.ADVENTURE);
});
});
这有很多内容!让我们将其分解:
- 我们为
GamePlayerEvents.OFFER 注册了一个监听器,该监听器接收一个 offer 参数。
- 我们从邀请中获取试图加入的玩家实例。
- 我们调用
offer.accept(...) 以接受该玩家加入游戏。
- 我们向接受函数传递一个 世界 和玩家将被传送到的 位置。这个世界是由 Plasmid 在上面传递给我们的!
- 然后我们在
.accept(...) 的结果上调用 .and(...),以便附加一些额外的生成逻辑,在玩家加入时运行。在这种情况下,就是在玩家加入时将他们的游戏模式设置为冒险模式。
现在我们已经设置了这些,我们可以回到我们的玩家加入监听器:目前,当调用它时我们没有做任何事情。我们希望当玩家加入时向他们发送问候语。让我们实现这一点:
GameSpace gameSpace = activity.getGameSpace();
activity.listen(GamePlayerEvents.ADD, player -> {
LiteralText message = new LiteralText(config.greeting);
gameSpace.getPlayers().sendMessage(message);
});
所以我们在监听器中添加了发送消息的逻辑,但是什么是 GameSpace?GameSpace 是 Plasmid 引入的一个概念,顾名思义,它代表了游戏发生的_空间_。对于我们的所有目的而言,这个空间仅仅是游戏所在的这一维度。GameSpace 对我们很有用,因为它会跟踪其中的所有玩家以及游戏发生的 ServerWorld。在这里,我们通过 GameActivity.getGameSpace() 访问 GameSpace。
与玩家交互还会通过另一个 Plasmid API 进行:PlayerSet。PlayerSet 仅代表一个玩家列表,可以被迭代或查询,同时还提供了对大量玩家执行批量操作的实用工具。例如发送消息!在这里,我们使用 PlayerSet.sendMessage() 向游戏中的每位玩家发送问候语。
太棒了!? 我们已经有了一个可运行的游戏!但在测试之前,让我们做一些轻微的重组。有了所有这些处理程序和 Lambda 表达式,我们在 createOpenProcedure 内部的代码很快就会变得非常冗长!如果能把所有事件监听器放在我们的 ExampleGame 对象上就好了。
事实证明,这完全可行,最终留下了我们的 ExampleGame 设置:
public final class ExampleGame {
private final ExampleGameConfig config;
private final GameSpace gameSpace;
private final ServerWorld world;
public ExampleGame(ExampleGameConfig config, GameSpace gameSpace, ServerWorld world) {
this.config = config;
this.gameSpace = gameSpace;
this.world = world;
}
public static GameOpenProcedure open(GameOpenContext<ExampleGameConfig> context) {
// 获取由 Plasmid 加载的配置
ExampleGameConfig config = context.config();
// 创建一个简单的地图模板,在 (0; 64; 0) 处放置一个石头方块
MapTemplate template = MapTemplate.createEmpty();
template.setBlockState(new BlockPos(0, 64, 0), Blocks.STONE.getDefaultState());
// 创建一个将从我们刚刚创建的模板生成地形的区块生成器
TemplateChunkGenerator generator = new TemplateChunkGenerator(context.server(), template);
// 设置这个迷你游戏所在世界的构建方式
RuntimeWorldConfig worldConfig = new RuntimeWorldConfig()
.setGenerator(generator)
.setTimeOfDay(6000);
return context.openWithWorld(worldConfig, (activity, world) -> {
ExampleGame game = new ExampleGame(config, activity.getGameSpace(), world);
activity.deny(GameRuleType.FALL_DAMAGE);
activity.listen(GamePlayerEvents.OFFER, game::onPlayerOffer);
activity.listen(GamePlayerEvents.ADD, game::onPlayerAdd);
});
}
private PlayerOfferResult onPlayerOffer(PlayerOffer offer) {
ServerPlayerEntity player = offer.player();
return offer.accept(this.world, new Vec3d(0.0, 64.0, 0.0))
.and(() -> {
player.changeGameMode(GameMode.ADVENTURE);
});
}
private void onPlayerAdd(ServerPlayerEntity player) {
LiteralText message = new LiteralText(this.config.greeting);
this.gameSpace.getPlayers().sendMessage(message);
}
}
测试游戏!
一旦一切编译成功,我们就可以启动 Minecraft 了。如果我们的 GameType 配置正确且游戏配置文件 JSON 就位,打开世界后,我们应该能够通过运行 /game open <id> 来启动游戏。(请记住,这里引用的是 JSON 文件的名称,而不是 GameType!)
所以在我们的例子中:/game open plasmid_example:hello_world_example
……我们将加入到一个虚空世界中,那里有一个石头方块和一句亲切的问候!
现在,任何其他玩家也可以通过运行 /game join 或点击聊天中出现的链接加入我们。
就是这样!?
Plasmid
Plasmid is a library for creating server-side minigames with Fabric.
Plasmid does all the boring work relating to minigame implementation, to rather allow focus effort on just the game itself.
Plasmid is the core of the Nucleoid Project, an effort to build an open source ecosystem for server-side Minecraft minigames.
You can view many examples of games implemented with Plasmid on the Nucleoid GitHub Organisation.
You may even be interested in playing some of them over on our testing Minecraft server at nucleoid.xyz!
You can also find us on our Discord if you have any troubles or queries, or would like to get involved.
Using
This is a mirror of our Getting Started wiki page and provides a basic introduction to Plasmid concepts.
You can view our wiki site for more detailed information.
If you would like to get up and running quickly with a basic game setup, clone the plasmid-starter repository, run init.py, and then delete .git, README.md, and init.py. Alternatively, if you are looking for examples of existing implemented games, take a look through the Nucleoid Organisation repositories.
Adding to Gradle
Assuming you already have a Fabric workspace set up, the first step to setting up Plasmid will be adding it to your gradle buildscript. You will need to add the maven repository as well as the plasmid dependency. PLASMID_VERSION should be replaced with the latest version from Maven.
This tutorial is currently updated for Plasmid 0.5.x.
repositories {
maven { url = 'https://maven.nucleoid.xyz/' }
}
dependencies {
// ...
modImplementation 'xyz.nucleoid:plasmid:PLASMID_VERSION'
}
Creating a game type
A "game type" (GameType) is the entry-point to creating a game with Plasmid: they provide a unique identifier for your game, as well as all the information needed for it to be able to call your code when the game starts.
Plasmid is designed to encourage data-driven games, and works with the concept of a "game config". A game config is essentially a specific variation of a game type! This may involve a different map to play on, or entirely different game mechanics. A game config is simply defined as a JSON file in a datapack that references your GameType and passes along any extra data that may be useful for configuring your game. While this may be a bit more work at first, it is very powerful in allowing games to be much easier to tweak or produce multiple variations of without duplicating code. More on configs later!
To register a GameType, you will need to call GameType.register() in your ModInitializer class. A call to register a GameType may look something like:
GameType.register(
new Identifier("plasmid_example", "example"),
ExampleGameConfig.CODEC,
ExampleGame::open
);
Let's break down what is going on here:
new Identifier("plasmid_example", "example")
- declares the unique identifier for this game type that will be referenced by game config JSONs
ExampleGameConfig.CODEC
- a
Codec that will be used to load the game configuration from a JSON file (more on this later!)
ExampleGame::open
- a method reference to a function that will be used to start your game when a player requests it
This naturally will not compile yet: neither ExampleGame nor ExampleGameConfig exist! Let's get to that.
Creating our config in code
First we will create our ExampleGameConfig class, which will hold a String field that will be used as a message to send to the player when they join. Java's new Records are perfect for configs, but not required!
public record ExampleGameConfig(String greeting) {
}
That's simple enough! But we're missing the CODEC field that we referenced earlier. What is that about?
A Codec is a very helpful tool implemented by Mojang's DataFixerUpper library that essentially allows for convenient serialization and deserialization of a Java object to a JSON file. A more detailed explanation of Codecs by Drullkus can be found here, but for simple purposes, all you need to know is the pattern for putting them together.
Essentially, a Codec describes how an object is serialized and deserialized. Simply, they can be created from a list of fields and how those fields should be serialized. It goes like this:
public record ExampleGameConfig(String greeting) {
public static final Codec<ExampleGameConfig> CODEC = RecordCodecBuilder.create(instance -> {
return instance.group(
Codec.STRING.fieldOf("greeting").forGetter(ExampleGameConfig::greeting)
).apply(instance, ExampleGameConfig::new);
});
}
This will correspond to a JSON file that looks something like:
{
"greeting": "Hello World!"
}
Most things here you can ignore: you only really need to worry about what's in the instance.group(...) call, and the generic on the Codec. To look at each relevant part more specifically:
Codec<ExampleGameConfig>
- The type of class that is being deserialized into is passed as a generic parameter to the
Codec.
Codec.STRING.fieldOf(...).forGetter(...)
- This adds a field with a given name and type that will be read from the JSON.
- You will notice that
Codec.STRING is itself a Codec<String>! Every field you declare will require a Codec to describe how that field should be handled. In this case, we're indicating that the greeting field should be loaded using Codec.STRING. In the same way, we could reference any other codec we create to add it as a field! This is very useful in allowing combinations of codecs to create complex structures!
- Codec tip: most serializable Minecraft types will hold a static
CODEC field for use (e.g. BlockPos.CODEC or Identifier.CODEC). If not, we bundle a MoreCodecs type which provides some common ones that are not included in the vanilla codebase (e.g. MoreCodecs.TEXT).
- The parameter to
.fieldOf() specifies the name of the field (in JSON) that this value will be read from.
.forGetter() specifies how the value of a field should be read back from our config object. This is useful since codecs allow for both serialization and deserialization, and the getter is required to turn the object back into data. We can use a method reference here since we're using a record.
ExampleGameConfig::new
- This tells the codec how to create the object once all the fields have been deserialized. This requires a method reference to the constructor for the given object with all the fields in order as they were specified!.
- For example, if we passed
Codec.STRING.fieldOf("foo") and then Codec.INT.fieldOf("bar), the constructor would take a (String, int).
- But here we take in one
String field, and the constructor we reference also takes a single String parameter.
The end result of all this Codec work is that when we create a game config, all this data will be automatically parsed from our JSON file and passed to our game code!
Creating a config
Now that we know what data our config should hold, we can create an actual game config JSON for Plasmid to load.
All game configs need to be located in your mod resources (or datapack!) at data/<namespace>/games/<id>.json. For the purpose of a mod, the namespace should just be your mod id, and the id can be any unique name that will later be used to reference your game config from inside Minecraft.
Plasmid requires only 1 JSON field from the config, while the rest is loaded as per the config codec that you set up. There are however also some additional optional fields which may be useful to define. The only required field is the type, which refers to the GameType you created earlier in namespace:path format (e.g. in our case, plasmid_example:example).
For our purposes, our game config at data/plasmid_example/games/hello_world_example.json will look like:
{
"type": "plasmid_example:example",
"greeting": "Hello, World!"
}
We can also add some additional builtin fields to our JSON such as a name, short_name, description, and icon.
This may look like:
{
"type": "plasmid_example:example",
"name": "Hello World Example!",
"description": ["Look at my cool game!", "It greets you when you join."],
"icon": "minecraft:apple"
// ...
}
name and description can also reference translation keys due to being JSON Text Components. For example, this may instead be: "name": {"translation": "game.plasmid_example.hello_world_example"}.
A note on translations
Translations are a bit non-standard in Plasmid due to it being entirely server-side! Usually translations are stored with the game client, and the server simply sends over translation keys which are then turned into relevant readable text on the client-side. Here, however, we need to instead handle translations by changing the packets that get sent to players such that they are correctly translated before the client even receives it. This is a lot of work! Luckily, this is handled by Server Translations, and we do not need to worry about it!
All this actually means for you is that your language files need to go in the data folder instead of the assets folder (e.g. data/<namespace>/lang/en_us.json).
There are some default language keys we should worry about if we're not manually defining a name: gameType.<namespace>.<id> and game.<namespace>.<id>. These keys are applied for game types and game configs respectively. When resolving the readable name for a game config, both the config translation and type translation will be tested, with the type as a fallback. This means only the game type translation is strictly necessary.
For example, we may define our data/plasmid_example/lang/en_us.json as:
{
"gameType.plasmid_example.example": "Plasmid Example!",
"game.plasmid_example.hello_world_example": "Hello World Example!"
}
Writing the code to start our game
Now that we have set up a config and have told Plasmid how to read from it, we can finally write the code to actually start our game.
For the purpose of this example, let's create an ExampleGame class. We will use this class to hold the state of the game as well as our ExampleGameConfig that got loaded. For now though, we just need to create this open function that we referenced to the GameType.
This should look like:
public class ExampleGame {
public static GameOpenProcedure open(GameOpenContext<ExampleGameConfig> context) {
// get our config that got loaded by Plasmid
ExampleGameConfig config = context.config();
// create a very simple map with a stone block at (0; 64; 0)
MapTemplate template = MapTemplate.createEmpty();
template.setBlockState(new BlockPos(0, 64, 0), Blocks.STONE.getDefaultState());
// create a chunk generator that will generate from this template that we just created
TemplateChunkGenerator generator = new TemplateChunkGenerator(context.server(), template);
// set up how the world that this minigame will take place in should be constructed
RuntimeWorldConfig worldConfig = new RuntimeWorldConfig()
.setGenerator(generator)
.setTimeOfDay(6000);
return context.openWithWorld(worldConfig, (activity, world) -> {
// to be implemented
});
}
}
There is a lot to unpack here, but it's not too complex if we break it down. Our open will be called whenever a player starts this game. The function takes a GameOpenContext, which holds the data from our JSON config (context.config()), and must return a GameOpenProcedure, which instructs Plasmid how it should continue to set up the game. It is worth nothing that this function is run asynchronously on the thread pool, so it is safe to run whatever slow code here before the game starts.
The GameOpenProcedure is created from the GameOpenContext.openWithWorld function, and takes in a RuntimeWorldConfig as well as a lambda that accepts a GameActivity and ServerWorld. A runtime world is a concept within Plasmid that represents the fully isolated and temporary world that the game takes place within. It is automatically deleted when the game finishes. When a player joins the game, their inventory will be cleared, and when they leave, it will be restored back to them. A game activity is a specific set of logic that is running within a game: this is what we will configure to change game behaviour. We can switch the activity within a game at any point.
The RuntimeWorldConfig describes how this world should be created. The most important thing to be configured within here is the chunk generator: this tells the game how the world should generate. It would be possible to, for example, pass the overworld chunk generator here, but for our purpose, we're creating an empty world with a single stone block. This is handled through the convenience TemplateChunkGenerator: this takes a MapTemplate, which is just a very basic world that contains some blocks! The generator then loads from that into the world itself.
Finally, we need to address what to do in the lambda with the GameActivity parameter. The code inside this lambda will run on the main server thread, and is used to run the actual game setup code. This mainly involves registering event listeners, or setting global rules.
Event tip: we make use of Stimuli for handling many events in games, so any event from there can be used within Plasmid.
For example:
return context.openWithWorld(worldConfig, (activity, world) -> {
activity.deny(GameRuleType.FALL_DAMAGE);
activity.listen(GamePlayerEvents.ADD, player -> {
// a player has been added!
});
});
This code will disable fall damage for all players, as well as registering an event listener that will be called whenever a player is added to this game.
However! Before we give functionality to our brilliant example game, we need to respond to the player offer event listener. This is called before any player joins the game, and is able to accept or reject that join request. Most critically, the listener defines how and where the player should be spawned into our game world.
An example offer listener may look like:
activity.listen(GamePlayerEvents.OFFER, offer -> {
ServerPlayerEntity player = offer.player();
return offer.accept(world, new Vec3d(0.0, 64.0, 0.0))
.and(() -> {
player.changeGameMode(GameMode.ADVENTURE);
});
});
That's a lot! Let's break it down:
- We register a listener for
GamePlayerEvents.OFFER which takes an offer parameter.
- We get the player instance who is trying to join from the offer.
- We call
offer.accept(...) to accept the player into the game.
- We pass the accept function a world and a position for the player to be teleported to. The world was passed to us above by Plasmid!
- We then call
.and(...) on the result of .accept(...) in order to attach some additional spawn logic to be run when the player joins. In this case, that is to set the player's game mode to adventure mode as they join.
Now that we have that set up, we can return to our player add listener: as of right now, we're not doing anything when it is called. We want it to send a greeting to the player when they join. Let's implement that:
GameSpace gameSpace = activity.getGameSpace();
activity.listen(GamePlayerEvents.ADD, player -> {
LiteralText message = new LiteralText(config.greeting);
gameSpace.getPlayers().sendMessage(message);
});
So we've added logic to send a message within the listener, but what is a GameSpace? A GameSpace is a concept introduced by Plasmid which, as the name implies, represents the space within which a game is occurring. For all our purposes, that space is just this one dimension that the game is playing within. The GameSpace is useful for us in that it keeps track of all the players within it, as well as the ServerWorld that the game is taking place within. Here, we access the GameSpace through GameActivity.getGameSpace().
Working with players additionally goes through a different Plasmid API: a PlayerSet. A PlayerSet represents just a list of players, and it can be iterated over or queried, but additionally provides utilities for performing bulk operations over many players. For example, sending a message! Here, we use PlayerSet.sendMessage() to send our greeting to every player within the game.
Tada! ? We have a working game! But before we test it, let's do some minor reorganization. With all these handlers and lambdas, our code inside createOpenProcedure is going to get quite lengthy very quickly! It would be nice if we can put all event listeners on our ExampleGame object instead.
Turns out, that works just fine, and we are left with our final ExampleGame setup:
public final class ExampleGame {
private final ExampleGameConfig config;
private final GameSpace gameSpace;
private final ServerWorld world;
public ExampleGame(ExampleGameConfig config, GameSpace gameSpace, ServerWorld world) {
this.config = config;
this.gameSpace = gameSpace;
this.world = world;
}
public static GameOpenProcedure open(GameOpenContext<ExampleGameConfig> context) {
// get our config that got loaded by Plasmid
ExampleGameConfig config = context.config();
// create a very simple map with a stone block at (0; 64; 0)
MapTemplate template = MapTemplate.createEmpty();
template.setBlockState(new BlockPos(0, 64, 0), Blocks.STONE.getDefaultState());
// create a chunk generator that will generate from this template that we just created
TemplateChunkGenerator generator = new TemplateChunkGenerator(context.server(), template);
// set up how the world that this minigame will take place in should be constructed
RuntimeWorldConfig worldConfig = new RuntimeWorldConfig()
.setGenerator(generator)
.setTimeOfDay(6000);
return context.openWithWorld(worldConfig, (activity, world) -> {
ExampleGame game = new ExampleGame(config, activity.getGameSpace(), world);
activity.deny(GameRuleType.FALL_DAMAGE);
activity.listen(GamePlayerEvents.OFFER, game::onPlayerOffer);
activity.listen(GamePlayerEvents.ADD, game::onPlayerAdd);
});
}
private PlayerOfferResult onPlayerOffer(PlayerOffer offer) {
ServerPlayerEntity player = offer.player();
return offer.accept(this.world, new Vec3d(0.0, 64.0, 0.0))
.and(() -> {
player.changeGameMode(GameMode.ADVENTURE);
});
}
private void onPlayerAdd(ServerPlayerEntity player) {
LiteralText message = new LiteralText(this.config.greeting);
this.gameSpace.getPlayers().sendMessage(message);
}
}
Testing the game!
Once everything compiles, we can finally launch up Minecraft. If our GameType is all correctly set up and game config JSON in place, once opening a world, we should be able to start our game by running: /game open <id>. (Remember, this is referencing the name of the JSON file and not the GameType!)
So in our case: /game open plasmid_example:hello_world_example
...and we should be joined into our void world with a stone block with a lovely greeting!
Now, any other player can join us too by running /game join or clicking the link that shows up in chat.
That's it! ?
评论 0
登录后参与评分
还没有评论,来抢沙发吧