欢迎光临散文网 会员登陆 & 注册

MDT-JS模组制作入门

2022-07-17 23:11 作者:NullPointerErr  | 我要投稿

前言

在MDT里,json-mod能达到的效果相对有限,而js-mod相对来说比较自由。在这里,我们先来简单的入个门,语法用的是Rhino.js。

制作前提

所有文件都应放置在你模组根目录下的`scripts/*`里,且必须要有一个模组的入口,命名为`main.js`

内容创建

内容的创建可以有如下的两种形式,中括号([])内的内容可选,现在MDT已经不支持`extendContent`函数

// 形式1
const @1 = extend(@2[, @3], {[@4]})
@5

// 形式2
const @1 = new @2([@3])
@5

在MDT里,js代码结尾处可以不用加分号(;)

  • @1:内容所拥有的变量名

  • @2:类名,内容的类型

    若是你欲制作类型本来在源码中存在,却无法使用,可以尝试使用(Packages.包名.类型进行使用)

  • @3:可选 内容构造时需要传入的参数(可以没有或者有多个,参数间以逗号(,)隔开,要传入的参数请自行阅读源码)

  • @4:可选 用于覆盖内容原先拥有的函数等

  • @5:其他的代码,如修改内容的其他属性,或其他的内容

内容导出/引用

内容的导出和引用可以更好的来分类文件,至少看起来不是很乱。当然也可以不用,你可以把全部的内容全部写在js模组入口`main.js`

导出

至少我看的其他js-mod大多数都是这么干的

// 形式1
exports.@1 = @1
[/*或者更多, 以换行符隔开*/]

// 形式2
module.exports = {
	@1 : @1[, /*或者更多, 用半角逗号(,)隔开*/]
}

引用

路径的后面直接写文件干名称,不用后缀;在其他与`main.js`不同目录所用的文件引用,均以`main.js`为开始目录(其实就是把其他文件换了一个地方执行)

const @1 = require('路径')
[/*或更多*/]

// 后续的使用
@1.导出的内容

其他

全局可用的函数/变量

这个文件可在`Mindustry-master\core\assets\scripts\global.js`找到

//Generated class. Do not modify.

"use strict";

let scriptName = "base.js"
let modName = "none"

const log = (context, obj) => Vars.mods.scripts.log(context, String(obj))
const print = text => log(modName + "/" + scriptName, text)

const newFloats = cap => Vars.mods.getScripts().newFloats(cap);

//these are not strictly necessary, but are kept for edge cases
const run = method => new java.lang.Runnable(){run: method}
const boolf = method => new Boolf(){get: method}
const boolp = method => new Boolp(){get: method}
const floatf = method => new Floatf(){get: method}
const floatp = method => new Floatp(){get: method}
const cons = method => new Cons(){get: method}
const prov = method => new Prov(){get: method}
const func = method => new Func(){get: method}

const newEffect = (lifetime, renderer) => new Effect.Effect(lifetime, new Effect.EffectRenderer({render: renderer}))
Call = Packages.mindustry.gen.Call

//js 'extend(Base, ..., {})' = java 'new Base(...) {}'
function extend(/*Base, ..., def*/){
    const Base = arguments[0]
    const def = arguments[arguments.length - 1]
    //swap order from Base, def, ... to Base, ..., def
    const args = [Base, def].concat(Array.from(arguments).splice(1, arguments.length - 2))

    //forward constructor arguments to new JavaAdapter
    const instance = JavaAdapter.apply(null, args)
    //JavaAdapter only overrides functions; set fields too
    for(var i in def){
        if(typeof(def[i]) != "function"){
            instance[i] = def[i]
        }
    }
    return instance
}

...

后言

既然你想制作js-mod,那源码的阅读能力总要有吧,源码可以去serctl.com辅助下载,如果你连GitHub都登不上的话就踢我吧。

在java中可以省去的东西在js中要写完整,比如在源码中有一段是这样的`ui.listfrag.toggle()`,你需要找到这个消失的东西并且改写成这样`Vars.ui.listfrag.toggle()`,一般都可以在Vars(MDT源码中)或者Core(Arc源码中)文件里找到


MDT-JS模组制作入门的评论 (共 条)

分享到微博请遵守国家法律