我的程序的一部分需要查看屏幕上某个点的颜色是否等于某个颜色,然后执行一个动作。我不知道如何不断检查屏幕上的点以查看颜色是否发生变化。任何帮助将不胜感激!
static Color coal1 = new Color(19, 19, 18); //color i want to match up
int xRock = gameSquare.x + x_scale; // points on the screen
int yRock = gameSquare.y + y_scale;
java.awt.Color c = robot.getPixelColor(xRock, yRock);//finds the rgb color of the point
if (!c.equals(coal1)){ //this is the part where I am stuck!
}
我希望它继续循环,直到 c 不再等于coal1。提前致谢!
编辑:新问题是我无法通过 c 发送以检查它是否 = 到煤炭 1。
新代码(主体)
package Restart;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;
import java.util.Timer;
public class MineCoal {
public static Rectangle gameSquare;
public static boolean runningMine = true;
static Timer timer = new Timer("Printer");
static MyTask t = new MyTask();
public static void main(String[] args) throws InterruptedException {
lookCoal();
}
public static void lookCoal() throws InterruptedException{
Thread.sleep(2000);
try {
Robot robot = new Robot();
while(runningMine == true){
gameSquare = new Rectangle(287,139,551,356); //== game square
BufferedImage img = robot.createScreenCapture(gameSquare);
WritableRaster r = img.getRaster();
DataBuffer db = r.getDataBuffer();
DataBufferInt dbi = (DataBufferInt)db;
int[] data = dbi.getData();
for (int x_scale = 0; x_scale < gameSquare.width; x_scale += 1) {
for(int y_scale = 0; y_scale < gameSquare.height; y_scale += 1) {
int rgb = data[x_scale + gameSquare.width * y_scale];
if ( (rgb == -15658737)||(rgb ==-15527150) ){ //finds coal
//checkinv();
if (runningMine == true){
runningMine = false;
int xRock = gameSquare.x + x_scale; // sets the x and y of the point
int yRock = gameSquare.y + y_scale;
robot.mouseMove(xRock, yRock);
java.awt.Color c = robot.getPixelColor(xRock, yRock); // gets the color of the point
System.out.println(c);
Thread.sleep(500);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(1000);
System.out.println("Found Rock");
timer.schedule(t, 0, 2000); //this goes to check if the point has changed colors but I can not send c through
}
}
}
}
}
}
catch(AWTException e) {
e.printStackTrace();
}
}
}
定时器类
package Restart;
import java.awt.Color;
import java.util.TimerTask;
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
static Color coal1 = new Color(19, 19, 18);
public void run() {
if (coal1.equals(c)) { //I can not get the c from the other class to compair with coal1
System.out.println("color is the same");
}
else {
System.out.println("color changed");
//Stop Timer.
this.cancel();
}
}
}