Excession/DiveBomber

From Robowiki
< Excession
Revision as of 00:44, 5 June 2008 by Excession (talk | contribs) (submitted code)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
package excession.drones;

import static java.lang.Math.PI;
import static java.lang.Math.atan2;
import static java.lang.Math.sqrt;
import static java.lang.Math.toRadians;
import static robocode.util.Utils.normalRelativeAngle;
import robocode.AdvancedRobot;
import robocode.ScannedRobotEvent;

/**
 * A drone that spirals in towards and then circles its enemy and fires pot
 * shots.
 * 
 * @author Allan Halme
 * @version 1.0, 2008-06-04
 */
public class SpiralCircle extends AdvancedRobot {

    private int direction = 1;

    private void init() {
        setAdjustRadarForRobotTurn(true);
        setAdjustGunForRobotTurn(true);
        setAdjustRadarForGunTurn(true);
    }

    @Override
    public void run() {
        init();
        setTurnRadarRightRadians(2 * PI);
        while (true) {
            execute();
        }
    }

    @Override
    public void onScannedRobot(ScannedRobotEvent event) {
        lockOnTarget(event);
        aimAndFire(event);
        move(event);
    }

    private void move(ScannedRobotEvent event) {
        double bearing = event.getBearingRadians();
        double r = event.getDistance();

        if (getVelocity() == 0.0) {
            direction *= -1;
        }

        final double SPEED = 20.0;
        final double DISTANCE_MAX = 50;
        final double DISTANCE_MIN = 40;

        double spiral = 0;
        if (r > DISTANCE_MAX) {
            spiral = toRadians(45);
        } else if (r < DISTANCE_MIN) {
            spiral = toRadians(-5);
        }

        double d = SPEED;
        final double b = sqrt(r * r - (d * d) / 4);
        double alpha = atan2(b, (d / 2));
        double tankTurn = bearing - alpha + spiral * direction;

        setTurnRightRadians(tankTurn);
        setAhead(d * direction);
    }

    /**
     * @see http://testwiki.roborumble.org/w/index.php?title=Radar#Wide_lock
     */
    private void lockOnTarget(ScannedRobotEvent event) {
        double absoluteBearing = getHeadingRadians() + event.getBearingRadians();
        double radarTurn = normalRelativeAngle(absoluteBearing - getRadarHeadingRadians());
        double arcToScan = Math.min(Math.atan(36.0 / event.getDistance()), PI / 4.0);
        radarTurn += (radarTurn < 0) ? -arcToScan : arcToScan;
        setTurnRadarRightRadians(radarTurn);
    }

    private void aimAndFire(ScannedRobotEvent event) {
        double absoluteBearing = getHeadingRadians() + event.getBearingRadians();
        double gunTurn = normalRelativeAngle(absoluteBearing - getGunHeadingRadians());
        setTurnGunRightRadians(gunTurn);

        final double power = 3.0;
        if (getGunHeat() == 0.0) {
            setFire(power);
        }
    }
}