Andy Malakov software blog

Saturday, June 13, 2009

Writing game bot in Java

Can Java be used to write a simple MMORPG game bots?

Easily. Java has a class java.awt.Robot that is intended for writing automated tests and provides just what we need.

First, lets create a bot that will keep an eye on your character's health status. The basic idea is very simple - when health status is running low, drink a healing potion. Repeat. This simple script covers your back and releases your mind from some routine actions. You will concentrate on attacking your opponent ;-)

import java.awt.Color;
import java.awt.Robot;
import java.awt.Toolkit;
import static java.awt.event.KeyEvent.*;

private Toolkit toolkit = Toolkit.getDefaultToolkit();
private Robot robot = new Robot();


We need two type of things:

  1. Inspect some area of the screen that shows your character health's status (usually appears as some sort of progress bar). We just need to know when some pixel inside the bar is getting black:
    boolean isBlack (int x, int y) {
    Color c = robot.getPixelColor (x, y);
    return c.getRed() < 16 && c.getGreen() < 16 && c.getBlue() < 16;
    }

  2. Simulating keyboard action is also easy (we need to press a hotkey for your healing potions)
    void key (int keyCode, long duration) throws InterruptedException {
    robot.keyPress(keyCode);
    Thread.sleep(duration);
    robot.keyRelease(keyCode);
    }

Now the program itself is trivial:
while (true) {
if (isBlack (90, 760))
key (VK_F1, 500);

Thread.sleep (50);
}


Here I assume that your healing potions are assigned to hotkey F1 (KeyEvent.VK_F1) and coordinates {90, 760} show your health status and become black when health is below 25% (your can use Paint or some other program to analyze game's screen shot).


Similar approach can be used to automate other tedious MMORPG tasks (mining gold, fishing, or gaining experience).


P.S. Take a look at this guy's screen (like a Boeing cockpit).



DISCLAIMER:Check your game's license before using this technique. It may be prohibited as something that gives unfair advantage over other players.