05 March 2012

Robocode - Learning Java made Entertaining

I know, that learning programming can be very frustrating for many people. I remember in my technical high school, we had many students struggling with learning programming above a certain level.
Very often this happens for two reasons:
  1. It becomes very repetitive and doesn't allow you to be creative
  2.  It is hard to find a new challenge
Robocode tries to solve these two problems.
Robocode is a programming game, where the goal is to develop a robot battle tank to battle against other tanks in Java or .NET. The robot battles are running in real-time and on-screen.
So you try to program a logic for your robot, to destroy the enemy robot(s).  Sounds like every little boys dream, doesn't it? The start is very easy and you have a huge resource on bots you can fight against, which requires to advance and refine your strategies more and more.

In Robocode you can mainly do four things:
  1. Turn and move your Robot
  2. Turn your gun
  3. Turn your radar
  4. Shoot


With every shot you fire you invest your own life/energy, but if your shot hits, you gain three times as much energy and the enemy loses four times as much energy. This way you don't go around wasting your energy.
Here is an Example of a simple Robot:
 
package tobijdc;
import robocode.*;
import java.awt.Color;

/**
 * TDTBot - a robot by tobijdc
 */
public class TDTBot extends AdvancedRobot
{
 private static final int MAX_DISTANCE = 550;

 public void run() {
  setColors(Color.pink,Color.black,Color.white);
  setTurnGunLeft(Double.POSITIVE_INFINITY);
  while(true) {
   setAhead(1000);
   execute();
  }
 }

 public void onScannedRobot(ScannedRobotEvent e) {
  if(e.getDistance() < MAX_DISTANCE){
   setFire(Math.min(3,getEnergy()/10));
  }
 }

 public void onHitWall(HitWallEvent e){
  setTurnLeft(90 - e.getBearing());
 }

 public void onHitByBullet(HitByBulletEvent e) {
  setTurnLeft(90 - e.getBearing());
 }
}

So first I tell the Robot to turn it's gun (together with it's Radar) for, well Infinity ^^. After that he will just move straight on. If it finds a Robot (onScannedRobot) it shoots it (as long as it is not too far away). The energy investment is 3 (the maximum), except when we drop below a certain level of health (on witch it decreases it's energy investment). If it hits the Wall, it turns parallel to it and continues driving along the wall. If it gets shot, it turns 90 degrees in regards to the bullet, this way it can move away from future bullets effectively.

If you want to learn more about Robocode, visit the Robocode-Wiki, it has tutorials and information about many strategies.

If you manage to defeat my TDTBot, comment or PM me and I'll send you my current robot to give you a real challenge ^^.

No comments:

Post a Comment