feat: 兼容Sponge部分功能

This commit is contained in:
coding 2017-10-30 03:17:42 +00:00
parent c7293370ea
commit e2566c4bf1
24 changed files with 431 additions and 126 deletions

View File

@ -29,7 +29,7 @@ public class MiaoScript extends JavaPlugin implements Executor {
@SneakyThrows @SneakyThrows
public void onEnable() { public void onEnable() {
new CommandSub("ms", this); new CommandSub("ms", this);
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getClassLoader(), getLogger()); engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger());
} }
@Cmd @Cmd

View File

@ -3,10 +3,10 @@ package pw.yumc.MiaoScript;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Logger;
import javax.script.ScriptException; import javax.script.ScriptException;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge; import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.args.GenericArguments;
@ -48,6 +48,7 @@ public class MiaoScriptSponge {
.permission("MiaoScript.admin") .permission("MiaoScript.admin")
.child(js(), "js") .child(js(), "js")
.child(file(), "file") .child(file(), "file")
.child(reload(), "reload")
.build(); .build();
} }
@ -81,11 +82,24 @@ public class MiaoScriptSponge {
.build(); .build();
} }
private CommandSpec reload() {
return CommandSpec.builder()
.description(Text.of("重载 JS 引擎"))
.executor((src, args) -> {
engine.disableEngine();
Sponge.getEventManager().unregisterPluginListeners(this);
engine.enableEngine();
// src.sendMesssage("§6[§bMiaoScript§6]§r §bMiaoScript §eEngine §a重启完成!");
return CommandResult.success();
})
.build();
}
@Listener @Listener
@SneakyThrows @SneakyThrows
public void onStart(GameStartedServerEvent event) { public void onStart(GameStartedServerEvent event) {
Sponge.getServer().getConsole(); Sponge.getServer().getConsole();
Sponge.getCommandManager().register(this, main(), "ms", "mscript", "MiaoScript"); Sponge.getCommandManager().register(this, main(), "ms", "mscript", "MiaoScript");
engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), Thread.currentThread().getContextClassLoader(), logger); engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), logger);
} }
} }

View File

@ -1,9 +1,14 @@
package pw.yumc.MiaoScript; package pw.yumc.MiaoScript;
import java.lang.Thread;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.script.ScriptEngineManager; import javax.script.ScriptEngineManager;
import javax.script.ScriptException; import javax.script.ScriptException;
@ -17,13 +22,11 @@ import pw.yumc.YumCore.engine.MiaoScriptEngine;
*/ */
public class ScriptEngine { public class ScriptEngine {
private String root; private String root;
private ClassLoader classLoader; private Object logger;
private Logger logger;
private MiaoScriptEngine engine; private MiaoScriptEngine engine;
public ScriptEngine(String root, ClassLoader classLoader, Logger logger) { public ScriptEngine(String root, Object logger) {
this.root = root; this.root = root;
this.classLoader = classLoader;
this.logger = logger; this.logger = logger;
enableEngine(); enableEngine();
} }
@ -33,10 +36,16 @@ public class ScriptEngine {
ScriptEngineManager manager = new ScriptEngineManager(null); ScriptEngineManager manager = new ScriptEngineManager(null);
this.engine = new MiaoScriptEngine(manager, "nashorn"); this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base()); this.engine.put("base", new Base());
this.engine.eval(new InputStreamReader(classLoader.getResourceAsStream("bios.js"))); Path bios = Paths.get(root, "bios.js");
// 如果存在自定义bios就加载自定义的
if (Files.exists(bios)) {
this.engine.eval("load('" + bios.toFile().getCanonicalPath() + "')");
} else {
this.engine.eval(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("bios.js")));
}
engine.invokeFunction("boot", root, logger); engine.invokeFunction("boot", root, logger);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, "MiaoScript 启动失败!", e); // logger.log(Level.SEVERE, "MiaoScript 启动失败!", e);
} }
} }
@ -44,7 +53,7 @@ public class ScriptEngine {
try { try {
engine.invokeFunction("disable"); engine.invokeFunction("disable");
} catch (ScriptException | NoSuchMethodException e) { } catch (ScriptException | NoSuchMethodException e) {
logger.log(Level.SEVERE, "MiaoScript 关闭失败!", e); // logger.log(Level.SEVERE, "MiaoScript 关闭失败!", e);
} }
} }

