快速上手多人游戏服务器开发。后续会基于 Google Agones,更新相关 K8S 运维、大规模快速扩展专用游戏服务器的文章。拥抱️原生 Cloud-Native!

系列

状态处理

Colyseus 中,room handlers有状态(stateful) 的。每个房间都有自己的状态。状态的突变会自动同步到所有连接的客户端。

序列化方法

  • Schema (default)

状态同步时

  • user 成功加入 room 后,他将从服务器接收到完整状态。
  • 在每个 patchRate 处,状态的二进制补丁会发送到每个客户端(默认值为50ms
  • 从服务器接收到每个补丁后,在客户端调用 onStateChange
  • 每种序列化方法都有自己处理传入状态补丁的特殊方式。

Schema

SchemaSerializer 是从 Colyseus 0.10 开始引入的,它是默认的序列化方法。

Schema 结构只用于房间的状态(可同步数据)。对于不能同步的算法中的数据,您需要使用 Schema 及其其他结构。

服务端

要使用 SchemaSerializer,你必须:

  • 有一个扩展 Schema 类的状态类
  • @type() 装饰器注释你所有的可同步属性
  • 为您的房间实例化状态(this.setState(new MyState()))
  1. import { Schema, type } from "@colyseus/schema";
  2. class MyState extends Schema {
  3. @type("string")
  4. currentTurn: string;
  5. }

原始类型

这些是您可以为 @type() 装饰器提供的类型及其限制。

如果您确切地知道 number 属性的范围,您可以通过为其提供正确的原始类型来优化序列化。

否则,请使用 "number",它将在序列化过程中添加一个额外的字节来标识自己。

Type Description Limitation
"string" utf8 strings maximum byte size of 4294967295
"number" auto-detects the int or float type to be used. (adds an extra byte on output) 0 to 18446744073709551615
"boolean" true or false 0 or 1
"int8" signed 8-bit integer -128 to 127
"uint8" unsigned 8-bit integer 0 to 255
"int16" signed 16-bit integer -32768 to 32767
"uint16" unsigned 16-bit integer 0 to 65535
"int32" signed 32-bit integer -2147483648 to 2147483647
"uint32" unsigned 32-bit integer 0 to 4294967295
"int64" signed 64-bit integer -9223372036854775808 to 9223372036854775807
"uint64" unsigned 64-bit integer 0 to 18446744073709551615
"float32" single-precision floating-point number -3.40282347e+38 to 3.40282347e+38
"float64" double-precision floating-point number -1.7976931348623157e+308 to 1.7976931348623157e+308

子 schema 属性

您可以在 "root" 状态定义中定义更多自定义数据类型,如直接引用(direct reference)、映射(map)或数组(array)。

  1. import { Schema, type } from "@colyseus/schema";
  2. class World extends Schema {
  3. @type("number")
  4. width: number;
  5. @type("number")
  6. height: number;
  7. @type("number")
  8. items: number = 10;
  9. }
  10. class MyState extends Schema {
  11. @type(World)
  12. world: World = new World();
  13. }

ArraySchema

ArraySchema 是内置 JavaScript Array 类型的可同步版本。

可以从数组中使用更多的方法。看看数组的 MDN 文档

示例:自定义 Schema 类型的数组

  1. import { Schema, ArraySchema, type } from "@colyseus/schema";
  2. class Block extends Schema {
  3. @type("number")
  4. x: number;
  5. @type("number")
  6. y: number;
  7. }
  8. class MyState extends Schema {
  9. @type([ Block ])
  10. blocks = new ArraySchema<Block>();
  11. }

示例:基本类型的数组

您不能在数组内混合类型。

  1. import { Schema, ArraySchema, type } from "@colyseus/schema";
  2. class MyState extends Schema {
  3. @type([ "string" ])
  4. animals = new ArraySchema<string>();
  5. }

array.push()

在数组的末尾添加一个或多个元素,并返回该数组的新长度。

  1. const animals = new ArraySchema<string>();
  2. animals.push("pigs", "goats");
  3. animals.push("sheeps");
  4. animals.push("cows");
  5. // output: 4

array.pop()

从数组中删除最后一个元素并返回该元素。此方法更改数组的长度。

  1. animals.pop();
  2. // output: "cows"
  3. animals.length
  4. // output: 3

array.shift()

从数组中删除第一个元素并返回被删除的元素。这个方法改变数组的长度。

  1. animals.shift();
  2. // output: "pigs"
  3. animals.length
  4. // output: 2

array.unshift()

将一个或多个元素添加到数组的开头,并返回数组的新长度。

  1. animals.unshift("pigeon");
  2. // output: 3

array.indexOf()

返回给定元素在数组中的第一个下标,如果不存在则返回 -1

  1. const itemIndex = animals.indexOf("sheeps");

array.splice()

通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。

  1. // find the index of the item you'd like to remove
  2. const itemIndex = animals.findIndex((animal) => animal === "sheeps");
  3. // remove it!
  4. animals.splice(itemIndex, 1);

array.forEach()

迭代数组中的每个元素。

  1. this.state.array1 = new ArraySchema<string>('a', 'b', 'c');
  2. this.state.array1.forEach(element => {
  3. console.log(element);
  4. });
  5. // output: "a"
  6. // output: "b"
  7. // output: "c"

MapSchema

MapSchema 是内置 JavaScript Map 类型的一个可同步版本。

建议使用 MapsID 跟踪您的游戏实体(entities),例如玩家(players),敌人(enemies)等。

"目前仅支持字符串 key":目前,MapSchema 只允许您提供值类型。key 类型总是 string

  1. import { Schema, MapSchema, type } from "@colyseus/schema";
  2. class Player extends Schema {
  3. @type("number")
  4. x: number;
  5. @type("number")
  6. y: number;
  7. }
  8. class MyState extends Schema {
  9. @type({ map: Player })
  10. players = new MapSchema<Player>();
  11. }

map.get()

通过 key 获取一个 map 条目:

  1. const map = new MapSchema<string>();
  2. const item = map.get("key");

OR

  1. //
  2. // NOT RECOMMENDED
  3. //
  4. // This is a compatibility layer with previous versions of @colyseus/schema
  5. // This is going to be deprecated in the future.
  6. //
  7. const item = map["key"];

map.set()

key 设置 map 项:

  1. const map = new MapSchema<string>();
  2. map.set("key", "value");

OR

  1. //
  2. // NOT RECOMMENDED
  3. //
  4. // This is a compatibility layer with previous versions of @colyseus/schema
  5. // This is going to be deprecated in the future.
  6. //
  7. map["key"] = "value";

map.delete()

key 删除一个 map 项:

  1. map.delete("key");

OR

  1. //
  2. // NOT RECOMMENDED
  3. //
  4. // This is a compatibility layer with previous versions of @colyseus/schema
  5. // This is going to be deprecated in the future.
  6. //
  7. delete map["key"];

map.size

返回 MapSchema 对象中的元素数量。

  1. const map = new MapSchema<number>();
  2. map.set("one", 1);
  3. map.set("two", 2);
  4. console.log(map.size);
  5. // output: 2

map.forEach()

按插入顺序遍历 map 的每个 key/value 对。

  1. this.state.players.forEach((value, key) => {
  2. console.log("key =>", key)
  3. console.log("value =>", value)
  4. });

"所有 Map 方法":您可以从 Maps 中使用更多的方法。看一看 MDN 文档的 Maps

CollectionSchema

"CollectionSchema 仅用 JavaScript 实现":目前为止,CollectionSchema 只能用于 JavaScript。目前还不支持 Haxec#LUAc++ 客户端。

CollectionSchemaArraySchema 的工作方式相似,但需要注意的是您无法控制其索引。

  1. import { Schema, CollectionSchema, type } from "@colyseus/schema";
  2. class Item extends Schema {
  3. @type("number")
  4. damage: number;
  5. }
  6. class Player extends Schema {
  7. @type({ collection: Item })
  8. items = new CollectionSchema<Item>();
  9. }

collection.add()

item 追加到 CollectionSchema 对象。

  1. const collection = new CollectionSchema<number>();
  2. collection.add(1);
  3. collection.add(2);
  4. collection.add(3);

collection.at()

获取位于指定 index 处的 item

  1. const collection = new CollectionSchema<string>();
  2. collection.add("one");
  3. collection.add("two");
  4. collection.add("three");
  5. collection.at(1);
  6. // output: "two"

collection.delete()

根据 item 的值删除 item

  1. collection.delete("three");

collection.has()

返回一个布尔值,无论该 item 是否存在于 set 中。

  1. if (collection.has("two")) {
  2. console.log("Exists!");
  3. } else {
  4. console.log("Does not exist!");
  5. }

collection.size

返回 CollectionSchema 对象中的元素数量。

  1. const collection = new CollectionSchema<number>();
  2. collection.add(10);
  3. collection.add(20);
  4. collection.add(30);
  5. console.log(collection.size);
  6. // output: 3

collection.forEach()

对于 CollectionSchema 对象中的每个 index/value 对,forEach() 方法按插入顺序执行所提供的函数一次。

  1. collection.forEach((value, at) => {
  2. console.log("at =>", at)
  3. console.log("value =>", value)
  4. });

SetSchema

"SetSchema 只在 JavaScript 中实现":SetSchema 目前只能在 JavaScript 中使用。目前还不支持 HaxeC#LUAC++ 客户端。

SetSchema 是内置 JavaScript Set 类型的可同步版本。

"更多":你可以从 Sets 中使用更多的方法。看一下 MDN 文档的 Sets

SetSchema 的用法与 [CollectionSchema] 非常相似,最大的区别是 Sets 保持唯一的值。Sets 没有直接访问值的方法。(如collection.at())

  1. import { Schema, SetSchema, type } from "@colyseus/schema";
  2. class Effect extends Schema {
  3. @type("number")
  4. radius: number;
  5. }
  6. class Player extends Schema {
  7. @type({ set: Effect })
  8. effects = new SetSchema<Effect>();
  9. }

set.add()

SetSchema 对象追加一个 item

  1. const set = new CollectionSchema<number>();
  2. set.add(1);
  3. set.add(2);
  4. set.add(3);

set.at()

获取位于指定 index 处的项。

  1. const set = new CollectionSchema<string>();
  2. set.add("one");
  3. set.add("two");
  4. set.add("three");
  5. set.at(1);
  6. // output: "two"

set.delete()

根据项的值删除项。

  1. set.delete("three");

set.has()

返回一个布尔值,无论该项是否存在于集合中。

  1. if (set.has("two")) {
  2. console.log("Exists!");
  3. } else {
  4. console.log("Does not exist!");
  5. }

set.size

返回 SetSchema 对象中的元素数量。

  1. const set = new SetSchema<number>();
  2. set.add(10);
  3. set.add(20);
  4. set.add(30);
  5. console.log(set.size);
  6. // output: 3

过滤每个客户端的数据

"这个特性是实验性的":@filter()/@filterChildren() 是实验性的,可能无法针对快节奏的游戏进行优化。

过滤旨在为特定客户端隐藏状态的某些部分,以避免在玩家决定检查来自网络的数据并查看未过滤状态信息的情况下作弊。

数据过滤器是每个客户端每个字段(或每个子结构,在 @filterChildren 的情况下)都会触发的回调。如果过滤器回调返回 true,字段数据将为该特定客户端发送,否则,数据将不为该客户端发送。

请注意,如果过滤函数的依赖关系发生变化,它不会自动重新运行,但只有在过滤字段(或其子字段)被更新时才会重新运行。请参阅此问题以了解解决方法。

@filter() property decorator

@filter() 属性装饰器可以用来过滤掉整个 Schema 字段。

下面是 @filter() 签名的样子:

  1. class State extends Schema {
  2. @filter(function(client, value, root) {
  3. // client is:
  4. //
  5. // the current client that's going to receive this data. you may use its
  6. // client.sessionId, or other information to decide whether this value is
  7. // going to be synched or not.
  8. // value is:
  9. // the value of the field @filter() is being applied to
  10. // root is:
  11. // the root instance of your room state. you may use it to access other
  12. // structures in the process of decision whether this value is going to be
  13. // synched or not.
  14. })
  15. @type("string") field: string;
  16. }

@filterChildren() 属性装饰器

@filterChildren() 属性装饰器可以用来过滤出 arraysmapssets 等内部的项。它的签名与 @filter() 非常相似,只是在 value 之前增加了 key 参数 — 表示 ArraySchemaMapSchemaCollectionSchema 等中的每一项。

  1. class State extends Schema {
  2. @filterChildren(function(client, key, value, root) {
  3. // client is:
  4. //
  5. // the current client that's going to receive this data. you may use its
  6. // client.sessionId, or other information to decide whether this value is
  7. // going to be synched or not.
  8. // key is:
  9. // the key of the current value inside the structure
  10. // value is:
  11. // the current value inside the structure
  12. // root is:
  13. // the root instance of your room state. you may use it to access other
  14. // structures in the process of decision whether this value is going to be
  15. // synched or not.
  16. })
  17. @type([Cards]) cards = new ArraySchema<Card>();
  18. }

例子: 在一场纸牌游戏中,每张纸牌的相关资料只应供纸牌拥有者使用,或在某些情况下(例如纸牌已被丢弃)才可使用。

查看 @filter() 回调签名:

  1. import { Client } from "colyseus";
  2. class Card extends Schema {
  3. @type("string") owner: string; // contains the sessionId of Card owner
  4. @type("boolean") discarded: boolean = false;
  5. /**
  6. * DO NOT USE ARROW FUNCTION INSIDE `@filter`
  7. * (IT WILL FORCE A DIFFERENT `this` SCOPE)
  8. */
  9. @filter(function(
  10. this: Card, // the instance of the class `@filter` has been defined (instance of `Card`)
  11. client: Client, // the Room's `client` instance which this data is going to be filtered to
  12. value: Card['number'], // the value of the field to be filtered. (value of `number` field)
  13. root: Schema // the root state Schema instance
  14. ) {
  15. return this.discarded || this.owner === client.sessionId;
  16. })
  17. @type("uint8") number: number;
  18. }

向后/向前兼容性

向后/向前兼容性可以通过在现有结构的末尾声明新的字段来实现,以前的声明不被删除,但在需要时被标记为 @deprecated()

这对于原生编译的目标特别有用,比如 C#, C++, Haxe 等 — 在这些目标中,客户端可能没有最新版本的 schema 定义。

限制和最佳实践

  • 每个 Schema 结构最多可以容纳 64 个字段。如果需要更多字段,请使用嵌套的 Schema 结构。
  • NaNnull 数字被编码为 0
  • null 字符串被编码为 ""
  • Infinity 被编码为 Number.MAX_SAFE_INTEGER 的数字。
  • 不支持多维数组。了解如何将一维数组用作多维数组
  • ArraysMaps 中的项必须都是同一类型的实例。
  • @colyseus/schema 只按照指定的顺序编码字段值。
    • encoder(服务器)和decoder(客户端)必须有相同的 schema 定义。
    • 字段的顺序必须相同。

客户端

Callbacks

您可以在客户端 schema 结构中使用以下回调来处理来自服务器端的更改。

  • onAdd (instance, key)
  • onRemove (instance, key)
  • onChange (changes) (on Schema instance)
  • onChange (instance, key) (on collections: MapSchema, ArraySchema, etc.)
  • listen()

"C#, C++, Haxe":当使用静态类型语言时,需要根据 TypeScript schema 定义生成客户端 schema 文件。参见在客户端生成 schema

onAdd (instance, key)

onAdd 回调只能在 maps (MapSchema)和数组(ArraySchema)中使用。调用 onAdd 回调函数时,会使用添加的实例及其 holder 对象上的 key 作为参数。

  1. room.state.players.onAdd = (player, key) => {
  2. console.log(player, "has been added at", key);
  3. // add your player entity to the game world!
  4. // If you want to track changes on a child object inside a map, this is a common pattern:
  5. player.onChange = function(changes) {
  6. changes.forEach(change => {
  7. console.log(change.field);
  8. console.log(change.value);
  9. console.log(change.previousValue);
  10. })
  11. };
  12. // force "onChange" to be called immediatelly
  13. player.triggerAll();
  14. };

onRemove (instance, key)

onRemove 回调只能在 maps (MapSchema) 和 arrays (ArraySchema) 中使用。调用 onRemove 回调函数时,会使用被删除的实例及其 holder 对象上的 key 作为参数。

  1. room.state.players.onRemove = (player, key) => {
  2. console.log(player, "has been removed at", key);
  3. // remove your player entity from the game world!
  4. };

onChange (changes: DataChange[])

onChange 对于直接 Schema 引用和集合结构的工作方式不同。关于集合结构 (array,map 等)的 onChange,请点击这里

您可以注册 onChange 来跟踪 Schema 实例的属性更改。onChange 回调是由一组更改过的属性以及之前的值触发的。

  1. room.state.onChange = (changes) => {
  2. changes.forEach(change => {
  3. console.log(change.field);
  4. console.log(change.value);
  5. console.log(change.previousValue);
  6. });
  7. };

你不能在未与客户端同步的对象上注册 onChange 回调。


onChange (instance, key)

onChange 对于直接 Schema 引用和 collection structures 的工作方式不同。

每当 primitive 类型(string, number, boolean等)的集合更新它的一些值时,这个回调就会被触发。

  1. room.state.players.onChange = (player, key) => {
  2. console.log(player, "have changes at", key);
  3. };

如果您希望检测 non-primitive 类型(包含 Schema 实例)集合中的更改,请使用onAdd 并在它们上注册 onChange

"onChangeonAddonRemoveexclusive(独占) 的":

onAddonRemove 期间不会触发 onChange 回调。

  1. 如果在这些步骤中还需要检测更改,请考虑注册 `onAdd` `onRemove`

.listen(prop, callback)

监听单个属性更改。

.listen() 目前只适用于 JavaScript/TypeScript

参数:

  • property: 您想要监听更改的属性名。
  • callback: 当 property 改变时将被触发的回调。
  1. state.listen("currentTurn", (currentValue, previousValue) => {
  2. console.log(`currentTurn is now ${currentValue}`);
  3. console.log(`previous value was: ${previousValue}`);
  4. });

.listen() 方法返回一个用于注销监听器的函数:

  1. const removeListener = state.listen("currentTurn", (currentValue, previousValue) => {
  2. // ...
  3. });
  4. // later on, if you don't need the listener anymore, you can call `removeListener()` to stop listening for `"currentTurn"` changes.
  5. removeListener();

listenonChange 的区别是什么?

.listen() 方法是单个属性上的 onChange 的简写。下面是

  1. state.onChange = function(changes) {
  2. changes.forEach((change) => {
  3. if (change.field === "currentTurn") {
  4. console.log(`currentTurn is now ${change.value}`);
  5. console.log(`previous value was: ${change.previousValue}`);
  6. }
  7. })
  8. }

客户端 schema 生成

这只适用于使用静态类型语言(如 C#、C++ 或 Haxe)的情况。

在服务器项目中,可以运行 npx schema-codegen 自动生成客户端 schema 文件。

  1. npx schema-codegen --help

输出:

  1. schema-codegen [path/to/Schema.ts]
  2. Usage (C#/Unity)
  3. schema-codegen src/Schema.ts --output client-side/ --csharp --namespace MyGame.Schema
  4. Valid options:
  5. --output: fhe output directory for generated client-side schema files
  6. --csharp: generate for C#/Unity
  7. --cpp: generate for C++
  8. --haxe: generate for Haxe
  9. --ts: generate for TypeScript
  10. --js: generate for JavaScript
  11. --java: generate for Java
  12. Optional:
  13. --namespace: generate namespace on output code

Built-in room » Lobby Room

"大厅房间的客户端 API 将在 Colyseus 1.0.0 上更改":

  • 内置的大厅房间目前依赖于发送消息来通知客户可用的房间。当 @filter() 变得稳定时,LobbyRoom 将使用 state 代替。

服务器端

内置的 LobbyRoom 将自动通知其连接的客户端,每当房间 "realtime listing" 有更新。

  1. import { LobbyRoom } from "colyseus";
  2. // Expose the "lobby" room.
  3. gameServer
  4. .define("lobby", LobbyRoom);
  5. // Expose your game room with realtime listing enabled.
  6. gameServer
  7. .define("your_game", YourGameRoom)
  8. .enableRealtimeListing();

onCreate()onJoin()onLeave()onDispose() 期间,会自动通知 LobbyRoom

如果你已经更新了你房间的metadata,并且需要触发一个 lobby 的更新,你可以在元数据更新之后调用 updateLobby()

  1. import { Room, updateLobby } from "colyseus";
  2. class YourGameRoom extends Room {
  3. onCreate() {
  4. //
  5. // This is just a demonstration
  6. // on how to call `updateLobby` from your Room
  7. //
  8. this.clock.setTimeout(() => {
  9. this.setMetadata({
  10. customData: "Hello world!"
  11. }).then(() => updateLobby(this));
  12. }, 5000);
  13. }
  14. }

客户端

您需要通过从 LobbyRoom 发送给客户端的信息来跟踪正在添加、删除和更新的房间。

  1. import { Client, RoomAvailable } from "colyseus.js";
  2. const client = new Client("ws://localhost:2567");
  3. const lobby = await client.joinOrCreate("lobby");
  4. let allRooms: RoomAvailable[] = [];
  5. lobby.onMessage("rooms", (rooms) => {
  6. allRooms = rooms;
  7. });
  8. lobby.onMessage("+", ([roomId, room]) => {
  9. const roomIndex = allRooms.findIndex((room) => room.roomId === roomId);
  10. if (roomIndex !== -1) {
  11. allRooms[roomIndex] = room;
  12. } else {
  13. allRooms.push(room);
  14. }
  15. });
  16. lobby.onMessage("-", (roomId) => {
  17. allRooms = allRooms.filter((room) => room.roomId !== roomId);
  18. });

Built-in room » Relay Room

内置的 RelayRoom 对于简单的用例非常有用,在这些用例中,除了连接到它的客户端之外,您不需要在服务器端保存任何状态。

通过简单地中继消息(将消息从客户端转发给其他所有人) — 服务器端不能验证任何消息 — 客户端应该执行验证。

RelayRoom 的源代码非常简单。一般的建议是在您认为合适的时候使用服务器端验证来实现您自己的版本。

服务器端

  1. import { RelayRoom } from "colyseus";
  2. // Expose your relayed room
  3. gameServer.define("your_relayed_room", RelayRoom, {
  4. maxClients: 4,
  5. allowReconnectionTime: 120
  6. });

客户端

请参阅如何注册来自 relayed room 的玩家加入、离开、发送和接收消息的回调。

连接到房间

  1. import { Client } from "colyseus.js";
  2. const client = new Client("ws://localhost:2567");
  3. //
  4. // Join the relayed room
  5. //
  6. const relay = await client.joinOrCreate("your_relayed_room", {
  7. name: "This is my name!"
  8. });

在玩家加入和离开时注册回调

  1. //
  2. // Detect when a player joined the room
  3. //
  4. relay.state.players.onAdd = (player, sessionId) => {
  5. if (relay.sessionId === sessionId) {
  6. console.log("It's me!", player.name);
  7. } else {
  8. console.log("It's an opponent", player.name, sessionId);
  9. }
  10. }
  11. //
  12. // Detect when a player leave the room
  13. //
  14. relay.state.players.onRemove = (player, sessionId) => {
  15. console.log("Opponent left!", player, sessionId);
  16. }
  17. //
  18. // Detect when the connectivity of a player has changed
  19. // (only available if you provided `allowReconnection: true` in the server-side)
  20. //
  21. relay.state.players.onChange = (player, sessionId) => {
  22. if (player.connected) {
  23. console.log("Opponent has reconnected!", player, sessionId);
  24. } else {
  25. console.log("Opponent has disconnected!", player, sessionId);
  26. }
  27. }

发送和接收消息

  1. //
  2. // By sending a message, all other clients will receive it under the same name
  3. // Messages are only sent to other connected clients, never the current one.
  4. //
  5. relay.send("fire", {
  6. x: 100,
  7. y: 200
  8. });
  9. //
  10. // Register a callback for messages you're interested in from other clients.
  11. //
  12. relay.onMessage("fire", ([sessionId, message]) => {
  13. //
  14. // The `sessionId` from who sent the message
  15. //
  16. console.log(sessionId, "sent a message!");
  17. //
  18. // The actual message sent by the other client
  19. //
  20. console.log("fire at", message);
  21. });

Colyseus 的最佳实践

这一部分需要改进和更多的例子!每一段都需要有自己的一页,有详尽的例子和更好的解释。

  • 保持你的 room 类尽可能小,没有游戏逻辑
  • 使可同步的数据结构尽可能小
    • 理想情况下,扩展 Schema 的每个类应该只有字段定义。
    • 自定义 getter 和 setter 方法可以实现,只要它们中没有游戏逻辑。
  • 你的游戏逻辑应该由其他结构来处理,例如:

为什么?

  • Models (@colyseus/schema) 应该只包含数据,不包含游戏逻辑。
  • Rooms 应该有尽可能少的代码,并将动作转发给其他结构

命令模式有几个优点,例如:

  • 它将调用该操作的类与知道如何执行该操作的对象解耦。
  • 它允许你通过提供一个队列系统来创建一个命令序列。
  • 实现扩展来添加一个新的命令很容易,可以在不改变现有代码的情况下完成。
  • 严格控制命令的调用方式和调用时间。
  • 由于命令简化了代码,因此代码更易于使用、理解和测试。

用法

安装

  1. npm install --save @colyseus/command

在您的 room 实现中初始化 dispatcher

  1. import { Room } from "colyseus";
  2. import { Dispatcher } from "@colyseus/command";
  3. import { OnJoinCommand } from "./OnJoinCommand";
  4. class MyRoom extends Room<YourState> {
  5. dispatcher = new Dispatcher(this);
  6. onCreate() {
  7. this.setState(new YourState());
  8. }
  9. onJoin(client, options) {
  10. this.dispatcher.dispatch(new OnJoinCommand(), {
  11. sessionId: client.sessionId
  12. });
  13. }
  14. onDispose() {
  15. this.dispatcher.stop();
  16. }
  17. }
  1. const colyseus = require("colyseus");
  2. const command = require("@colyseus/command");
  3. const OnJoinCommand = require("./OnJoinCommand");
  4. class MyRoom extends colyseus.Room {
  5. onCreate() {
  6. this.dispatcher = new command.Dispatcher(this);
  7. this.setState(new YourState());
  8. }
  9. onJoin(client, options) {
  10. this.dispatcher.dispatch(new OnJoinCommand(), {
  11. sessionId: client.sessionId
  12. });
  13. }
  14. onDispose() {
  15. this.dispatcher.stop();
  16. }
  17. }

命令实现的样子:

  1. // OnJoinCommand.ts
  2. import { Command } from "@colyseus/command";
  3. export class OnJoinCommand extends Command<YourState, {
  4. sessionId: string
  5. }> {
  6. execute({ sessionId }) {
  7. this.state.players[sessionId] = new Player();
  8. }
  9. }
  1. // OnJoinCommand.js
  2. const command = require("@colyseus/command");
  3. exports.OnJoinCommand = class OnJoinCommand extends command.Command {
  4. execute({ sessionId }) {
  5. this.state.players[sessionId] = new Player();
  6. }
  7. }

查看更多

Refs

中文手册同步更新在:

  • https:/colyseus.hacker-linner.com
  1. 我是为少
  2. 微信:uuhells123
  3. 公众号:黑客下午茶
  4. 加我微信(互相学习交流),关注公众号(获取更多学习资料~)

ColyseusJS 轻量级多人游戏服务器开发框架 - 中文手册(下)的更多相关文章

  1. ColyseusJS 轻量级多人游戏服务器开发框架 - 中文手册(中)

    快速上手多人游戏服务器开发.后续会基于 Google Agones,更新相关 K8S 运维.大规模快速扩展专用游戏服务器的文章.拥抱️原生 Cloud-Native! 系列 ColyseusJS 轻量 ...

  2. ColyseusJS 轻量级多人游戏服务器开发框架 - 中文手册(系统保障篇)

    快速上手多人游戏服务器开发.后续会基于 Google Agones,更新相关 K8S 运维.大规模快速扩展专用游戏服务器的文章.拥抱️原生 Cloud-Native! 系列 ColyseusJS 轻量 ...

  3. ColyseusJS 轻量级多人游戏服务器开发框架 - 中文手册(上)

    快速上手多人游戏服务器开发.后续会基于 Google Agones,更新相关 K8S 运维.大规模快速扩展专用游戏服务器的文章.拥抱️原生 Cloud-Native! 快速开始 在开始之前,让我们确保 ...

  4. phpredis中文手册——《redis中文手册》 php版

    本文是参考<redis中文手册>,将示例代码用php来实现,注意php-redis与redis_cli的区别(主要是返回值类型和参数用法). 目录(使用CTRL+F快速查找命令): Key ...

  5. [转]phpredis中文手册

    本文是参考<redis中文手册>,将示例代码用php来实现,注意php-redis与redis_cli的区别(主要是返回值类型和参数用法). 目录(使用CTRL+F快速查找命令): Key ...

  6. man rpcbind(rpcbind中文手册)

    本人译作集合:http://www.cnblogs.com/f-ck-need-u/p/7048359.html RPCBIND() BSD System Manager's Manual RPCBI ...

  7. phpredis中文手册——《redis中文手册》 php版(转)

    redis中文手册:http://readthedocs.org/docs/redis/en/latest/ 本文是参考<redis中文手册>,将示例代码用php来实现,注意php-red ...

  8. Flask 中文手册 0.10 文档

    Flask 中文手册 0.10 文档 欢迎使用 Flask 欢迎阅读 Flask 文档. 本文档分为几个部分.我推荐您先从 安装 开始,之后再浏览 快速入门 章节. 教程 比快速入门更详细地介绍了如何 ...

  9. Dig HOWTO 中文手册--dig命令使用大全

    Dig HOWTO 中文手册--dig命令使用大全 DNS -- 本人翻译的dig howto手册. 译者序: 可以这样说,翻译本篇文档的过程就是我重新学习DNS的过程,dig命令可以帮助我们学习DN ...

随机推荐

  1. java 各种类型转换

    public class TypeConversion { public static void main(String[] args) throws ParseException { // 1.将字 ...

  2. 【python+selenium的web自动化】- 针对上传操作的实现方案

    如果想从头学起selenium,可以去看看这个系列的文章哦! https://www.cnblogs.com/miki-peng/category/1942527.html 关于上传操作 ​ 上传有两 ...

  3. VUE移动端音乐APP学习【四】:scroll组件及loading组件开发

    scroll组件 制作scroll 组件,然后嵌套一个 DOM 节点,使得该节点就能够滚动.该组件中需要引入 BetterScroll 插件. scroll.vue: <template> ...

  4. Java并发编程之多线程

    线程 进程/线程/协程/管程 进程:操作系统会以进程为单位,分配系统资源(CPU时间片.内存等资源),是资源分配的最小单位 进程间通信(IPC): 管道(Pipe) 命名管道(FIFO) 消息队列(M ...

  5. sqli-labs系列——第五关

    less5 更改id后无果,不能用union联合查询 此处用报错注入 报错注入的概念:(1). 通过floor报错 and (select 1 from (select count(*),concat ...

  6. 前端开发:基于cypress的自动化实践

    作为一个伪开发,在一个平台项目中负责前端的开发工作,开发框架为vue,本文我会站在前端开发的角度介绍,我是如何使用cypress的. [x] 如何在vue中使用cypress [x] 如何运行cypr ...

  7. java面试-集合类不安全问题及解决方案

    一.List 1.代码演示 public class ArrayListNotSafeDemo { public static void main(String[] args) { List<S ...

  8. 【CTF】Pwn入门 XCTF 部分writeup

    碎碎念 咕咕咕了好久的Pwn,临时抱佛脚入门一下. 先安利之前看的一个 Reverse+Pwn 讲解视频 讲的还是很不错的,建议耐心看完 另外感觉Reverse和Pwn都好难!! 不,CTF好难!! ...

  9. 自动化kolla-ansible部署ubuntu20.04+openstack-victoria之ceph部署-07

    自动化kolla-ansible部署ubuntu20.04+openstack-victoria之ceph部署-07 欢迎加QQ群:1026880196 进行交流学习 近期我发现网上有人转载或者复制原 ...

  10. JDK8接口新关键字default和static

    JDK8及以后,允许我们在接口中定义static方法和default方法. public interface InterfaceDemo { // static修饰符定义静态方法 static voi ...