思路
通过Robot类可以模拟点击事件,但是像素坐标是绝对位置,每次都不一样。
借助模拟器的快捷键位设置就可以将坐标相对化。下图是雷电模拟器例子
可以看到图中的快捷键。
最后便是如果Robot要执行模拟器中对应的快捷键,有个前提条件:该模拟器窗口必须位于当前窗口。
这个可以借助Java的JNA实现,操作窗口。
依赖
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.8.0</version>
</dependency>
代码例子
package com.xiaowuqin;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import java.awt.*;
import java.awt.event.KeyEvent;
public class main {
private static WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, "雷电模拟器");//获得窗口句柄
private static Robot robot;
static {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
long count=0;
Thread.sleep(2000);
while(true){
System.out.println("第"+(++count)+"场战斗");
fastPlay(robot);
}
}
static void findWindows(){//将指定窗口句柄设置为当前窗口
if(hwnd==null){
System.out.println("窗口未找到");
}else{
User32.INSTANCE.ShowWindow(hwnd, 9);
User32.INSTANCE.SetForegroundWindow(hwnd); // bring to front
}
}
static void minWindows(){//最小化窗口
User32.INSTANCE.ShowWindow(hwnd, 6);
}
private static void fastPlay(Robot robot) throws InterruptedException {
altq(robot);
Thread.sleep(8000);
//战斗按钮
// altw(robot);
// Thread.sleep(500);
// //精灵按钮
//
// alte(robot);
// Thread.sleep(500);
//
// altR(robot);
// Thread.sleep(9000);
// //出战
alte(robot);
Thread.sleep(7000);
//一技能按钮
altq(robot);
Thread.sleep(1000);
altq(robot);
Thread.sleep(1000);
altq(robot);
Thread.sleep(1000);
altq(robot);
Thread.sleep(1000);
}
//alt+r
private static void altR(Robot robot) {
findWindows();
robot.keyPress(KeyEvent.VK_ALT);
for(int i=1;i<=2;i++)
{
robot.keyPress(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_R);
}
robot.keyRelease(KeyEvent.VK_ALT);
//minWindows();
}
//alt+e
private static void alte(Robot robot) {
findWindows();
robot.keyPress(KeyEvent.VK_ALT);
for(int i=1;i<=2;i++)
{
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
}
robot.keyRelease(KeyEvent.VK_ALT);
//minWindows();
}
//alt+w
private static void altw(Robot robot) {
findWindows();
robot.keyPress(KeyEvent.VK_ALT);
for(int i=1;i<=2;i++)
{
robot.keyPress(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_W);
}
robot.keyRelease(KeyEvent.VK_ALT);
//minWindows();
}
//alt+Q
private static void altq(Robot robot) {
findWindows();
robot.keyPress(KeyEvent.VK_ALT);
for(int i=1;i<=2;i++)
{
robot.keyPress(KeyEvent.VK_Q);
robot.keyRelease(KeyEvent.VK_Q);
}
robot.keyRelease(KeyEvent.VK_ALT);
//minWindows();
}
}