View File

@ -7,6 +7,7 @@ var disable;
*/ */
(function () { (function () {
boot = function (root, logger) { boot = function (root, logger) {
try {
log = logger; log = logger;
// 开发环境下初始化 // 开发环境下初始化
root = root || "src/main/resources"; root = root || "src/main/resources";
@ -14,16 +15,20 @@ var disable;
release(root, "[core|modules]/.*", true); release(root, "[core|modules]/.*", true);
release(root, "plugins/.*"); release(root, "plugins/.*");
load(root + '/core/init.js'); load(root + '/core/init.js');
try { if (__FILE__ !== "<eval>") {
logger.info('载入自定义 BIOS 文件 ' + __FILE__);
global.debug = true;
}
init(root); init(root);
} catch (ex) { } catch (ex) {
if(console.ex){ if (console && console.ex) {
console.ex(ex); console.ex(ex);
}else{ } else {
ex.printStackTrace();
throw ex; throw ex;
} }
} finally { } finally {
disable = disablePlugins disable = disablePlugins;
} }
}; };
@ -34,14 +39,12 @@ var disable;
var classLoader = java.lang.Thread.currentThread().getContextClassLoader(); var classLoader = java.lang.Thread.currentThread().getContextClassLoader();
var url = classLoader.getResource("plugin.yml"); var url = classLoader.getResource("plugin.yml");
if (url === null) { if (url === null) { return; }
return;
}
var upath = url.getFile().substring(url.getFile().indexOf("/") + 1); var upath = url.getFile().substring(url.getFile().indexOf("/") + 1);
var jarPath = java.net.URLDecoder.decode(upath.substring(0, upath.indexOf('!'))); var jarPath = java.net.URLDecoder.decode(upath.substring(0, upath.indexOf('!')));
if (!Files.exists(Paths.get(jarPath))) { if (!Files.exists(Paths.get(jarPath))) { jarPath = "/" + jarPath; }
jarPath = "/" + jarPath;
}
try { try {
var jar = new java.util.jar.JarFile(jarPath); var jar = new java.util.jar.JarFile(jarPath);
var r = new RegExp(regex);// "[core|modules]/.*" var r = new RegExp(regex);// "[core|modules]/.*"

View File

@ -5,66 +5,35 @@
(function (global) { (function (global) {
var Arrays = Java.type('java.util.Arrays'); var Arrays = Java.type('java.util.Arrays');
var Level = Java.type('java.util.logging.Level'); var Level = Java.type('java.util.logging.Level');
var String = Java.type('java.lang.String'); var Console = {
var Console = function (name) { createNew: function(name) {
Object.defineProperty(this, 'name', { var console = {};
Object.defineProperty(console, 'name', {
get: function () { get: function () {
return this._name; return this._name;
}.bind(this), }.bind(console),
set: function (name) { set: function (name) {
this._name = name ? '[' + name + '] ' : ''; this._name = name ? '[' + name + '] ' : '';
this.prefix = name ? '§6[§cMS§6][§b' + name + '§6]§r ' : ''; this.prefix = name ? '§6[§cMS§6][§b' + name + '§6]§r ' : '§6[§bMiaoScript§6]§r ';
}.bind(this) }.bind(console)
}); });
this.name = name; console.name = name;
this.log = function () { console.log = console.info = function () {
log.info(this.name + Array.prototype.join.call(arguments, ' ')); log.info(this.name + Array.prototype.join.call(arguments, ' '));
}; };
this.info = this.log; console.warn = function () {
this.warn = function () {
log.warning(this.name + Array.prototype.join.call(arguments, ' ')); log.warning(this.name + Array.prototype.join.call(arguments, ' '));
}; };
this.error = function () { console.error = function () {
log.log(Level.SEVERE, this.name + Array.prototype.join.call(arguments, ' ')); log.log(Level.SEVERE, this.name + Array.prototype.join.call(arguments, ' '));
}; };
switch (DetectServerType) { console.debug = function () {
case ServerType.Bukkit: log.info(this.name + '[DEBUG] ' + Array.prototype.join.call(arguments, ' '));
this.sender = function () {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) {
console.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(this.prefix + args.join(' '));
}; };
this.console = function () { console.debug = global.debug ? console.debug : global.noop;
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' ')); console.sender = console.info;
}; console.console = console.info;
break; console.ex = function (ex) {
case ServerType.Sponge:
this.sender = function () {
var Text = Java.type("org.spongepowered.api.text.Text");
var sender = arguments[0];
if (!(sender instanceof org.spongepowered.api.command.CommandSource)) {
console.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(this.prefix + args.join(' ')));
};
this.console = function () {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));
};
break;
default:
this.sender = function () {
throw Error("console.sender 不支持的服务器类型: " + DetectServerType);
};
this.console = function () {
throw Error("console.console 不支持的服务器类型: " + DetectServerType);
};
}
this.debug = this.log;
this.ex = function (ex) {
this.console('§4' + ex); this.console('§4' + ex);
var track = ex.getStackTrace(); var track = ex.getStackTrace();
if (track.class) { if (track.class) {
@ -78,7 +47,57 @@
} }
}.bind(this)); }.bind(this));
} }
return console;
}
}
var BukkitConsole = {
createNew: function () {
var console = Console.createNew();
console.sender = function () {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) {
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(console.prefix + args.join(' '));
}; };
console.console = function () {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
};
return console;
}
}
var SpongeConsole = {
createNew: function () {
var console = Console.createNew();
console.sender = function () {
var Text = Java.type("org.spongepowered.api.text.Text");
var sender = arguments[0];
if (!(sender instanceof org.spongepowered.api.command.CommandSource)) {
this.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(console.prefix + args.join(' ')));
};
console.console = function () {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));
};
console.warn = function () {
log.warn(this.name + Array.prototype.join.call(arguments, ' '));
};
return console;
}
}
switch (DetectServerType) {
case ServerType.Bukkit:
global.Console = BukkitConsole;
break;
case ServerType.Sponge:
global.Console = SpongeConsole;
break;
default:
global.Console = Console; global.Console = Console;
global.console = new Console(); break;
}
global.console = global.Console.createNew();
})(global); })(global);

