package crazy; import robocode.*; import java.awt.Color; import java.awt.geom.Point2D; import robocode.util.Utils; /** * CrazyTracker2 - a robot by Ben Pringle */ public class CrazyTracker2 extends AdvancedRobot { static double FORWARD = 1;//choose forward or backward static double rand = 185;//a random number that changes /** * CrazyTracker2's run method */ public void run() { setColors(Color.blue,Color.black,Color.yellow); setAdjustGunForRobotTurn(true);//allow gun and radar setAdjustRadarForGunTurn(true);//free movement while (true) { turnRadarRight(360);//scan for enemies } } /** * onScannedRobot: We have a target. Go get it. */ public void onScannedRobot(ScannedRobotEvent e) { //here I use an oscillating movement pattern, but //I use a constant "rand" that I change randomly //so that Patternmatchers can't lock onto me if (getDistanceRemaining() == 0) { FORWARD = -FORWARD; setAhead(rand * FORWARD);} setTurnRightRadians(e.getBearingRadians() +Math.PI/2-0.5236*FORWARD *(e.getDistance()>200?1:-1)); //here I get my enemy's statistics so that I can use //linear targeting double bulletPower = Math.min(3.0,getEnergy()); double myX = getX(); double myY = getY(); double absoluteBearing = getHeadingRadians() + e.getBearingRadians(); double enemyX = getX() + e.getDistance() * Math.sin(absoluteBearing); double enemyY = getY() + e.getDistance() * Math.cos(absoluteBearing); double enemyHeading = e.getHeadingRadians(); double enemyVelocity = e.getVelocity(); //now I do my calculations for linear targeting so that //I know where my enemy will be once my bullet gets there double deltaTime = 0; double battleFieldHeight= getBattleFieldHeight(),battleFieldWidth= getBattleFieldWidth(); double predictedX = enemyX, predictedY = enemyY; while((++deltaTime)*(20.0 - 3.0*bulletPower) <Point2D.Double.distance(myX, myY, predictedX, predictedY)){ predictedX += Math.sin(enemyHeading) * enemyVelocity; predictedY += Math.cos(enemyHeading) * enemyVelocity; if( predictedX < 18.0 || predictedY < 18.0 || predictedX > battleFieldWidth - 18.0 || predictedY > battleFieldHeight - 18.0){ predictedX = Math.min(Math.max(18.0, predictedX), battleFieldWidth - 18.0); predictedY = Math.min(Math.max(18.0, predictedY), battleFieldHeight - 18.0); break;}} double theta = Utils.normalAbsoluteAngle(Math.atan2(predictedX - getX(), predictedY - getY())); //now I can turn my gun... setTurnRadarRightRadians (Utils.normalRelativeAngle(absoluteBearing - getRadarHeadingRadians())); setTurnGunRightRadians(Utils.normalRelativeAngle(theta - getGunHeadingRadians())); //...and fire! fire(3); } /** * onHitByBullet: Randomize my movement */ public void onHitByBullet(HitByBulletEvent e) { //change my movement to throw off patternmatchers rand += Math.random()*5*FORWARD; } }