如何模块化写脚本

HAMI_8194621172 · 6 小时前

回答

Hamibot AI
1
· 6 小时前

Hamibot模块化脚本编写指南

Hamibot提供了一个简单但强大的模块系统,帮助你组织和管理代码。模块化可以让你的脚本结构更清晰、代码更易于维护和复用。

模块系统基础

在Hamibot中,每个文件被视为一个独立的模块,文件和模块是一一对应的。模块之间的变量是隔离的,一个模块中的本地变量不会影响其他模块。

创建模块

  1. 创建一个.js文件作为你的模块
  2. 在模块中定义你需要的函数或变量
  3. 使用module.exports导出需要公开的接口
// 文档地址 https://docs.hamibot.com/

// 创建一个名为 utils.js 的模块
const PI = Math.PI; // 这是私有变量,外部无法访问

// 导出多个函数
module.exports = {
  // 计算圆的面积
  calculateArea: function(radius) {
    return PI * radius * radius;
  },
  
  // 计算圆的周长
  calculateCircumference: function(radius) {
    return 2 * PI * radius;
  },
  
  // 一个工具函数
  formatNumber: function(num) {
    return num.toFixed(2);
  }
};

导入和使用模块

使用require()函数导入其他模块:

// 文档地址 https://docs.hamibot.com/

// 主脚本 main.js
// 导入同一目录下的 utils 模块
var utils = require('utils.js');

// 使用导入的函数
var radius = 5;
var area = utils.calculateArea(radius);
var circumference = utils.calculateCircumference(radius);

toast("半径为 " + radius + " 的圆的面积是 " + utils.formatNumber(area));
toast("周长是 " + utils.formatNumber(circumference));

模块导出的不同方式

你可以根据需要选择不同的导出方式:

1. 导出单个函数

// 文档地址 https://docs.hamibot.com/

// square.js
module.exports = function(width) {
  return {
    area: function() {
      return width * width;
    },
    perimeter: function() {
      return 4 * width;
    }
  };
};

使用方式:

// 文档地址 https://docs.hamibot.com/

var square = require('square.js');
var mySquare = square(4);
toast("正方形面积: " + mySquare.area());

2. 导出单个对象

// 文档地址 https://docs.hamibot.com/

// config.js
module.exports = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  maxRetries: 3
};

注意事项

  1. 文件路径require()中的路径是相对于当前脚本文件的。如果模块在子目录中,需要包含目录名,如require('lib/utils.js')

  2. 在线编辑器限制:在线编辑器暂不支持多文件,可将模块打包为单文件后上传。

  3. 循环依赖:避免模块之间的循环依赖,这可能导致意外行为。

  4. 私有变量:模块内部定义的变量是私有的,不会污染全局命名空间。

  5. 作用域隔离:每个模块在自己的作用域中执行,变量不会互相影响。

实际应用示例

假设你正在编写一个自动点击脚本,可以这样组织代码:

  1. 创建clickUtils.js处理点击操作:
// 文档地址 https://docs.hamibot.com/

module.exports = {
  safeClick: function(x, y) {
    if (click(x, y)) {
      toast("点击成功: " + x + ", " + y);
      return true;
    } else {
      toast("点击失败: " + x + ", " + y);
      return false;
    }
  },
  
  waitForElement: function(id, timeout) {
    timeout = timeout || 5000;
    var startTime = new Date().getTime();
    while (new Date().getTime() - startTime < timeout) {
      var elem = id(id);
      if (elem.exists()) {
        return elem;
      }
      sleep(200);
    }
    return null;
  }
};
  1. 创建main.js作为主脚本:
// 文档地址 https://docs.hamibot.com/

var clickUtils = require('clickUtils.js');

// 使用模块中的工具函数
function main() {
  // 等待登录按钮出现
  var loginBtn = clickUtils.waitForElement('com.example:id/login_btn', 10000);
  if (loginBtn) {
    clickUtils.safeClick(loginBtn.bounds().centerX(), loginBtn.bounds().centerY());
  } else {
    toast("登录按钮未找到");
  }
}

main();

通过模块化组织代码,你可以将复杂的功能分解为更小、更易管理的部分,提高代码的可读性和可维护性。

ℹ️ 本回答由 AI 生成,内容仅供参考