UNPKG

mm_os

Version:

MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。

137 lines (126 loc) 3.35 kB
const { Drive } = require('mm_machine'); const { GameWorld } = require('./world.js'); /** * 游戏 */ class Game extends Drive { static config = { name: 'default', // 世界类型 可选值:角色扮演RPG、动作游戏ACT、冒险游戏AVG、AAG、SLG、SRPG、RTS、FTG、STG、FPS、TPS、PZL、SPG、RCG(RAC)、CAG、TAB、MSC、WAG、MUD、MOBA type: 'RPG', }; /** * 构造函数 * @param {object} config 配置参数 * @param {object} parent 父对象 */ constructor(config, parent) { super({ ...Game.config, ...config || {} }, parent); // // 世界列表 // this._worlds = new Map(); } } /** * 初始化游戏 * @param {object} server 游戏服务器 * @param {object} eventer 事件管理器 * @param {object} logger 日志管理器 */ Game.prototype._initCore = async function (server, eventer, logger) { if (logger) { this.setLogger(logger); } if (eventer) { this.getEventer = function () { return eventer; }; } if (!server) { throw new TypeError('游戏服务器不能为空'); } else { this.getServer = function () { return server; }; } }; /** * 创建世界 * @param {object} config 世界配置 * @param {string} world_id 世界ID * @returns {object} 创建的世界对象 */ Game.prototype.createWorld = async function (config, world_id) { // 参数校验 if (!config.name) { throw new TypeError('世界配置必须包含名称'); } let world = new GameWorld(config, this); world.world_id = world_id; await world.do('init', this._channel, this.getEventer(), this.getLogger()); this._worlds.set(world.world_id, world); return world; }; /** * 获取世界 * @param {string} world_id 世界ID * @returns {object} 世界对象 */ Game.prototype.get = function (world_id) { return this._worlds.get(world_id); }; /** * 创建主城世界 * @param {object} config 世界配置 * @returns {object} 游戏世界对象 */ Game.prototype._createMainWorld = async function (config = {}) { var world = await this.createWorld({ name: 'main_world', title: '主城世界', type: 'safe', max_players: this.config.max_players || 5000, ...config }); this._channel.main_world_id = world.world_id; return world; }; /** * 获取世界 * @param {string} world_id 世界ID * @returns {object} 世界对象 */ Game.prototype.getById = function (world_id) { return this._worlds.get(world_id); }; /** * 进入世界 * @param {string} world_id 世界ID * @param {string} player_id 玩家ID * @returns {object} 世界对象 * @throws {Error} 进入世界失败时抛出 */ Game.prototype.enter = function (world_id, player_id) { let game = this.getById(world_id); if (!game) { throw new Error(`${world_id} 不存在`); } game.enter(player_id); return game; }; /** * 根据世界名称获取世界对象 * @param {string} name 世界名称 * @returns {object|null} 世界对象,如果不存在则返回null */ Game.prototype.getByName = function (name) { for (let game of this._worlds.values()) { if (game.config.name === name) { return game; } } return null; }; module.exports = { Game };