feat: 新增Sponge的部分支持(测试中)

Signed-off-by: 502647092 <admin@yumc.pw>
This commit is contained in:
2017-10-26 21:01:24 +08:00
parent 4bb2c48021
commit e387863061
18 changed files with 437 additions and 221 deletions

4
.gitignore vendored
View File

@ -38,3 +38,7 @@
/atlassian-ide-plugin.xml /atlassian-ide-plugin.xml
/src/main/resources/cache/ /src/main/resources/cache/
# ThinkPHP
vendor/
composer.lock

21
pom.xml
View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>pw.yumc</groupId> <groupId>pw.yumc</groupId>
<artifactId>MiaoScript</artifactId> <artifactId>MiaoScript</artifactId>
<version>1.1.4</version> <version>1.1.5</version>
<developers> <developers>
<developer> <developer>
<id>502647092</id> <id>502647092</id>
@ -49,7 +49,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <!--<plugin>
<groupId>com.github.wvengen</groupId> <groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId> <artifactId>proguard-maven-plugin</artifactId>
<version>2.0.13</version> <version>2.0.13</version>
@ -71,7 +71,7 @@
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>-->
</plugins> </plugins>
</build> </build>
<ciManagement> <ciManagement>
@ -94,6 +94,10 @@
<id>yumc-repo</id> <id>yumc-repo</id>
<url>http://repo.yumc.pw/content/groups/public/</url> <url>http://repo.yumc.pw/content/groups/public/</url>
</repository> </repository>
<repository>
<id>sponge</id>
<url>https://repo.spongepowered.org/maven/</url>
</repository>
</repositories> </repositories>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
@ -114,6 +118,17 @@
<artifactId>YumCore</artifactId> <artifactId>YumCore</artifactId>
<type>jar</type> <type>jar</type>
<version>[1.8,)</version> <version>[1.8,)</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId>
<version>6.0.0</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -26,6 +26,9 @@
-keepclassmembers class * implements net.md_5.bungee.api.plugin.Listener { -keepclassmembers class * implements net.md_5.bungee.api.plugin.Listener {
@net.md_5.bungee.event.EventHandler <methods>; @net.md_5.bungee.event.EventHandler <methods>;
} }
-keepclassmembers class * {
@org.spongepowered.api.event.Listener <methods>;
}
# -----保护继承事件不被清理----- # -----保护继承事件不被清理-----
-keep class ** extends org.bukkit.event.Event {*;} -keep class ** extends org.bukkit.event.Event {*;}
@ -46,6 +49,9 @@
-keepclassmembers class **.commands.annotation.** {<methods>;} -keepclassmembers class **.commands.annotation.** {<methods>;}
-keepclassmembers class * implements **.commands.interfaces.Executor {<methods>;} -keepclassmembers class * implements **.commands.interfaces.Executor {<methods>;}
# -----保护注解命令方法不被清理-----
-keep @org.spongepowered.api.plugin.Plugin class * {*;}
# -----保护注解NotProguard标记----- # -----保护注解NotProguard标记-----
-keep class **.NotProguard -keep class **.NotProguard
-keep @**.NotProguard class * {*;} -keep @**.NotProguard class * {*;}

View File

