mm_os
Version:
MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。
137 lines (113 loc) • 3.71 kB
JavaScript
/**
* 玩家进入频道
* @param {string} player_id 玩家ID
* @param {number} channel_id 频道ID
* @returns {boolean} 是否进入成功
*/
Zone.prototype.enterChannel = async function (player_id, channel_id) {
// 参数校验
if (!player_id || typeof player_id !== 'string') {
throw new TypeError('玩家ID必须是有效字符串');
}
if (!channel_id || typeof channel_id !== 'number') {
throw new TypeError('频道ID必须是有效数字');
}
// 获取玩家对象
var player = this.getPlayer(player_id);
// 检查频道是否存在
if (!this.channel.has(channel_id)) {
throw new Error(`频道 ${channel_id} 不存在`);
}
// 如果玩家已在其他频道,先退出
if (player.channel_id && this.channel.get(player.channel_id)) {
await this.channel.get(player.channel_id).leave(player_id);
}
// 玩家进入频道
await this.channel.get(channel_id).enter(player_id);
// 更新玩家频道ID
player.channel_id = channel_id;
return true;
};
/**
* 切换频道
* @param {string} player_id 玩家ID
* @param {number} channel_id 频道ID
* @returns {boolean} 是否切换成功
*/
Zone.prototype.switchChannel = async function (player_id, channel_id) {
// 参数校验
if (!player_id || typeof player_id !== 'string') {
throw new TypeError('玩家ID必须是有效字符串');
}
if (!channel_id || typeof channel_id !== 'number') {
throw new TypeError('频道ID必须是有效数字');
}
// 获取玩家对象
var player = this.getPlayer(player_id);
// 检查目标频道是否存在
if (!this.channel[channel_id]) {
throw new Error(`频道 ${channel_id} 不存在`);
}
// 如果玩家已在目标频道,直接返回
if (player.channel_id === channel_id) {
return true;
}
// 退出当前频道
if (player.channel_id && this.channel.get(player.channel_id)) {
await this.channel.get(player.channel_id).leave(player_id);
}
// 进入目标频道
await this.channel.get(channel_id).enter(player_id);
// 更新玩家频道ID
player.channel_id = channel_id;
return true;
};
/**
* 频道数据发送
* @param {number} channel_id 频道ID
* @param {object} data 发送数据
* @param {string} msg_type 消息类型
* @param {string} msg_group 消息范围
* @param {string} sender_id 发送者ID
* @returns {object} 发送结果
*/
Zone.prototype.sendToChannel = async function (channel_id, data, msg_type = 'text', msg_group = 'channel', sender_id = 'system') {
// 参数校验
if (!channel_id || typeof channel_id !== 'number') {
throw new TypeError('频道ID必须是有效数字');
}
if (!data || typeof data !== 'object') {
throw new TypeError('发送数据必须是有效对象');
}
try {
// 检查频道是否存在
var channel = this.channel.get(channel_id);
if (!channel) {
throw new Error(`频道 ${channel_id} 不存在`);
}
// 创建发送对象
var send_obj = {
data: data,
msg_type: msg_type,
msg_group: msg_group,
sender_id: sender_id,
timestamp: Date.now(),
channel_id: channel_id,
zone_name: this.config.name,
msg_id: this._generateMsgId()
};
// 触发频道数据发送事件,由业务层处理具体的发送逻辑
this.emitEvent('channel_send', {
...send_obj
});
return {
players: channel.getPlayerNum(),
success: 0,
fail: 0,
failed_players: []
};
} catch (error) {
this.log('error', `频道数据发送失败: `, error);
throw error;
}
};