Creating a robot in Java with Robocode

Robocode is a programming game where you get to build a robot to battle with other robots. It supports the Java programming language and the .NET framework. We will use the Java programming language in this example.

Download Robocode from http://sourceforge.net/projects/robocode/files/robocode/ and run it. Select Robot->Editor and select File->New->Robot in the Robot Editor. Give your robot a nice name (for example, “Robocop”) and click “OK”. You may use the same package name for your robot.

You should get something similar to the following snippet of code.

package Robocop;
import robocode.*;
//import java.awt.Color;

// API help : http://robocode.sourceforge.net/docs/robocode/robocode/Robot.html

/**
 * Robocop - a robot by Ferhat
 */
public class Robocop extends Robot
{
	/**
	 * run: Robocop's default behavior
	 */
	public void run() {
		// Initialization of the robot should be put here

		// After trying out your robot, try uncommenting the import at the top,
		// and the next line:

		// setColors(Color.red,Color.blue,Color.green); // body,gun,radar

		// Robot main loop
		while(true) {
			// Replace the next 4 lines with any behavior you would like
			ahead(100);
			turnGunRight(360);
			back(100);
			turnGunRight(360);
		}
	}

	/**
	 * onScannedRobot: What to do when you see another robot
	 */
	public void onScannedRobot(ScannedRobotEvent e) {
		// Replace the next line with any behavior you would like
		fire(1);
	}

	/**
	 * onHitByBullet: What to do when you're hit by a bullet
	 */
	public void onHitByBullet(HitByBulletEvent e) {
		// Replace the next line with any behavior you would like
		back(10);
	}

	/**
	 * onHitWall: What to do when you hit a wall
	 */
	public void onHitWall(HitWallEvent e) {
		// Replace the next line with any behavior you would like
		back(20);
	}
}

The Robocode API supports a lot of calls for manipulating your robot. For example, the onScannedRobot event handler can be used to fire towards an enemy robot when the enemy robot has been scanned by your radar. The energy of your robot will increase if you hit an enemy robot and the energy of the enemy robot will decrease if it gets hit.

Select Compiler->Compile to compile your program. Select Battle->New and add your robot and a few sample robots to the battle and click “Start Battle”. The robots will battle with each other and a ranking will be displayed after 10 rounds.

Robot battle

 

This entry was posted in Java and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?