@ -6,13 +6,8 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.bukkit.plugin.Plugin;
import lombok.val; import lombok.val;
import pw.yumc.YumCore.annotation.NotProguard; import pw.yumc.YumCore.annotation.NotProguard;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.P;
import pw.yumc.YumCore.bukkit.compatible.C;
import pw.yumc.YumCore.mc.MinecraftTools; import pw.yumc.YumCore.mc.MinecraftTools;
/** /**
@ -23,25 +18,15 @@ import pw.yumc.YumCore.mc.MinecraftTools;
*/ */
@NotProguard @NotProguard
public class Base { public class Base {
public Plugin getPlugin() {
return P.instance;
}
public Class getClass(String name) throws ClassNotFoundException { public Class getClass(String name) throws ClassNotFoundException {
return Class.forName(name); return Class.forName(name);
} }
public Class getLog() {
return Log.class;
}
public String read(String path) throws IOException { public String read(String path) throws IOException {
Log.fd("读取文件 %s ...", path);
return new String(Files.readAllBytes(new File(path).toPath()), "UTF-8"); return new String(Files.readAllBytes(new File(path).toPath()), "UTF-8");
} }
public void save(String path, String content) throws IOException { public void save(String path, String content) throws IOException {
Log.fd("保存文件 %s ...", path);
File file = new File(path); File file = new File(path);
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
Files.write(file.toPath(), content.getBytes("UTF-8")); Files.write(file.toPath(), content.getBytes("UTF-8"));
@ -54,7 +39,6 @@ public class Base {
public void delete(Path path) throws IOException { public void delete(Path path) throws IOException {
val file = path.toFile(); val file = path.toFile();
if (!file.exists()) { return; } if (!file.exists()) { return; }
Log.fd("删除文件 %s ...", path);
if (file.isDirectory()) { if (file.isDirectory()) {
for (Path f : Files.list(file.toPath()).collect(Collectors.toList())) { for (Path f : Files.list(file.toPath()).collect(Collectors.toList())) {
delete(f); delete(f);
@ -63,18 +47,6 @@ public class Base {
Files.delete(path); Files.delete(path);
} }
public Class getActionBar() {
return C.ActionBar.class;
}
public Class getTitle() {
return C.Title.class;
}
public Class getPlayer() {
return C.Player.class;
}
public Class getTools() { public Class getTools() {
return MinecraftTools.class; return MinecraftTools.class;
} }

View File

@ -1,10 +1,6 @@
package pw.yumc.MiaoScript; package pw.yumc.MiaoScript;
import java.io.File; import java.io.File;
import java.io.InputStreamReader;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -19,7 +15,6 @@ import pw.yumc.YumCore.commands.CommandSub;
import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help; import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.interfaces.Executor; import pw.yumc.YumCore.commands.interfaces.Executor;
import pw.yumc.YumCore.engine.MiaoScriptEngine;
/** /**
* 喵式脚本 * 喵式脚本
@ -28,33 +23,34 @@ import pw.yumc.YumCore.engine.MiaoScriptEngine;
* @since 2016年8月29日 上午7:50:39 * @since 2016年8月29日 上午7:50:39
*/ */
public class MiaoScript extends JavaPlugin implements Executor { public class MiaoScript extends JavaPlugin implements Executor {
private MiaoScriptEngine engine; private ScriptEngine engine;
@Override @Override
@SneakyThrows
public void onEnable() { public void onEnable() {
new CommandSub("ms", this); new CommandSub("ms", this);
saveScript(); saveScript();
enableEngine(); engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getClassLoader(), getLogger());
} }
@Cmd @Cmd
@Help("执行 JS 代码") @Help("执行 JS 代码")
@SneakyThrows @SneakyThrows
public void js(CommandSender sender, String script) { public void js(CommandSender sender, String script) {
result(sender, engine.eval(script)); result(sender, engine.getEngine().eval(script));
} }
@Cmd @Cmd
@Help("执行 JS 代码文件") @Help("执行 JS 代码文件")
@SneakyThrows @SneakyThrows
public void file(CommandSender sender, String file) { public void file(CommandSender sender, String file) {
result(sender, engine.eval("load('" + new File(getDataFolder(), file).getCanonicalPath() + "')")); result(sender, engine.getEngine().eval("load('" + new File(getDataFolder(), file).getCanonicalPath() + "')"));
} }
@Cmd @Cmd
@Help("重启脚本引擎") @Help("重启脚本引擎")
public void reload(CommandSender sender) { public void reload(CommandSender sender) {
disableEngine(); engine.disableEngine();
val server = Bukkit.getServer(); val server = Bukkit.getServer();
try { try {
server.getScheduler().cancelTasks(this); server.getScheduler().cancelTasks(this);
@ -65,7 +61,7 @@ public class MiaoScript extends JavaPlugin implements Executor {
} catch (Exception ex) { } catch (Exception ex) {
Log.d("Error reload", ex); Log.d("Error reload", ex);
} }
enableEngine(); engine.enableEngine();
Log.sender(sender, "§bMiaoScript §eEngine §a重启完成!"); Log.sender(sender, "§bMiaoScript §eEngine §a重启完成!");
} }
@ -82,34 +78,8 @@ public class MiaoScript extends JavaPlugin implements Executor {
P.saveFile("plugins"); P.saveFile("plugins");
} }
private void enableEngine() {
Thread currentThread = Thread.currentThread();
ClassLoader previousClassLoader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(getClassLoader());
try {
ScriptEngineManager manager = new ScriptEngineManager();
this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base());
this.engine.eval(new InputStreamReader(this.getResource("bios.js")));
engine.invokeFunction("boot", this);
} catch (Exception e) {
Log.d(e);
} finally {
currentThread.setContextClassLoader(previousClassLoader);
}
}
private void disableEngine() {
try {
engine.invokeFunction("disable");
} catch (ScriptException | NoSuchMethodException e) {
Log.w("脚本引擎关闭失败! %s:%s", e.getClass().getName(), e.getMessage());
Log.d(e);
}
}
@Override @Override
public void onDisable() { public void onDisable() {
disableEngine(); engine.disableEngine();
} }
} }

View File

@ -0,0 +1,91 @@
package pw.yumc.MiaoScript;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Logger;
import javax.script.ScriptException;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.text.Text;
import com.google.inject.Inject;
import lombok.SneakyThrows;
/**
* Created with IntelliJ IDEA
*
* @author 喵♂呜
* Created on 2017/10/25 20:35.
*/
@Plugin(id = "miaoscript", name = "MiaoScript", version = "1.0", authors = "喵♂呜")
public class MiaoScriptSponge {
private ScriptEngine engine;
@Inject
private Logger logger;
@Inject
@ConfigDir(sharedRoot = false)
private File pluginConfigDir;
@Listener
public void onInit(GameInitializationEvent event) {
}
private CommandSpec main() {
return CommandSpec.builder()
.description(Text.of("喵式脚本主命令"))
.permission("MiaoScript.admin")
.child(js(), "js")
.child(file(), "file")
.build();
}
private CommandSpec js() {
return CommandSpec.builder()
.description(Text.of("执行JS命令"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
engine.getEngine().eval(args.<String>getOne("js").orElse(""));
} catch (ScriptException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
private CommandSpec file() {
return CommandSpec.builder()
.description(Text.of("执行JS文件"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
engine.getEngine().eval(new FileReader(new File(pluginConfigDir, args.<String>getOne("js").orElse(""))));
} catch (ScriptException | IOException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
@Listener
@SneakyThrows
public void onStart(GameStartedServerEvent event) {
Sponge.getServer().getConsole();
Sponge.getCommandManager().register(this, main(), "ms", "mscript", "MiaoScript");
engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), Thread.currentThread().getContextClassLoader(), logger);
}
}

View File

@ -0,0 +1,54 @@
package pw.yumc.MiaoScript;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import pw.yumc.YumCore.engine.MiaoScriptEngine;
/**
* Created with IntelliJ IDEA
*
* @author 喵♂呜
* Created on 2017/10/25 21:01.
*/
public class ScriptEngine {
private String root;
private ClassLoader classLoader;
private Logger logger;
private MiaoScriptEngine engine;
public ScriptEngine(String root, ClassLoader classLoader, Logger logger) {
this.root = root;
this.classLoader = classLoader;
this.logger = logger;
enableEngine();
}
public void enableEngine() {
try {
ScriptEngineManager manager = new ScriptEngineManager(null);
this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base());
this.engine.eval(new InputStreamReader(classLoader.getResourceAsStream("bios.js")));
engine.invokeFunction("boot", root, logger);
} catch (Exception e) {
logger.log(Level.SEVERE, "MiaoScript 启动失败!", e);
}
}
public void disableEngine() {
try {
engine.invokeFunction("disable");
} catch (ScriptException | NoSuchMethodException e) {
logger.log(Level.SEVERE, "MiaoScript 关闭失败!", e);
}
}
public MiaoScriptEngine getEngine() {
return engine;
}
}

View File

@ -1,26 +1,62 @@
'use strict'; 'use strict';
var log = base.getLog().static; var log;
var boot; var boot;
var disable; var disable;
/** /**
* 初始化框架引擎 * 初始化框架引擎
*/ */
(function () { (function () {
boot = function (plugin) { boot = function (root, logger) {
log = logger;
// 开发环境下初始化 // 开发环境下初始化
var root = "src/main/resources"; root = root || "src/main/resources";
if (plugin !== null) { // 解压文件到根目录
// noinspection JSUnresolvedVariable release(root, "[core|modules]/.*", true);
root = plugin.dataFolder.canonicalPath; release(root, "plugins/.*");
}
load(root + '/core/init.js'); load(root + '/core/init.js');
try { try {
init(root); init(root);
} catch (ex) { } catch (ex) {
log.w("MiaoScript 初始化失败! %s", ex);
throw ex; throw ex;
} finally { } finally {
disable = disablePlugins disable = disablePlugins
} }
}; };
function release(root, regex, replace) {
print(Array.prototype.join.call(arguments, ' '));
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
var classLoader = java.lang.Thread.currentThread().getContextClassLoader();
var url = classLoader.getResource("plugin.yml");
if (url === null) {
return;
}
var upath = url.getFile().substring(url.getFile().indexOf("/") + 1);
var jarPath = java.net.URLDecoder.decode(upath.substring(0, upath.indexOf('!')));
if (!Files.exists(Paths.get(jarPath))) {
jarPath = "/" + jarPath;
}
try {
var jar = new java.util.jar.JarFile(jarPath);
var r = new RegExp(regex);// "[core|modules]/.*"
jar.stream().forEach(function (entry) {
if (!entry.isDirectory()) {
if (r.test(entry.name)) {
var path = Paths.get(root, entry.name);
var parentFile = path.toFile().parentFile;
if (!parentFile.exists()) {
parentFile.mkdirs();
}
Files.copy(classLoader.getResourceAsStream(entry.name), path, StandardCopyOption[replace ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
}
}
})
} catch (ex) {
} finally {
}
}
})(); })();

View File

@ -2,9 +2,10 @@
* 控制台输出类 * 控制台输出类
*/ */
/*global base*/ /*global base*/
(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 = function (name) { var Console = function (name) {
Object.defineProperty(this, 'name', { Object.defineProperty(this, 'name', {
get: function () { get: function () {
@ -17,38 +18,66 @@
}); });
this.name = name; this.name = name;
this.log = function () { this.log = function () {
log.i(this.name + Array.prototype.join.call(arguments, ' ')); log.info(this.name + Array.prototype.join.call(arguments, ' '));
}, };
this.warn = function () { this.warn = function () {
log.w(this.name + Array.prototype.join.call(arguments, ' ')); log.warning(this.name + Array.prototype.join.call(arguments, ' '));
}, };
this.error = function () { this.error = function () {
log.log(Level.SEVERE, this.name + Array.prototype.join.call(arguments, ' ')); log.log(Level.SEVERE, this.name + Array.prototype.join.call(arguments, ' '));
}, };
this.debug = function () { switch (DetectServerType) {
log.d(this.name + Array.prototype.join.call(arguments, ' ')); case ServerType.Bukkit:
} this.sender = function () {
this.sender = function () { var sender = arguments[0];
var sender = arguments[0]; if (!(sender instanceof org.bukkit.command.CommandSender)) {
if (!(sender instanceof org.bukkit.command.CommandSender)) { console.error("第一个参数未实现 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.ex = function (ex) {
log.console('§4' + ex);
var track = ex.getStackTrace();
if (track.class) { track = Arrays.asList(track) }
if (track.forEach) {
track.forEach(function (stack) {
if (stack.className.startsWith('<')) {
log.console(' §e位于 §c%s => §c%s §4行%s', stack.fileName, stack.methodName, stack.lineNumber);
} else {
log.console(' §e位于 §c%s.%s(§4%s:%s§c)', stack.className, stack.methodName, stack.fileName, stack.lineNumber);
} }
}); var args = Array.prototype.slice.call(arguments, 1);
} sender.sendMessage(this.prefix + args.join(' '));
};
this.console = function () {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
};
break;
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);
var track = ex.getStackTrace();
if (track.class) {
track = Arrays.asList(track)
}
track.forEach(function (stack) {
if (stack.className.startsWith('<')) {
this.console(String.format(' §e位于 §c%s => §c%s §4行%s', stack.fileName, stack.methodName, stack.lineNumber));
} else {
this.console(String.format(' §e位于 §c%s.%s(§4%s:%s§c)', stack.className, stack.methodName, stack.fileName, stack.lineNumber));
}
}.bind(this));
}
};
global.Console = Console; global.Console = Console;
global.console = new Console(); global.console = new Console();
})(global) })(global);

View File

@ -0,0 +1,22 @@
/**
* 服务器探测类
*/
/*global base*/
var ServerType = {
Bukkit: 1,
Sponge: 2
};
var MServer;
var DetectServerType = ServerType.Bukkit;
try {
MServer = Java.type("org.bukkit.Bukkit");
DetectServerType = ServerType.Bukkit;
} catch (ex) {
// IGNORE
}
try {
MServer = Java.type("org.spongepowered.api.Sponge");
DetectServerType = ServerType.Sponge;
} catch (ex) {
// IGNORE
}

View File

@ -18,6 +18,7 @@ function init(root) {
function loadCore() { function loadCore() {
// 加载基础模块 // 加载基础模块
load(root + '/core/ext.js'); load(root + '/core/ext.js');
load(root + '/core/detect.js');
load(root + '/core/console.js'); load(root + '/core/console.js');
} }

View File

@ -7,7 +7,7 @@
'use strict'; 'use strict';
var File = Java.type("java.io.File"); var File = Java.type("java.io.File");
var separatorChar = File.separatorChar; var separatorChar = File.separatorChar;
var paths = [parent, '', parent + separatorChar + 'core', parent + separatorChar + 'modules']; var paths = [parent, parent + separatorChar + 'core', parent + separatorChar + 'modules'];
/** /**
* 解析模块名称为文件 * 解析模块名称为文件
@ -17,21 +17,22 @@
* 核心目录 /core * 核心目录 /core
* 模块目录 /modules * 模块目录 /modules
* @param name 模块名称 * @param name 模块名称
* @param parent 父目录
*/ */
function resolve(name, parent) { function resolve(name, parent) {
if (_canonical(name)) { if (_canonical(name)) {
name = _canonical(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;
} else { } else {
// 查找可能存在的路径 // 查找可能存在的路径
for(var i in paths) { for (var i in paths) {
var path = paths[i]; var path = paths[i];
var result = resolveAsFile(path, name) || resolveAsDirectory(path, name); var result = resolveAsFile(path, name) || resolveAsDirectory(path, name);
if (result) { if (result) {
return result; return result;
} }
} }
} }
@ -43,7 +44,7 @@
* @returns {*} * @returns {*}
*/ */
function resolveAsFile(dir, file) { function resolveAsFile(dir, file) {
var file = ext.notNull(dir) ? new File(dir, file) : new File(file); file = ext.notNull(dir) ? new File(dir, file) : new File(file);
if (file.isFile()) { if (file.isFile()) {
return file; return file;
} }
@ -58,7 +59,7 @@
* @returns {*} * @returns {*}
*/ */
function resolveAsDirectory(dir, file) { function resolveAsDirectory(dir, file) {
var dir = ext.notNull(dir) ? new File(dir, file) : new File(file); dir = ext.notNull(dir) ? new File(dir, file) : new File(file);
var _package = new File(dir, 'package.json'); var _package = new File(dir, 'package.json');
if (_package.exists()) { if (_package.exists()) {
var json = JSON.parse(base.read(_package)); var json = JSON.parse(base.read(_package));
@ -80,7 +81,8 @@
/** /**
* 预编译模块 * 预编译模块
* @param file * @param file JS文件
* @param optional 附加选项
* @returns {Object} * @returns {Object}
*/ */
function compileJs(file, optional) { function compileJs(file, optional) {
@ -98,13 +100,14 @@
/** /**
* 编译模块 * 编译模块
* @param id * @param id 模块ID
* @param name * @param name 模块名称
* @param file * @param file 模块文件
* @param optional 附加选项
* @returns {Object} * @returns {Object}
*/ */
function compileModule(id, name, file, optional) { function compileModule(id, name, file, optional) {
log.fd('加载模块 %s 位于 %s Optional %s', name, id, optional.toJson()); console.debug('加载模块 %s 位于 %s Optional %s', name, id, optional.toJson());
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
var module = { var module = {
id: id, id: id,
@ -117,11 +120,11 @@
compiledWrapper.apply(module.exports, [ compiledWrapper.apply(module.exports, [
module, module.exports, module.require, file.parentFile, file module, module.exports, module.require, file.parentFile, file
]); ]);
log.fd('模块 %s 编译成功!', name); console.debug('模块 %s 编译成功!', name);
module.loaded = true; module.loaded = true;
} catch (ex) { } catch (ex) {
log.console("§4警告! §b模块 §a%s §4编译失败! ERR: %s", name, ex); console.console("§4警告! §b模块 §a%s §4编译失败! ERR: %s", name, ex);
log.d(ex); console.ex(ex);
} }
return module; return module;
} }
@ -145,16 +148,17 @@
* 加载模块 * 加载模块
* @param name 模块名称 * @param name 模块名称
* @param path 路径 * @param path 路径
* @param optional 附加选项
* @returns {*} * @returns {*}
* @private * @private
*/ */
function _require(name, path, optional) { function _require(name, path, optional) {
var file = _canonical(name) ? name : resolve(name, path); var file = _canonical(name) ? name : resolve(name, path);
if (file === undefined) { if (file === undefined) {
log.console("§c模块 §a%s §c加载失败! §4未找到该模块!", name); console.console("§c模块 §a%s §c加载失败! §4未找到该模块!", name);
return {exports:{}}; return {exports: {}};
} }
if (!optional) optional = { cache: true } if (!optional) optional = {cache: true};
// 重定向文件名称和类型 // 重定向文件名称和类型
name = file.name.split(".")[0]; name = file.name.split(".")[0];
var id = _canonical(file); var id = _canonical(file);
@ -185,6 +189,6 @@
parent = new File(parent); parent = new File(parent);
} }
var cacheModules = []; var cacheModules = [];
log.d("初始化 require 模块组件 父目录 %s", _canonical(parent)); console.debug("初始化 require 模块组件 父目录 %s", _canonical(parent));
return exports(parent); return exports(parent);
}); });

View File

@ -19,14 +19,14 @@ exports.nmsVersion = Bukkit.server.class.name.split('.')[3];
*/ */
exports.nmsCls = function (name) { exports.nmsCls = function (name) {
return Java.type(['net.minecraft.server', exports.nmsVersion, name].join('.')); return Java.type(['net.minecraft.server', exports.nmsVersion, name].join('.'));
} };
exports.command = function (name) { exports.command = function (name) {
return Server.getPluginCommand(name); return Server.getPluginCommand(name);
} };
/** /**
* 获取玩家 * 获取玩家
*/ */
exports.player = function(){ exports.player = function () {
switch (arguments.length) { switch (arguments.length) {
case 0: case 0:
return undefined; return undefined;
@ -35,18 +35,18 @@ exports.player = function(){
default: default:
return Bukkit.getPlayerExtra(arguments[0]); return Bukkit.getPlayerExtra(arguments[0]);
} }
} };
/** /**
* 获取在线玩家 * 获取在线玩家
*/ */
exports.players = function(){ exports.players = function () {
switch (arguments.length) { switch (arguments.length) {
case 1: case 1:
return Bukkit.onlinePlayers.forEach(arguments[0]); return Bukkit.onlinePlayers.forEach(arguments[0]);
default: default:
return Bukkit.onlinePlayers; return Bukkit.onlinePlayers;
} }
} };
/** /**
* 插件管理 * 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}} * @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}

View File

@ -13,13 +13,13 @@ var PluginCommand = Java.type('org.bukkit.command.PluginCommand');
var StringUtil = Java.type('org.bukkit.util.StringUtil'); var StringUtil = Java.type('org.bukkit.util.StringUtil');
var ArrayList = Java.type('java.util.ArrayList'); var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays') var Arrays = Java.type('java.util.Arrays');
function enable(jsp){ function enable(jsp) {
var commands = jsp.description.commands; var commands = jsp.description.commands;
if(commands){ if (commands) {
var pluginCmds = []; var pluginCmds = [];
for (var name in commands){ for (var name in commands) {
var command = commands[name]; var command = commands[name];
if (typeof command !== 'object') continue; if (typeof command !== 'object') continue;
var newCmd = create(jsp, name); var newCmd = create(jsp, name);
@ -29,7 +29,7 @@ function enable(jsp){
if (command.permission) newCmd.setPermission(command.permission); if (command.permission) newCmd.setPermission(command.permission);
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']); if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
pluginCmds.push(newCmd); pluginCmds.push(newCmd);
log.d('插件 %s 注册命令 %s ...', jsp.description.name, name); console.debug('插件 %s 注册命令 %s ...', jsp.description.name, name);
} }
commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCmds)); commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCmds));
} }
@ -43,7 +43,7 @@ function create(jsp, name) {
return register(jsp, ref.on(PluginCommand).create(name, plugin).get()); return register(jsp, ref.on(PluginCommand).create(name, plugin).get());
} }
function register(jsp, cmd){ function register(jsp, cmd) {
commandMap.register(jsp.description.name, cmd); commandMap.register(jsp.description.name, cmd);
return cmd; return cmd;
} }
@ -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);
log.d('插件 %s 设置命令 %s(%s) 执行器 ...', jsp.description.name, name, c); console.debug('插件 %s 设置命令 %s(%s) 执行器 ...', 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) {
log.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s', 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', sender.name, jsp.description.name, command, Java.from(args).join(' '), ex);
console.ex(ex); console.ex(ex);
} }
}); });
@ -78,14 +78,14 @@ 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) {
log.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s',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', sender.name, jsp.description.name, command, Java.from(args).join(' '), ex);
console.ex(ex); console.ex(ex);
} }
}); });
} }
} }
exports.enable = enable exports.enable = enable;
exports.on = on; exports.on = on;
exports.off = function () { exports.off = function () {

View File

@ -46,7 +46,7 @@ function mapEventName() {
if (isVaildEvent(clz)) { if (isVaildEvent(clz)) {
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
var simpleName = clz.simpleName.toLowerCase(); var simpleName = clz.simpleName.toLowerCase();
log.fd("Mapping Event [%s] => %s", clz.name, simpleName); console.debug("Mapping Event [%s] => %s", clz.name, simpleName);
mapEvent[simpleName] = clz; mapEvent[simpleName] = clz;
count++; count++;
} }
@ -85,12 +85,12 @@ function isVaildEvent(clz) {
function listen(jsp, event, exec, priority, ignoreCancel) { function listen(jsp, event, exec, priority, ignoreCancel) {
var name = jsp.description.name; var name = jsp.description.name;
if (ext.isNull(name)) throw new TypeError('插件名称为空 请检查传入参数!'); if (ext.isNull(name)) throw new TypeError('插件名称为空 请检查传入参数!');
var eventCls = mapEvent[event] || mapEvent[event.toLowerCase()] || mapEvent[event +'Event'] || mapEvent[event.toLowerCase() + 'event']; var eventCls = mapEvent[event] || mapEvent[event.toLowerCase()] || mapEvent[event + 'Event'] || mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) { if (!eventCls) {
try { try {
eventCls = base.getClass(eventCls); eventCls = base.getClass(eventCls);
} catch (ex) { } catch (ex) {
log.w("事件 %s 未找到!", event); console.warn("事件 %s 未找到!", event);
return; return;
} }
} }
@ -115,10 +115,10 @@ function listen(jsp, event, exec, priority, ignoreCancel) {
EventPriority[priority], EventPriority[priority],
new EventExecutor({ new EventExecutor({
execute: function (listener, event) { execute: function (listener, event) {
try{ try {
exec(event); exec(event);
} catch (ex){ } catch (ex) {
log.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s', name, event.class.simpleName, ex); console.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s', name, event.class.simpleName, ex);
console.ex(ex); console.ex(ex);
} }
} }
@ -131,20 +131,20 @@ function listen(jsp, event, exec, priority, ignoreCancel) {
var off = { var off = {
event: eventCls, event: eventCls,
listener: listener, listener: listener,
off: function(){ off: function () {
ref.on(this.event).call('getHandlerList').get().unregister(this.listener); ref.on(this.event).call('getHandlerList').get().unregister(this.listener);
log.d('插件 %s 注销事件 %s', name, this.event.simpleName); console.debug('插件 %s 注销事件 %s', name, this.event.simpleName);
} }
} }
listeners.push(off); listeners.push(off);
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
log.d('插件 %s 注册事件 %s 方法 %s', name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name); console.debug('插件 %s 注册事件 %s 方法 %s', name, eventCls.simpleName, exec.name === '' ? '匿名方法' : exec.name);
return off; return off;
} }
var mapEvent = []; var mapEvent = [];
// 映射事件名称 // 映射事件名称
log.i('Bukkit 事件映射完毕 共计 %s 个事件!', mapEventName().toFixed(0)); console.info('Bukkit 事件映射完毕 共计 %s 个事件!', mapEventName().toFixed(0));
module.exports = { module.exports = {
on: listen, on: listen,

View File

@ -12,37 +12,37 @@ var manager = require('./bukkit').plugin.manager;
var Permission = Java.type("org.bukkit.permissions.Permission"); var Permission = Java.type("org.bukkit.permissions.Permission");
var PermissionDefault = Java.type('org.bukkit.permissions.PermissionDefault'); var PermissionDefault = Java.type('org.bukkit.permissions.PermissionDefault');
function enable (plugin) { function enable(plugin) {
var permissions = plugin.description.permissions; var permissions = plugin.description.permissions;
if(permissions){ if (permissions) {
for (var name in permissions){ for (var name in permissions) {
var permission = permissions[name]; var permission = permissions[name];
if (typeof permission !== 'object') continue; if (typeof permission !== 'object') continue;
var desc = permission.description; var desc = permission.description;
var def = permission.default || 'OP'; var def = permission.default || 'OP';
try { try {
manager.addPermission(new Permission(name, desc, PermissionDefault.getByName(def))); manager.addPermission(new Permission(name, desc, PermissionDefault.getByName(def)));
} catch (ex) { } catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined! // ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
} }
log.d('插件 %s 注册权限 %s Default %s ...', plugin.description.name, name, def); console.debug('插件 %s 注册权限 %s Default %s ...', plugin.description.name, name, def);
} }
} }
} }
function disable (plugin) { function disable(plugin) {
var permissions = plugin.description.permissions; var permissions = plugin.description.permissions;
if(permissions){ if (permissions) {
for (var name in permissions){ for (var name in permissions) {
try { try {
manager.removePermission(name); manager.removePermission(name);
} catch (ex) { } catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined! // ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
} }
log.d('插件 %s 注销权限 %s ...', plugin.description.name, name); console.debug('插件 %s 注销权限 %s ...', plugin.description.name, name);
} }
} }
} }
exports.enable = enable exports.enable = enable;
exports.disable = disable exports.disable = disable;

View File

@ -18,9 +18,9 @@ var permission = require('./permission');
function loadPlugins(dir) { function loadPlugins(dir) {
var plugin = fs.file(root, dir); var plugin = fs.file(root, dir);
if (!plugin) { if (!plugin) {
log.i("首次加载 创建文件夹 %s ...", plugin); console.info("首次加载 创建文件夹 %s ...", plugin);
} else { } else {
log.i("开始扫描 %s 下的插件 ...", plugin); console.info("开始扫描 %s 下的插件 ...", plugin);
createUpdate(plugin); createUpdate(plugin);
var files = []; var files = [];
fs.list(plugin).forEach(function (file) { fs.list(plugin).forEach(function (file) {
@ -71,7 +71,7 @@ function loadJsPlugins(files) {
function loadPlugin(file) { function loadPlugin(file) {
var update = fs.file(fs.file(file.parentFile, 'update'), file.name); var update = fs.file(fs.file(file.parentFile, 'update'), file.name);
if (update.exists()) { if (update.exists()) {
log.i('自动升级插件 %s', file.name); console.info('自动升级插件 %s', file.name);
fs.move(update, file, true); fs.move(update, file, true);
} }
var plugin = require(file, { var plugin = require(file, {
@ -80,16 +80,16 @@ function loadPlugin(file) {
return beforeLoadHook(origin); return beforeLoadHook(origin);
} }
}); });
log.d("插件编译结果: %s", plugin.toJson()); console.debug("插件编译结果: %s", plugin.toJson());
var desc = plugin.description; var desc = plugin.description;
if (!desc || !desc.name) { if (!desc || !desc.name) {
log.w("文件 %s 不存在 description 描述信息 无法加载插件!", file); console.warn("文件 %s 不存在 description 描述信息 无法加载插件!", file);
} else { } else {
initPlugin(file, plugin); initPlugin(file, plugin);
afterLoadHook(plugin); afterLoadHook(plugin);
plugins.push(plugin); plugins.push(plugin);
plugins[plugin.description.name] = plugin; plugins[plugin.description.name] = plugin;
log.i('载入插件 %s 版本 %s By %s', desc.name, desc.version || '未知', desc.author || '未知'); console.info('载入插件 %s 版本 %s By %s', desc.name, desc.version || '未知', desc.author || '未知');
} }
return plugin; return plugin;
} }
@ -110,7 +110,7 @@ function afterLoadHook(plugin) {
// 给 console 添加插件名称 // 给 console 添加插件名称
plugin.console.name = plugin.description.name; plugin.console.name = plugin.description.name;
// 赋值 self // 赋值 self
for (var i in plugin){ for (var i in plugin) {
plugin.self[i] = plugin[i]; plugin.self[i] = plugin[i];
} }
} }
@ -118,15 +118,19 @@ function afterLoadHook(plugin) {
/** /**
* 初始化插件内容(提供config,__DATA__等参数) * 初始化插件内容(提供config,__DATA__等参数)
*/ */
function initPlugin(file, plugin){ function initPlugin(file, plugin) {
// 初始化 __FILE__ // 初始化 __FILE__
plugin.__FILE__ = file; plugin.__FILE__ = file;
// 初始化 __DATA__ // 初始化 __DATA__
plugin.__DATA__ = fs.file(file.parentFile, plugin.description.name); plugin.__DATA__ = fs.file(file.parentFile, plugin.description.name);
// 初始化 getDataFolder() // 初始化 getDataFolder()
plugin.getDataFolder = function() { return plugin.__DATA__; } plugin.getDataFolder = function () {
return plugin.__DATA__;
};
// 初始化 getFile() // 初始化 getFile()
plugin.getFile = function(name) { return fs.file(plugin.getDataFolder(), name); } plugin.getFile = function (name) {
return fs.file(plugin.getDataFolder(), name);
};
// 初始化插件配置相关方法 // 初始化插件配置相关方法
initPluginConfig(plugin); initPluginConfig(plugin);
@ -138,7 +142,7 @@ function initPlugin(file, plugin){
/** /**
* 初始化插件配置 * 初始化插件配置
*/ */
function initPluginConfig(plugin){ function initPluginConfig(plugin) {
// 初始化 config // 初始化 config
plugin.configFile = plugin.getFile('config.yml'); plugin.configFile = plugin.getFile('config.yml');
/** /**
@ -146,7 +150,7 @@ function initPluginConfig(plugin){
* @constructor * @constructor
* @constructor (file|string) * @constructor (file|string)
*/ */
plugin.getConfig = function() { plugin.getConfig = function () {
switch (arguments.length) { switch (arguments.length) {
case 0: case 0:
return plugin.config; return plugin.config;
@ -157,34 +161,34 @@ function initPluginConfig(plugin){
} }
return yaml.safeLoad(base.read(file)); return yaml.safeLoad(base.read(file));
} }
} };
/** /**
* 重载配置文件 * 重载配置文件
* @constructor * @constructor
* @constructor (file|string) * @constructor (file|string)
*/ */
plugin.reloadConfig = function() { plugin.reloadConfig = function () {
plugin.config = plugin.getConfig(plugin.configFile); plugin.config = plugin.getConfig(plugin.configFile);
} };
/** /**
* 保存配置文件 * 保存配置文件
* @constructor * @constructor
* @constructor (file, content) * @constructor (file, content)
*/ */
plugin.saveConfig = function() { plugin.saveConfig = function () {
switch (arguments.length) { switch (arguments.length) {
case 0: case 0:
plugin.configFile.parentFile.mkdirs() plugin.configFile.parentFile.mkdirs();
base.save(plugin.configFile, plugin.config.toYaml()); base.save(plugin.configFile, plugin.config.toYaml());
break; break;
case 2: case 2:
base.save(arguments[0], arguments[1].toYaml()); base.save(arguments[0], arguments[1].toYaml());
break; break;
} }
} };
if (plugin.configFile.isFile()) { if (plugin.configFile.isFile()) {
plugin.config = plugin.getConfig('config.yml'); plugin.config = plugin.getConfig('config.yml');
} else if (plugin.description.config ){ } else if (plugin.description.config) {
plugin.config = plugin.description.config; plugin.config = plugin.description.config;
plugin.saveConfig(); plugin.saveConfig();
} }
@ -195,20 +199,28 @@ function runAndCatch(jsp, exec, ext) {
try { try {
// 绑定方法的this到插件自身 // 绑定方法的this到插件自身
exec.bind(jsp)(); exec.bind(jsp)();
if (ext) { ext(); } if (ext) {
ext();
}
} catch (ex) { } catch (ex) {
log.console('§6插件 §b%s §6执行 §d%s §6方法时发生错误 §4%s', jsp.description.name, exec.name, ex.message); console.console('§6插件 §b%s §6执行 §d%s §6方法时发生错误 §4%s', jsp.description.name, exec.name, ex.message);
console.ex(ex); console.ex(ex);
} }
} }
} }
function checkAndGet(args) { function checkAndGet(args) {
if (args.length === 0) { return plugins; } if (args.length === 0) {
return plugins;
}
var name = args[0]; var name = args[0];
// 如果是插件 则直接返回 // 如果是插件 则直接返回
if (name.description) { return [name]; } if (name.description) {
if (!exports.plugins[name]) { throw new Error("插件 " + name + " 不存在!"); } return [name];
}
if (!exports.plugins[name]) {
throw new Error("插件 " + name + " 不存在!");
}
return [exports.plugins[name]]; return [exports.plugins[name]];
} }
@ -220,7 +232,7 @@ exports.init = function (plugin, path) {
if (plugin !== null) { if (plugin !== null) {
// 如果过plugin不等于null 则代表是正式环境 // 如果过plugin不等于null 则代表是正式环境
exports.$ = plugin; exports.$ = plugin;
log.i("初始化 MiaoScript 插件系统 版本: %s", plugin.description.version); console.info("初始化 MiaoScript 插件系统 版本: %s", plugin.description.version);
} }
loadPlugins(path); loadPlugins(path);
}; };
@ -231,7 +243,7 @@ exports.enable = function () {
checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.enable)); checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.enable));
}; };
exports.disable = function () { exports.disable = function () {
checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.disable, function(){ checkAndGet(arguments).forEach(function (p) runAndCatch(p, p.disable, function () {
event.disable(p); event.disable(p);
// task.cancel(); // task.cancel();
})); }));

View File

@ -49,7 +49,7 @@ function load() {
function enable() { function enable() {
command.on(self, 'mtag', { command.on(self, 'mtag', {
cmd: function cmd (sender, command, args){ cmd: function cmd(sender, command, args) {
var subcommand = args[0]; var subcommand = args[0];
switch (subcommand) { switch (subcommand) {
case 'reload': case 'reload':
@ -59,18 +59,18 @@ function enable() {
break; break;
} }
}, },
tab: function tab (sender, command, args){ tab: function tab(sender, command, args) {
return ['reload']; return ['reload'];
} }
}) });
bukkit.players(function (p) fakeTag.set(p)); bukkit.players(function (p) fakeTag.set(p));
event.on(self, 'PlayerJoin', function (event) fakeTag.set(event.player)); event.on(self, 'PlayerJoin', function (event) fakeTag.set(event.player));
var entityUpdate = function (event) { var entityUpdate = function (event) {
var player = event.entity || event.player; var player = event.entity || event.player;
if(player instanceof org.bukkit.entity.Player){ if (player instanceof org.bukkit.entity.Player) {
setTimeout(function () { setTimeout(function () {
fakeTag.update(player); fakeTag.update(player);
}, 1); }, 1);
} }
}; };
event.on(self, 'EntityRegainHealth', entityUpdate, false); event.on(self, 'EntityRegainHealth', entityUpdate, false);
@ -99,7 +99,7 @@ function FakeTag(name) {
try { try {
// 注册tag对象 // 注册tag对象
mainScoreboard.registerObjective(name, new ScoreboardBaseCriteria(name)); mainScoreboard.registerObjective(name, new ScoreboardBaseCriteria(name));
} catch (ex){ } catch (ex) {
// ignore 忽略创建错误 eg: java.lang.IllegalArgumentException: An objective with the name 'xxxxx' already exists! // ignore 忽略创建错误 eg: java.lang.IllegalArgumentException: An objective with the name 'xxxxx' already exists!
} }
var objective = mainScoreboard.getObjective(name); var objective = mainScoreboard.getObjective(name);
@ -118,24 +118,24 @@ function FakeTag(name) {
sendPacket(player, cache.objective); sendPacket(player, cache.objective);
sendPacket(player, cache.display); sendPacket(player, cache.display);
this.update(player); this.update(player);
} };
this.update = function (player){ this.update = function (player) {
var score = mainScoreboard.getPlayerScoreForObjective(player.name, objective); var score = mainScoreboard.getPlayerScoreForObjective(player.name, objective);
score.setScore(player.getHealth()); score.setScore(player.getHealth());
var scorePack = new PacketPlayOutScoreboardScore(score); var scorePack = new PacketPlayOutScoreboardScore(score);
//把其他玩家缓存的包发给这个玩家 //把其他玩家缓存的包发给这个玩家
bukkit.players(function (t) { bukkit.players(function (t) {
sendPacket(t, scorePack); sendPacket(t, scorePack);
if (t.name != player.name) { if (t.name !== player.name) {
var outher = mainScoreboard.getPlayerScoreForObjective(t.name, objective); var outher = mainScoreboard.getPlayerScoreForObjective(t.name, objective);
outher.setScore(t.getHealth()); outher.setScore(t.getHealth());
sendPacket(player, new PacketPlayOutScoreboardScore(outher)); sendPacket(player, new PacketPlayOutScoreboardScore(outher));
} }
}); });
} };
this.disable = function (){ this.disable = function () {
// 注销tag对象 // 注销tag对象
mainScoreboard.unregisterObjective(objective); mainScoreboard.unregisterObjective(objective);
} }