View File

@ -3,8 +3,8 @@
*/ */
/*global base*/ /*global base*/
var ServerType = { var ServerType = {
Bukkit: 1, Bukkit: 'bukkit',
Sponge: 2 Sponge: 'sponge'
}; };
var MServer; var MServer;
var DetectServerType = ServerType.Bukkit; var DetectServerType = ServerType.Bukkit;

View File

@ -4,11 +4,12 @@ var global = this;
// noinspection JSUnusedLocalSymbols // noinspection JSUnusedLocalSymbols
function init(root) { function init(root) {
log.info('Init MiaoScript System...');
global.root = root; global.root = root;
loadCore(); loadCore();
loadRequire(); loadRequire();
loadPatch(); loadPatch();
loadLib4Bukkit(); loadServerLib();
loadPlugins(); loadPlugins();
} }
@ -16,9 +17,12 @@ function init(root) {
* 初始化核心 * 初始化核心
*/ */
function loadCore() { function loadCore() {
global.noop = function () {};
// 加载基础模块 // 加载基础模块
load(root + '/core/ext.js'); load(root + '/core/ext.js');
// 探测服务器类型
load(root + '/core/detect.js'); load(root + '/core/detect.js');
// 加载Console
load(root + '/core/console.js'); load(root + '/core/console.js');
} }
@ -41,8 +45,7 @@ function loadPatch() {
/** /**
* 加载Bukkit的类库 * 加载Bukkit的类库
*/ */
function loadLib4Bukkit() { function loadServerLib() {
require('modules/event');
var task = require('modules/task'); var task = require('modules/task');
global.setTimeout = function (func, time, _async) { global.setTimeout = function (func, time, _async) {
return _async ? task.laterAsync(func, time) : task.later(func, time); return _async ? task.laterAsync(func, time) : task.later(func, time);
@ -64,11 +67,13 @@ function loadLib4Bukkit() {
function loadPlugins() { function loadPlugins() {
// 初始化本体插件 // 初始化本体插件
global.manager = require('modules/plugin'); global.manager = require('modules/plugin');
if (manager) {
manager.init('plugins'); manager.init('plugins');
// 只有当在正式环境运行的时候才加载 // 只有当在正式环境运行的时候才加载
if (manager.$) {
manager.load(); manager.load();
manager.enable(); manager.enable();
} else {
console.console('§4当前服务器不支持使用MiaoScript插件系统!');
} }
} }

View File

@ -20,9 +20,7 @@
* @param parent 父目录 * @param parent 父目录
*/ */
function resolve(name, parent) { function resolve(name, parent) {
if (_canonical(name)) { name = _canonical(name) || name;
name = _canonical(name);
}
// 解析本地目录 // 解析本地目录
if (name.startsWith('./') || name.startsWith('../')) { if (name.startsWith('./') || name.startsWith('../')) {
return resolveAsFile(parent, name) || resolveAsDirectory(parent, name) || undefined; return resolveAsFile(parent, name) || resolveAsDirectory(parent, name) || undefined;

View File

@ -59,13 +59,13 @@ function register(jsp, cmd) {
function on(jsp, name, exec) { function on(jsp, name, exec) {
var c = get(name) || create(jsp, name); var c = get(name) || create(jsp, name);
console.debug('插件 %s 设置命令 %s(%s) 执行器 ...'.fotmat(jsp.description.name, name, c)); console.debug('插件 %s 设置命令 %s(%s) 执行器 ...'.format(jsp.description.name, name, c));
if (exec.cmd) { if (exec.cmd) {
c.setExecutor(function (sender, cmd, command, args) { c.setExecutor(function (sender, cmd, command, args) {
try { try {
return exec.cmd(sender, command, args); return exec.cmd(sender, command, args);
} catch (ex) { } catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s'.fotmat(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex)); console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s'.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex); console.ex(ex);
} }
}); });
@ -78,7 +78,7 @@ function on(jsp, name, exec) {
StringUtil.copyPartialMatches(token, Arrays.asList(exec.tab(sender, command, args)), completions); StringUtil.copyPartialMatches(token, Arrays.asList(exec.tab(sender, command, args)), completions);
return completions; return completions;
} catch (ex) { } catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s'.fotmat(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex)); console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s'.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex); console.ex(ex);
} }
}); });

View File

@ -0,0 +1,19 @@
var BukkitConsole = {
createNew: function () {
var console = Console.createNew();
console.sender = function () {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) {
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(console.prefix + args.join(' '));
};
console.console = function () {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
};
return console;
}
}
global.Console = BukkitConsole;
exports = global.Console;

View File

@ -138,7 +138,7 @@ function listen(jsp, event, exec, priority, ignoreCancel) {
} }
listeners.push(off); listeners.push(off);
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
console.debug('插件 %s 注册事件 %s 方法 %s'.format(name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name)); console.debug('插件 %s 注册事件 %s => %s'.format(name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name));
return off; return off;
} }

View File

@ -6,7 +6,7 @@
// var zip = require("core/zip"); // var zip = require("core/zip");
var fs = require('core/fs'); var fs = require('core/fs');
var yaml = require('modules/yaml'); var yaml = require('modules/yaml');
var event = require('modules/event'); var event = require('./event');
var bukkit = require('./server'); var bukkit = require('./server');
var command = require('./command'); var command = require('./command');
var permission = require('./permission'); var permission = require('./permission');
@ -99,7 +99,7 @@ function beforeLoadHook(origin) {
// 处理 event 为了不影响 正常逻辑 event 还是手动require吧 // 处理 event 为了不影响 正常逻辑 event 还是手动require吧
// result = result + 'var event = {}; module.exports.event = event;'; // result = result + 'var event = {}; module.exports.event = event;';
// 注入 console 对象 // 给插件注入单独的 console // 注入 console 对象 // 给插件注入单独的 console
result = result + 'var console = new Console(); module.exports.console = console;'; result = result + 'var console = Console.createNew(); module.exports.console = console;';
// 插件注入 self 对象 // 插件注入 self 对象
result = result + 'var self = {}; module.exports.self = self;'; result = result + 'var self = {}; module.exports.self = self;';
return result; return result;
@ -226,7 +226,6 @@ function checkAndGet(args) {
var plugins = []; var plugins = [];
exports.$ = undefined;
exports.plugins = plugins; exports.plugins = plugins;
exports.init = function (path) { exports.init = function (path) {
var plugin = bukkit.plugin.self; var plugin = bukkit.plugin.self;

View File

@ -5,10 +5,10 @@
*/ */
/*global Java, base, module, exports, require, __FILE__*/ /*global Java, base, module, exports, require, __FILE__*/
var Bukkit = Java.type("org.bukkit.Bukkit"); var Bukkit = MServer;
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
var Server = Bukkit.server; var Server = Bukkit.server;
var PluginManager = Bukkit.pluginManager; var PluginManager = Server.pluginManager;
exports.$ = Bukkit; exports.$ = Bukkit;
/** /**
* 获取NMS版本 * 获取NMS版本

View File

@ -1 +1 @@
module.exports = require('./bukkit/command'); module.exports = require('./mserver').command;

View File

@ -1 +1 @@
module.exports = require('./bukkit/event'); module.exports = require('./mserver').event;

View File

@ -0,0 +1,8 @@
module.exports = {
command: require('./' + DetectServerType + '/command'),
event: require('./' + DetectServerType + '/event'),
permission: require('./' + DetectServerType + '/permission'),
plugin: require('./' + DetectServerType + '/plugin'),
server: require('./' + DetectServerType + '/server'),
task: require('./' + DetectServerType + '/task')
}

View File

@ -1 +1 @@
module.exports = require('./bukkit/permission'); module.exports = require('./mserver').permission;

View File

@ -1 +1 @@
module.exports = require('./bukkit/plugin'); module.exports = require('./mserver').plugin;

View File

@ -1 +1 @@
module.exports = require('./bukkit/server'); module.exports = require('./mserver').server;

View File

@ -0,0 +1,93 @@
'use strict';
/**
* Sponge 命令相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var server = require('./server');
var plugin = server.plugin.self;
var CommandManager = server.CommandManager;
var CommandSpec = Java.type('org.spongepowered.api.command.spec.CommandSpec');
var Text = Java.type('org.spongepowered.api.text.Text');
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
function enable(jsp) {
var commands = jsp.description.commands;
if (commands) {
var pluginCmds = [];
for (var name in commands) {
var command = commands[name];
if (typeof command !== 'object') continue;
var newCmd = create(jsp, name);
if (command.description) newCmd.setDescription(command.description);
if (command.usage) newCmd.setUsage(command.usage);
if (command.aliases) newCmd.setAliases(Arrays.asList(command.aliases));
if (command.permission) newCmd.setPermission(command.permission);
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
pluginCmds.push(newCmd);
console.debug('插件 %s 注册命令 %s ...'.format(jsp.description.name, name));
}
commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCmds));
}
}
function get(name) {
return commandMap.getCommand(name);
}
function create(jsp, name) {
return register(jsp, ref.on(PluginCommand).create(name, plugin).get());
}
function register(jsp, cmd) {
commandMap.register(jsp.description.name, cmd);
return cmd;
}
// var exec = {
// cmd: function (sender, command, args) {
//
// },
// tab: function (sender, command, args) {
//
// }
// };
function on(jsp, name, exec) {
var c = get(name) || create(jsp, name);
console.debug('插件 %s 设置命令 %s(%s) 执行器 ...'.format(jsp.description.name, name, c));
if (exec.cmd) {
c.setExecutor(function (sender, cmd, command, args) {
try {
return exec.cmd(sender, command, args);
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s'.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex);
}
});
}
if (exec.tab) {
c.setTabCompleter(function (sender, cmd, command, args) {
try {
var completions = new ArrayList();
var token = args[args.length - 1];
StringUtil.copyPartialMatches(token, Arrays.asList(exec.tab(sender, command, args)), completions);
return completions;
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s'.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex);
}
});
}
}
exports.enable = enable;
exports.on = on;
exports.off = function () {
};

View File

@ -0,0 +1,23 @@
var SpongeConsole = {
createNew: function () {
var console = Console.createNew();
console.sender = function () {
var Text = Java.type("org.spongepowered.api.text.Text");
var sender = arguments[0];
if (!(sender instanceof org.spongepowered.api.command.CommandSource)) {
this.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
}
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(console.prefix + args.join(' ')));
};
console.console = function () {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));
};
console.warn = function () {
log.warn(this.name + Array.prototype.join.call(arguments, ' '));
};
return console;
}
}
global.Console = SpongeConsole;
exports = global.Console;

View File

@ -0,0 +1,43 @@
'use strict';
/**
* Sponge基础操作
* Created by 蒋天蓓 on 2017/10/27 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Sponge = MServer;
// noinspection JSUnresolvedVariable
var Server = Sponge.server;
var PluginManager = Sponge.pluginManager;
exports.$ = Sponge;
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
exports.plugin = {
/**
* 插件管理工具
*/
manager: PluginManager,
/**
* 获得插件实例
* @param name 插件名称
* @returns {*}
*/
get: function (name) {
return PluginManager.getPlugin(name);
},
/**
* 载入插件 并且返回结果
* @param name 插件名称
* @returns {*}
*/
load: function (name) {
var plugin = this.get(name);
if (ext.notNull(plugin) && !plugin.isEnabled()) {
PluginManager.enablePlugin(plugin);
}
return PluginManager.isPluginEnabled(name);
},
self: PluginManager.getPlugin('miaoscript').get()
};

View File

@ -0,0 +1,72 @@
'use strict';
/*global Java, base, module, exports, require, __FILE__*/
/**
* 任务计划
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
var plugin = require('./server').plugin.self;
var Comsumer = Java.type('java.util.function.Consumer');
var Task = Java.type("org.spongepowered.api.scheduler.Task");
/**
* 创建任务对象
* @param func 任务
*/
exports.create = function (func) {
return Task.builder().execute(new Comsumer(func));
};
/**
* 运行任务
* @param func 任务
*/
exports.run = function (func) {
return exports.create(func).submit(plugin);
};
/**
* 延时运行任务
* @param func 任务
* @param time 延时时间
*/
exports.later = function (func, time) {
return exports.create(func).delayTicks(time).submit(plugin);
};
/**
* 运行循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
exports.timer = function () {
switch (arguments.length) {
case 2:
return exports.create(arguments[0]).intervalTicks(arguments[1]).submit(plugin);
case 3:
return exports.create(arguments[0]).delayTicks(arguments[1]).intervalTicks(arguments[2]).submit(plugin);
}
};
/**
* 运行异步任务
* @param func function 任务
*/
exports.async = function (func) {
return exports.create(func).async().submit(plugin);
};
/**
* 延时运行异步任务
* @param func 任务
* @param time 延时时间
*/
exports.laterAsync = function (func, time) {
return exports.create(func).async().delayTicks(time).submit(plugin);
};
/**
* 运行异步循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
exports.timerAsync = function () {
switch (arguments.length) {
case 2:
return exports.create(arguments[0]).async().intervalTicks(arguments[1]).submit(plugin);
case 3:
return exports.create(arguments[0]).async().delayTicks(arguments[1]).intervalTicks(arguments[2]).submit(plugin);
}
};

View File

@ -1 +1 @@
module.exports = require('./bukkit/task'); module.exports = require('./mserver').task;