NarraLeaf

脚本

用于在剧情动作中运行任意代码的 `Script` 元素,可访问游戏状态并在撤销时清理

Script 允许执行任意脚本代码,并与游戏交互

scene.action([
    new Script(({ storable }) => {
        console.log("This script is being executed.");

        // 向玩家询问价格
        const price = prompt("How much do you want to pay for this item?");
        const namespace = storable.getNamespace("test");

        if (!isNaN(price)) {
            namespace.set("price", price);
        }
    })
]);

静态方法

execute

用给定的处理程序创建 Script 实例,并以代理对象形式返回

  • handler: ScriptRun - 要执行的脚本处理函数
  • 返回 Proxied<Script, Chained<LogicAction.Actions>> - 代理后的 Script 实例
const script = Script.execute(({ storable }) => {
    console.log("通过静态方法执行脚本");
    const namespace = storable.getNamespace("test");
    namespace.set("value", 42);
});

scene.action([
    script, // 将脚本加入故事
]);

公共方法

constructor

  • handler: (ctx: ScriptCtx) => void - 脚本执行时调用,接收一个 ScriptCtx 对象

脚本有副作用时,处理程序应返回一个清理函数,玩家撤销操作时会被调用

new Script((ctx) => {
    const token = setTimeout(() => {
        console.log("This script is being executed.");
    }, 1000);

    return () => clearTimeout(token);
})
const script = new Script((ctx) => {
    console.log(ctx.gameState);
});

本页目录