最近才发现autojs这个宝藏,修改自掘金前辈的代码(juejin.cn/post/709521… ),尝试使用它去完成蚂蚁森林能量收取。话不多说,上代码。
main();
/**
* 需要保持支付宝在未打开状态,且打开后无弹窗,蚂蚁森林在首页应用中展示
*/
function main() {
console.log("等待获取无障碍权限");
auto.waitFor();
console.log("申请截屏权限");
requestScreenCapturePermision();
console.log("打开支付宝");
launchApp("支付宝");
var searchErrorCount = 0;
var target;
while (
!(target = findViewByClassAndText("TextView", "蚂蚁森林")) &&
searchErrorCount < 30
) {
console.log("查找控件中");
searchErrorCount += 1;
}
if (searchErrorCount >= 30) {
toast("长时间未能查寻到【蚂蚁森林】按钮,脚本终止");
console.log("长时间未能查寻到【蚂蚁森林】按钮,脚本终止");
backOut();
return;
}
console.log("找到蚂蚁森林按钮");
randomDelayClick(1, 2, target);
console.log("点击蚂蚁森林按钮");
delay(random(1, 2));
console.log("能量收割机");
energyHarvester();
}
/**
* 申请截屏权限 个别系统需要每次都申请截图权限 子线程自动允许
*/
function requestScreenCapturePermision() {
threads.start(function () {
for (let i = 0; i < 100; i++) {
if (textExists("立即开始")) {
click("立即开始");
threads.currentThread().interrupt();
}
}
});
if (!requestScreenCapture()) {
toast("请允许截图权限后重试");
exit();
}
captureScreen();
}
/**
* 循环获取能量 随机延迟半秒到一秒是为了看起来更像人。。。
* 也许大家会有 为什么没有点击找能量代码的疑惑
* 是因为经过我的测试 #ffc2ff01 这个颜色 不仅在能量球上面有 而且找能量按钮也有这个颜色!
* 于是我只需要用一个找色循环就可以实现收取能量球与进入下一页面两个操作 是不是很牛呢? 嘻嘻嘻
*/
function energyHarvester() {
var image, point, errorCount;
while (true) {
delay(random(0.5, 1));
if (!findViewByClassAndText("Button", "返回我的森林")) {
//截图
image = captureScreen();
//获取能量球颜色坐标
point = findColor(image, "#ffc2ff01", { threshold: 4 });
if (point) {
//获取成功则收取能量
errorCount = 0;
click(point.x, point.y);
console.log("收集能量 : " + point);
continue;
} else {
console.log("能量已收完,下一个");
/**
* 由于找能量按钮是图片,又懒得引入orc去识别文字,所以直接点击坐标,
* 880和1055 分别是水平方向按钮的左右两端距屏幕左侧的距离,
* 1580和1628 分别是竖直方向按钮的上下两端距屏幕顶部的距离,
* 通过random方法随机点击区域内的一个点
*/
var left = 880 * device.width/ 1080;
var right = 1055 * device.width/ 1080;
var top = 1580 * device.height/ 2248;
var bottom = 1628 * device.height/ 2248;
click(random(left, right), random(top, bottom));
console.log("点击找能量");
}
} else {
console.info("能量收集完毕,返回首页");
toast("能量收集完毕,返回首页");
click("返回我的森林");
delay(random(1, 2));
break;
}
}
backOut();
}
//退出软件
function backOut() {
console.log("退出支付宝");
for (let i = 0; i < 3; i++) {
delay(0.5);
back();
}
}
//↓↓↓ 下面是一些工具人方法 用来获取控件、点击、延时之类的
function findViewByClassAndId(name, viewId) {
return className(name).id(viewId).findOne(1000);
}
function findViewByClassAndText(name, s) {
return className(name).text(s).findOne(1000);
}
function randomDelayClick(t1, t2, view) {
delay(random(t1, t2));
randomClickBounds(view);
}
function randomClickBounds(view) {
if (view) {
bounds = view.bounds();
return click(
random(bounds.left, bounds.right),
random(bounds.top, bounds.bottom)
);
}
console.log("randomClickBounds view == null");
return false;
}
function delay(seconds) {
sleep(1000 * seconds);
}
function delayBack(seconds) {
delay(seconds);
back();
}
function textExists(str) {
return textContains(str).exists();
}