Esempio n. 1
0
 public void onScannedRobot(ScannedRobotEvent event) {
   a = Utils.normalRelativeAngle(getHeadingRadians() + event.getBearingRadians());
   e = event.getEnergy();
   d = event.getDistance();
   x = d * Math.sin(a);
   y = d * Math.cos(a);
   h = event.getHeadingRadians();
   dh = -Utils.normalRelativeAngle(getGunHeadingRadians() - a);
 }
Esempio n. 2
0
  public void onScannedRobot(ScannedRobotEvent e) {
    robotLocation = new Point2D.Double(getX(), getY());
    enemyAbsoluteBearing = getHeadingRadians() + e.getBearingRadians();
    enemyDistance = e.getDistance();
    enemyLocation = vectorToLocation(enemyAbsoluteBearing, enemyDistance, robotLocation);

    // Change direction at random
    if (Math.random() < 0.015) {
      movementLateralAngle *= -1;
    }
    move();
    execute();

    // radar
    setTurnRadarRightRadians(
        Utils.normalRelativeAngle(enemyAbsoluteBearing - getRadarHeadingRadians()) * 2);

    /*
     * Circular Gun from wiki
     */
    double absBearing = e.getBearingRadians() + getHeadingRadians();

    // Finding the heading and heading change.
    double enemyHeading = e.getHeadingRadians();
    double enemyHeadingChange = enemyHeading - oldEnemyHeading;
    oldEnemyHeading = enemyHeading;

    double deltaTime = 0;
    double predictedX = getX() + e.getDistance() * Math.sin(absBearing);
    double predictedY = getY() + e.getDistance() * Math.cos(absBearing);
    while ((++deltaTime) * BULLET_SPEED
        < Point2D.Double.distance(getX(), getY(), predictedX, predictedY)) {

      // Add the movement we think our enemy will make to our enemy's current X and Y
      predictedX += Math.sin(enemyHeading) * (e.getVelocity());
      predictedY += Math.cos(enemyHeading) * (e.getVelocity());

      // Find our enemy's heading changes.
      enemyHeading += enemyHeadingChange;

      // If our predicted coordinates are outside the walls, put them 18
      // distance units away from the walls as we know
      // that that is the closest they can get to the wall (Bots are
      // non-rotating 36*36 squares).
      predictedX = Math.max(Math.min(predictedX, getBattleFieldWidth() - 18), 18);
      predictedY = Math.max(Math.min(predictedY, getBattleFieldHeight() - 18), 18);
    }
    // Find the bearing of our predicted coordinates from us.
    double aim = Utils.normalAbsoluteAngle(Math.atan2(predictedX - getX(), predictedY - getY()));

    // Aim and fire.
    setTurnGunRightRadians(Utils.normalRelativeAngle(aim - getGunHeadingRadians()));
    setFire(BULLET_POWER);

    setTurnRadarRightRadians(Utils.normalRelativeAngle(absBearing - getRadarHeadingRadians()) * 2);
  }
Esempio n. 3
0
 public void wallSmoothing(double absBearing) {
   double goalDirection = absBearing - Math.PI / 2 * moveDirection;
   Rectangle2D fieldRect =
       new Rectangle2D.Double(18, 18, getBattleFieldWidth() - 36, getBattleFieldHeight() - 36);
   while (!fieldRect.contains(
       getX() + Math.sin(goalDirection) * 120, getY() + Math.cos(goalDirection) * 120)) {
     goalDirection += moveDirection * .1;
   }
   double turn = robocode.util.Utils.normalRelativeAngle(goalDirection - getHeadingRadians());
   if (Math.abs(turn) > Math.PI / 2) {
     turn = robocode.util.Utils.normalRelativeAngle(turn + Math.PI);
     setBack(100);
   } else setAhead(100);
   setTurnRightRadians(turn);
 }
 /**
  * Turns this robot to the specified angle (in degrees). The robot will turn to the side with the
  * shortest delta angle to the specified angle.
  *
  * @param angle the angle to turn this robot to
  * @see #heading
  * @see #turnLeft(int)
  * @see #turnRight(int)
  * @see #turnAheadLeft(int, int)
  * @see #turnAheadRight(int, int)
  * @see #turnBackLeft(int, int)
  * @see #turnBackRight(int, int)
  */
 public void turnTo(int angle) {
   if (peer != null) {
     peer.turnBody(Utils.normalRelativeAngle(toRadians(angle) - peer.getBodyHeading()));
   } else {
     uninitializedException();
   }
 }
  private double getRadarTurn() {
    // роботу жизненно необходимо постоянно видеть противника
    // считаем абсолютный угол до противника:
    final double alphaToEnemy = angleTo(getX(), getY(), enemyX, enemyY);
    // считаем направление, на который надо повернуть радар, чтобы противник остался в фокусе:
    final double sign =
        (alphaToEnemy != getRadarHeadingRadians())
            ? signum(Utils.normalRelativeAngle(alphaToEnemy - getRadarHeadingRadians()))
            : 1;

    // добавляем 5 градусов поворта для надёжности и получаем результирующий угол
    return Utils.normalRelativeAngle(alphaToEnemy - getRadarHeadingRadians() + RADIANS_5 * sign);
    // В принципе, прямо здесь можно вызвать setTurnRadarRightRadians, но я противник функций с сайд
    // эффектами и стараюсь
    // минимизировать их количество
  }
Esempio n. 6
0
  public void onScannedRobot(ScannedRobotEvent e) {
    oldRobotLocation.setLocation(robotLocation);
    robotLocation.setLocation(getX(), getY());
    enemyAbsoluteBearing = getHeadingRadians() + e.getBearingRadians();
    enemyDistance = e.getDistance();
    oldEnemyLocation.setLocation(enemyLocation);
    toLocation(enemyAbsoluteBearing, enemyDistance, robotLocation, enemyLocation);

    deltaBearing =
        Utils.normalRelativeAngle(
            absoluteBearing(oldRobotLocation, enemyLocation)
                - absoluteBearing(oldRobotLocation, oldEnemyLocation));

    currentAimFactors =
        aimFactors[aimDirectionSegment()][
            Math.min(
                (int) (enemyDistance / (getBattleFieldWidth() / DISTANCE_SEGMENTS)),
                DISTANCE_SEGMENTS - 1)][
            Math.min(
                (int) (enemyLocation.getY() / (getBattleFieldHeight() / VERTICAL_SEGMENTS)),
                VERTICAL_SEGMENTS - 1)];

    setTurnGunRightRadians(
        Utils.normalRelativeAngle(
            enemyAbsoluteBearing
                + maxEnemyBearing * sign(deltaBearing) * mostVisitedFactor()
                - getGunHeadingRadians()));

    if (getEnergy() > 3.1) {
      Bullet bullet = setFireBullet(3);
      if (bullet != null) {
        Wave wave = new Wave();
        wave.wTime = getTime();
        wave.bearingDelta = deltaBearing;
        wave.oldRLocation.setLocation(robotLocation);
        wave.oldELocation.setLocation(enemyLocation);
        wave.wAimFactors = currentAimFactors;
        addCustomEvent(wave);
      }
    }

    setAhead(getY() > enemyLocation.getY() ? -50 : 50);

    setTurnRadarRightRadians(
        Utils.normalRelativeAngle(enemyAbsoluteBearing - getRadarHeadingRadians()) * 2);
  }
 /** returns the factor index for the statistics array */
 public static int getFactorIndex(Wave wave, Point2D.Double target) {
   double offsetAngle = (absoluteBearing(wave.getOrigin(), target) - wave.getAngle());
   double factor =
       Utils.normalRelativeAngle(offsetAngle)
           / maxEscapeAngle(wave.getVelocity())
           * wave.getDirection();
   return computeBin(factor);
 }
Esempio n. 8
0
  public void onScannedRobot(ScannedRobotEvent e) {
    // ...
    // if(getRadarHeadingRadians() - getGunHeading() == 0)
    //			fire(1);
    // Absolute angle towards target
    double angleToEnemy = getHeadingRadians() + e.getBearingRadians();

    // Subtract current radar heading to get the turn required to face the enemy, be sure it is
    // normalized
    double radarTurn = Utils.normalRelativeAngle(angleToEnemy - getRadarHeadingRadians());

    // Distance we want to scan from middle of enemy to either side
    // The 36.0 is how many units from the center of the enemy robot it scans.
    double extraTurn = Math.min(Math.atan(5.0 / e.getDistance()), Rules.RADAR_TURN_RATE_RADIANS);

    // Adjust the radar turn so it goes that much further in the direction it is going to turn
    // Basically if we were going to turn it left, turn it even more left, if right, turn more
    // right.
    // This allows us to overshoot our enemy so that we get a good sweep that will not slip.
    radarTurn += (radarTurn < 0 ? -extraTurn : extraTurn);

    // Turn the radar
    setTurnRadarRightRadians(radarTurn);

    // is the enemy left or right of us
    double distance = getRadarHeading() - getGunHeading();
    double[] wert = {distance};

    // setTurnGunLeft(encog.Adjust.predict(NETWORK, wert));

    if (distance < 0) setTurnGunRight(distance);

    if (distance >= 0) setTurnGunRight(distance);

    // System.out.println(distance);

    // if enemy is within fire range -> fire
    //	    if (getGunHeading() > getRadarHeading()-2 && getGunHeading() < getRadarHeading()+2)

    setFire(1);

    System.out.println("gunheat:" + getGunHeat());
    if (getGunHeat() == 1.2) {
      LIST.add(getTime());
      System.out.println("distance: " + LIST);
      //	    	int shouldHit = (int) (getTime() + (e.getDistance() / 17));
      //    		System.out.println("when should it hit: " + shouldHit);
    }

    if (LIST.size() != 0) {
      if (LIST.get(0) + (getTime() - LIST.get(0)) * VELOCITY > e.getDistance()) {
        System.out.println("did you hit?: " + getTime());
        LIST.remove(0);
      }
    }

    execute();
  }
Esempio n. 9
0
 private void goTo(Point2D destination) {
   double angle =
       Utils.normalRelativeAngle(
           absoluteBearing(robotLocation, destination) - getHeadingRadians());
   double turnAngle = Math.atan(Math.tan(angle));
   setTurnRightRadians(turnAngle);
   setAhead(robotLocation.distance(destination) * (angle == turnAngle ? 1 : -1));
   // Hit the brake pedal hard if we need to turn sharply
   setMaxVelocity(Math.abs(getTurnRemaining()) > 33 ? 0 : MAX_VELOCITY);
 }
  private double getBodyTurn() {
    // а вот вычисление угла поворота посложее
    final double alphaToMe = angleTo(enemyX, enemyY, getX(), getY());

    // определяем угловое направление относительно противника (по часовой стрелке, либо против) ...
    final double lateralDirection =
        signum(
            (getVelocity() != 0 ? getVelocity() : 1)
                * Math.sin(Utils.normalRelativeAngle(getHeadingRadians() - alphaToMe)));
    // получаем желаемое направление движения
    final double desiredHeading =
        Utils.normalAbsoluteAngle(alphaToMe + Math.PI / 2 * lateralDirection);
    // нормализуем направление по скорости
    final double normalHeading =
        getVelocity() >= 0
            ? getHeadingRadians()
            : Utils.normalAbsoluteAngle(getHeadingRadians() + Math.PI);
    // и возвращаем угол поворта
    return Utils.normalRelativeAngle(desiredHeading - normalHeading);
  }
Esempio n. 11
0
  private void gotoPointandSmooth() {

    Point2D actualPosition = new Point2D.Double(getX(), getY());

    Projection proj =
        new Projection(
            new Point2D.Double(getX(), getY()),
            getHeading(),
            getVelocity(),
            move.ahead,
            getTurnRemaining() + move.turnRight);
    tickProjection t = proj.projectNextTick();

    /* Movement Settings, find the next position */
    double distanceToNewPosition = actualPosition.distance(nextPosition);
    if (move.smooth(t.getPosition(), t.getHeading(), proj.getWantedHeading(), move.ahead)) {
      // out.println("smooth");
      wallSmoothing = true;
      double _turnRight = move.turnRight;
      int _ahead = 100 * move.ahead;

      setAhead(_ahead);
      setTurnRight(_turnRight);
    } else if (distanceToNewPosition < 15 || wallSmoothing == true) {
      wallSmoothing = false;
      PositionFinder p = new PositionFinder(enemies, this);
      // Point2D.Double testPoint = p.findBestPoint(200);
      // double range = distanceToTarget*0.5;
      // Point2D.Double testPoint = p.findBestPointInRange(attempt, range);
      Point2D.Double testPoint = p.findBestPointInRangeWithRandomOffset(200);
      nextPosition = testPoint;
      // out.println("point");
    }

    /* Movement to nextPosition */
    else {
      Double angle =
          org.pattern.utils.Utils.calcAngle(nextPosition, actualPosition) - getHeadingRadians();
      Double direction = 1.0;

      if (Math.cos(angle) < 0) {
        angle += Math.PI;
        direction = -1.0;
      }
      if (direction > 0) move.ahead = 1;
      else move.ahead = -1;
      setAhead(distanceToNewPosition * direction);
      angle = Utils.normalRelativeAngle(angle);
      setTurnRightRadians(angle);
    }
  }
Esempio n. 12
0
  @Override
  public void onScannedRobot(ScannedRobotEvent event) {
    double absoluteBearing = robot.getHeadingRadians() + event.getBearingRadians();
    lastTurnGunRadiansDiff =
        robocode.util.Utils.normalRelativeAngle(absoluteBearing - robot.getGunHeadingRadians());
    robot.setTurnGunRightRadians(lastTurnGunRadiansDiff);

    double MAX_DIST = 1000;
    double dist = Math.min(MAX_DIST, event.getDistance());
    double multi = ((MAX_DIST - dist) / MAX_DIST);
    double firePower = multi * Rules.MAX_BULLET_POWER;
    firePower = Math.max(Rules.MIN_BULLET_POWER, firePower);

    //		System.out.println(String.format("dist: %f, multi: %f, fire: %f", dist, multi, firePower));

    robot.setFire(firePower);
  }
 public static void setBackAsFront(AdvancedRobot robot, double goAngle) {
   double angle = Utils.normalRelativeAngle(goAngle - robot.getHeadingRadians());
   if (Math.abs(angle) > (Math.PI / 2)) {
     if (angle < 0) {
       robot.setTurnRightRadians(Math.PI + angle);
     } else {
       robot.setTurnLeftRadians(Math.PI - angle);
     }
     robot.setBack(100);
   } else {
     if (angle < 0) {
       robot.setTurnLeftRadians(-1 * angle);
     } else {
       robot.setTurnRightRadians(angle);
     }
     robot.setAhead(100);
   }
 }
Esempio n. 14
0
  private void goToPoint(Point2D nextPosition) {

    Point2D actualPosition = new Point2D.Double(getX(), getY());
    Double distanceToNewPosition = actualPosition.distance(nextPosition);
    Double angle =
        org.pattern.utils.Utils.calcAngle(nextPosition, actualPosition) - getHeadingRadians();
    Double direction = 1.0;

    if (Math.cos(angle) < 0) {
      angle += Math.PI;
      direction = -1.0;
    }
    if (direction > 0) move.ahead = 1;
    else move.ahead = -1;
    setAhead(distanceToNewPosition * direction);
    angle = Utils.normalRelativeAngle(angle);
    setTurnRightRadians(angle);
  }
Esempio n. 15
0
  public void onScannedRobot(ScannedRobotEvent e) {
    double absBearing = e.getBearingRadians() + getHeadingRadians();
    setTurnRadarRightRadians(
        FACTOR * robocode.util.Utils.normalRelativeAngle(absBearing - getRadarHeadingRadians()));
    aceInTheHole(e);
    if (getOthers() > 10) {

      doCircling(e);
      wallSmoothing(absBearing);

    } else if (getOthers() < 10 && getOthers() > 1) {
      doStraffing(e);
      wallSmoothing(absBearing);
    } else if (getOthers() == 1) {
      seekAndDestroy(e);
      wallSmoothing(absBearing);
    }
  }
Esempio n. 16
0
    public boolean test() {

      if ((RaikoGun.enemyLocation).distance(firePosition)
          <= (distance += bulletVelocity) + bulletVelocity) {
        try {
          waveGuessFactors[
              (int)
                  Math.round(
                      (Utils.normalRelativeAngle(
                                  absoluteBearing(firePosition, RaikoGun.enemyLocation)
                                      - enemyAbsBearing))
                              / bearingDirection
                          + GF_ZERO)]++;
        } catch (ArrayIndexOutOfBoundsException ignore) {
        }
        bot.removeCustomEvent(this);
      }
      return false;
    }
Esempio n. 17
0
 public boolean test() {
   if (11 * (getTime() - wTime) > oldRLocation.distance(enemyLocation)) {
     double bearingDiff =
         Utils.normalRelativeAngle(
             absoluteBearing(oldRLocation, enemyLocation)
                 - absoluteBearing(oldRLocation, oldELocation));
     wAimFactors[
         (int)
             Math.round(
                 Math.max(
                     0D,
                     Math.min(
                         AIM_FACTORS - 1D,
                         ((sign(bearingDelta) * bearingDiff) / maxEnemyBearing)
                                 * (AIM_FACTORS - 1D)
                                 / 2D
                             + (AIM_FACTORS - 1D) / 2D)))]++;
     removeCustomEvent(this);
   }
   return false;
 }
    public void onStatus(StatusEvent e) {
      final RobotStatus s = e.getStatus();

      others = peer.getOthers();
      energy = Math.max(1, (int) (s.getEnergy() + 0.5));
      robotX = (int) (s.getX() + 0.5);
      robotY = (int) (s.getY() + 0.5);
      heading = (int) (toDegrees(s.getHeading()) + 0.5);
      gunHeading = (int) (toDegrees(s.getGunHeading()) + 0.5);
      gunBearing =
          (int) (toDegrees(Utils.normalRelativeAngle(s.getGunHeading() - s.getHeading())) + 0.5);
      gunReady = (s.getGunHeat() <= 0);

      currentTurn = e.getTime();

      // Auto fire
      if (juniorFirePower > 0 && gunReady && (peer.getGunTurnRemaining() == 0)) {
        if (peer.setFire(juniorFirePower) != null) {
          gunReady = false;
          juniorFirePower = 0;
        }
      }

      // Reset event data
      scannedDistance = -1;
      scannedAngle = -1;
      scannedBearing = -1;
      scannedVelocity = -99;
      scannedHeading = -1;
      scannedEnergy = -1;
      hitByBulletAngle = -1;
      hitByBulletBearing = -1;
      hitRobotAngle = -1;
      hitRobotBearing = -1;
      hitWallAngle = -1;
      hitWallBearing = -1;
    }
Esempio n. 19
0
  public static MovementDecision toMovementDecision(
      LXXRobotState robot, double targetHeading, MovementDirection movementDirection) {
    final double robotHeading =
        movementDirection == MovementDirection.FORWARD
            ? robot.getHeadingRadians()
            : Utils.normalAbsoluteAngle(robot.getHeadingRadians() + LXXConstants.RADIANS_180);
    final double neededTurnRateRadians = Utils.normalRelativeAngle(targetHeading - robotHeading);
    double turnRateRadians = neededTurnRateRadians;
    final double speed = robot.getVelocityModule();
    final double acceleratedSpeed = min(speed + 1, Rules.MAX_VELOCITY);
    if (abs(turnRateRadians) > Rules.getTurnRateRadians(acceleratedSpeed)) {
      turnRateRadians = Rules.getTurnRateRadians(acceleratedSpeed) * signum(turnRateRadians);
    }
    final double acceleration = getAcceleration(robot, turnRateRadians, robotHeading);
    turnRateRadians =
        min(
                abs(neededTurnRateRadians),
                abs(
                    Rules.getTurnRateRadians(
                        LXXUtils.limit(0, speed + acceleration, Rules.MAX_VELOCITY))))
            * signum(turnRateRadians);

    return new MovementDecision(acceleration, turnRateRadians, movementDirection);
  }
Esempio n. 20
0
  public void onScannedRobot(ScannedRobotEvent e) {

    /*-------- setup data -----*/
    if (enemyName == null) {

      enemyName = e.getName();
    }
    Point2D.Double robotLocation = new Point2D.Double(bot.getX(), bot.getY());
    double theta;
    final double enemyAbsoluteBearing = bot.getHeadingRadians() + e.getBearingRadians();
    final double enemyDistance = e.getDistance();
    enemyLocation = projectMotion(robotLocation, enemyAbsoluteBearing, enemyDistance);
    final double enemyEnergy = e.getEnergy();

    Rectangle2D.Double BF = new Rectangle2D.Double(18, 18, 764, 564);

    /*
        To explain the below; if the enemy's absolute acceleration is
        zero then we segment on time since last velocity change, lateral
        acceleration and lateral velocity.
        If their absolute acceleration is non zero then we segment on absolute
        acceleration and absolute velocity.
        Regardless we segment on walls (near/far approach to walls) and distance.
        I'm trying to have my cake and eat it, basically. :-)
    */
    MicroWave w = new MicroWave();

    final double lastLatVel = enemyLatVel;
    double lastVelocity = enemyVelocity;
    enemyLatVel =
        (enemyVelocity = e.getVelocity()) * Math.sin(e.getHeadingRadians() - enemyAbsoluteBearing);

    int distanceIndex = (int) enemyDistance / 140;

    double bulletPower = distanceIndex == 0 ? 3 : 2;
    theta = Math.min(bot.getEnergy() / 4, Math.min(enemyEnergy / 4, bulletPower));
    if (theta == bulletPower) bot.addCustomEvent(w);
    bulletPower = theta;
    w.bulletVelocity = 20D - 3D * bulletPower;

    int accelIndex = (int) Math.round(Math.abs(enemyLatVel) - Math.abs(lastLatVel));

    if (enemyLatVel != 0) bearingDirection = enemyLatVel > 0 ? 1 : -1;
    w.bearingDirection = bearingDirection * Math.asin(8D / w.bulletVelocity) / GF_ZERO;

    double moveTime = w.bulletVelocity * lastVChangeTime++ / enemyDistance;
    int bestGF = moveTime < .1 ? 1 : moveTime < .3 ? 2 : moveTime < 1 ? 3 : 4;

    int vIndex = (int) Math.abs(enemyLatVel / 3);

    if (Math.abs(Math.abs(enemyVelocity) - Math.abs(lastVelocity)) > .6) {
      lastVChangeTime = 0;
      bestGF = 0;

      accelIndex = (int) Math.round(Math.abs(enemyVelocity) - Math.abs(lastVelocity));
      vIndex = (int) Math.abs(enemyVelocity / 3);
    }

    if (accelIndex != 0) accelIndex = accelIndex > 0 ? 1 : 2;

    w.firePosition = robotLocation;
    w.enemyAbsBearing = enemyAbsoluteBearing;
    // now using PEZ' near-wall segment
    w.waveGuessFactors =
        guessFactors[accelIndex][bestGF][vIndex][
            BF.contains(
                    projectMotion(
                        robotLocation,
                        enemyAbsoluteBearing + w.bearingDirection * GF_ZERO,
                        enemyDistance))
                ? 0
                : BF.contains(
                        projectMotion(
                            robotLocation,
                            enemyAbsoluteBearing + .5 * w.bearingDirection * GF_ZERO,
                            enemyDistance))
                    ? 1
                    : 2][
            distanceIndex];

    bestGF = GF_ZERO;

    for (int gf = GF_ONE; gf >= 0 && enemyEnergy > 0; gf--)
      if (w.waveGuessFactors[gf] > w.waveGuessFactors[bestGF]) bestGF = gf;

    bot.setTurnGunRightRadians(
        Utils.normalRelativeAngle(
            enemyAbsoluteBearing
                - bot.getGunHeadingRadians()
                + w.bearingDirection * (bestGF - GF_ZERO)));

    if (bot.getEnergy() > 1 || distanceIndex == 0) bot.setFire(bulletPower);

    bot.setTurnRadarRightRadians(
        Utils.normalRelativeAngle(enemyAbsoluteBearing - bot.getRadarHeadingRadians()) * 2);
  }
 private double getGunTurn() {
   // вычисления тривиальны: считаем на какой угол надо повернуть пушку, чтобы она смотрела прямо
   // на противника:
   return Utils.normalRelativeAngle(
       angleTo(getX(), getY(), enemyX, enemyY) - getGunHeadingRadians());
 }
Esempio n. 22
0
  public void surf() {
    RobotState currentState =
        new RobotState(
            ScanLog.myLocation(),
            _robot.getHeadingRadians(),
            _robot.getVelocity(),
            _robot.getTime());
    boolean goingClockwise = (_lastMovementChoice == CLOCKWISE_OPTION);

    double orbitCounterClockwiseDanger =
        checkDanger(
            currentState, COUNTERCLOCKWISE_OPTION, goingClockwise, FIRST_WAVE, WAVES_TO_SURF);
    double stopDanger =
        checkDanger(currentState, STOP_OPTION, goingClockwise, FIRST_WAVE, WAVES_TO_SURF);
    double orbitClockwiseDanger =
        checkDanger(currentState, CLOCKWISE_OPTION, goingClockwise, FIRST_WAVE, WAVES_TO_SURF);

    int goOrientation = _lastMovementChoice;

    Wave orbitWave = findSurfableWave(FIRST_WAVE);
    double orbitAbsBearing, distanceToClosestWaveSource;

    try {
      distanceToClosestWaveSource = ScanLog.myLocation().distance(orbitWave.sourceLocation);
      orbitAbsBearing = DUtils.absoluteBearing(orbitWave.sourceLocation, ScanLog.myLocation());
    } catch (NullPointerException noSurfableWaves) {
      distanceToClosestWaveSource = ScanLog.getLastDistance();
      orbitAbsBearing = ScanLog.getLastEnemyScan().getAbsBearingRadians();
    }

    double goAngle, attackAngle;
    if (stopDanger == NO_SURFABLE_WAVES) {
      attackAngle = -1.047;
      _robot.setMaxVelocity(8);

      double goAngleCcw =
          orbitAbsBearing + (COUNTERCLOCKWISE_OPTION * ((Math.PI / 2) + attackAngle));
      goAngleCcw =
          wallSmoothing(
              ScanLog.myLocation(),
              goAngleCcw,
              COUNTERCLOCKWISE_OPTION,
              distanceToClosestWaveSource);

      double goAngleCw = orbitAbsBearing + (CLOCKWISE_OPTION * ((Math.PI / 2) + attackAngle));
      goAngleCw =
          wallSmoothing(
              ScanLog.myLocation(), goAngleCw, CLOCKWISE_OPTION, distanceToClosestWaveSource);

      if (Math.abs(Utils.normalRelativeAngle(goAngleCw - orbitAbsBearing))
          < Math.abs(Utils.normalRelativeAngle(goAngleCcw - orbitAbsBearing))) {
        goOrientation = CLOCKWISE_OPTION;
        goAngle = goAngleCw;
      } else {
        goOrientation = COUNTERCLOCKWISE_OPTION;
        goAngle = goAngleCcw;
      }
    } else {
      _robot.setMaxVelocity(8);
      attackAngle = _currentDistancer.attackAngle(distanceToClosestWaveSource, _desiredDistance);

      if (ScanLog.enemyIsRammer()
          && ScanLog.getLastDistance() < 300
          && orbitWave != NO_WAVE_FOUND) {
        if (Utils.normalRelativeAngle(
                DUtils.absoluteBearing(ScanLog.myLocation(), orbitWave.sourceLocation)
                    - ScanLog.getLastScan().getAbsBearingRadians())
            > 0) {
          goOrientation = -1;
        } else {
          goOrientation = 1;
        }
      } else if (stopDanger <= orbitCounterClockwiseDanger
          && stopDanger <= orbitClockwiseDanger
          && !ScanLog.enemyIsRammer()) {

        _robot.setMaxVelocity(0);
      } else {
        if (orbitClockwiseDanger < orbitCounterClockwiseDanger) {
          goOrientation = CLOCKWISE_OPTION;
        } else {
          goOrientation = COUNTERCLOCKWISE_OPTION;
        }
      }

      goAngle = orbitAbsBearing + (goOrientation * ((Math.PI / 2) + attackAngle));
      goAngle =
          wallSmoothing(ScanLog.myLocation(), goAngle, goOrientation, distanceToClosestWaveSource);
    }

    DUtils.setBackAsFront(_robot, goAngle);

    _lastMovementChoice = goOrientation;
  }
Esempio n. 23
0
  public MovSimStat[] futurePos(
      int steps,
      double x,
      double y,
      double velocity,
      double maxVelocity,
      double heading,
      double distanceRemaining,
      double angleToTurn,
      double maxTurnRate,
      double battleFieldW,
      double battleFieldH) {
    // maxTurnRate in degrees
    MovSimStat[] pos = new MovSimStat[steps];
    double acceleration = 0;
    boolean slowingDown = false;
    double moveDirection;

    maxTurnRate = Math.toRadians(maxTurnRate);
    if (distanceRemaining == 0) moveDirection = 0;
    else if (distanceRemaining < 0.0) moveDirection = -1;
    else moveDirection = 1;

    // heading, accel, velocity, distance
    for (int i = 0; i < steps; i++) {
      // heading
      double lastHeading = heading;
      double turnRate =
          Math.min(
              maxTurnRate,
              ((0.4 + 0.6 * (1.0 - (Math.abs(velocity) / systemMaxVelocity))) * systemMaxTurnRate));
      if (angleToTurn > 0.0) {
        if (angleToTurn < turnRate) {
          heading += angleToTurn;
          angleToTurn = 0.0;
        } else {
          heading += turnRate;
          angleToTurn -= turnRate;
        }
      } else if (angleToTurn < 0.0) {
        if (angleToTurn > -turnRate) {
          heading += angleToTurn;
          angleToTurn = 0.0;
        } else {
          heading -= turnRate;
          angleToTurn += turnRate;
        }
      }
      heading = Utils.normalAbsoluteAngle(heading);
      // movement
      if (distanceRemaining != 0.0 || velocity != 0.0) {
        // lastX = x; lastY = y;
        if (!slowingDown && moveDirection == 0) {
          slowingDown = true;
          if (velocity > 0.0) moveDirection = 1;
          else if (velocity < 0.0) moveDirection = -1;
          else moveDirection = 0;
        }
        double desiredDistanceRemaining = distanceRemaining;
        if (slowingDown) {
          if (moveDirection == 1 && distanceRemaining < 0.0) desiredDistanceRemaining = 0.0;
          else if (moveDirection == -1 && distanceRemaining > 1.0) desiredDistanceRemaining = 0.0;
        }
        double slowDownVelocity =
            (double)
                (int)
                    (maxBraking
                        / 2.0
                        * ((Math.sqrt(4.0 * Math.abs(desiredDistanceRemaining) + 1.0)) - 1.0));
        if (moveDirection == -1) slowDownVelocity = -slowDownVelocity;
        if (!slowingDown) {
          if (moveDirection == 1) {
            if (velocity < 0.0) acceleration = maxBraking;
            else acceleration = maxAcceleration;
            if (velocity + acceleration > slowDownVelocity) slowingDown = true;
          } else if (moveDirection == -1) {
            if (velocity > 0.0) acceleration = -maxBraking;
            else acceleration = -maxAcceleration;
            if (velocity + acceleration < slowDownVelocity) slowingDown = true;
          }
        }
        if (slowingDown) {
          if (distanceRemaining != 0.0
              && Math.abs(velocity) <= maxBraking
              && Math.abs(distanceRemaining) <= maxBraking) slowDownVelocity = distanceRemaining;
          double perfectAccel = slowDownVelocity - velocity;
          if (perfectAccel > maxBraking) perfectAccel = maxBraking;
          else if (perfectAccel < -maxBraking) perfectAccel = -maxBraking;
          acceleration = perfectAccel;
        }
        if (velocity > maxVelocity || velocity < -maxVelocity) acceleration = 0.0;
        velocity += acceleration;
        if (velocity > maxVelocity) velocity -= Math.min(maxBraking, velocity - maxVelocity);
        if (velocity < -maxVelocity) velocity += Math.min(maxBraking, -velocity - maxVelocity);
        double dx = velocity * Math.sin(heading);
        double dy = velocity * Math.cos(heading);
        x += dx;
        y += dy;
        // boolean updateBounds = false;
        // if (dx != 0.0 || dy != 0.0) updateBounds = true;
        if (slowingDown && velocity == 0.0) {
          distanceRemaining = 0.0;
          moveDirection = 0;
          slowingDown = false;
          acceleration = 0.0;
        }
        // if (updateBounds) updateBoundingBox();
        distanceRemaining -= velocity;
        if (x < 18 || y < 18 || x > battleFieldW - 18 || y > battleFieldH - 18) {
          distanceRemaining = 0;
          angleToTurn = 0;
          velocity = 0;
          moveDirection = 0;
          x = Math.max(18, Math.min(battleFieldW - 18, x));
          y = Math.max(18, Math.min(battleFieldH - 18, y));
        }
      }
      // add position
      pos[i] =
          new MovSimStat(x, y, velocity, heading, Utils.normalRelativeAngle(heading - lastHeading));
    }
    return pos;
  }
Esempio n. 24
0
  private void checkRobotCollision(List<RobotPeer> robots) {
    for (RobotPeer otherRobot : robots) {
      if (!(otherRobot == null || otherRobot == owner || otherRobot.isDead())
          && otherRobot.getBoundingBox().intersectsLine(boundingLine)) {

        state = BulletState.HIT_VICTIM;
        frame = 0;
        victim = otherRobot;

        double damage = Rules.getBulletDamage(power);
        double score = damage;

        if (score > otherRobot.getEnergy()) {
          score = otherRobot.getEnergy();
        }
        otherRobot.updateEnergy(-damage);

        boolean teamFire =
            (owner.getTeamPeer() != null && owner.getTeamPeer() == otherRobot.getTeamPeer());

        if (!teamFire) {
          owner.getRobotStatistics().scoreBulletDamage(otherRobot.getName(), score);
        }

        if (otherRobot.getEnergy() <= 0) {
          if (otherRobot.isAlive()) {
            otherRobot.kill();
            if (!teamFire) {
              final double bonus = owner.getRobotStatistics().scoreBulletKill(otherRobot.getName());

              if (bonus > 0) {
                owner.println(
                    "SYSTEM: Bonus for killing "
                        + (owner.getNameForEvent(otherRobot) + ": " + (int) (bonus + .5)));
              }
            }
          }
        }
        owner.updateEnergy(Rules.getBulletHitBonus(power));

        Bullet bullet = createBullet(false);

        otherRobot.addEvent(
            new HitByBulletEvent(
                robocode.util.Utils.normalRelativeAngle(
                    heading + Math.PI - otherRobot.getBodyHeading()),
                bullet));

        owner.addEvent(
            new BulletHitEvent(owner.getNameForEvent(otherRobot), otherRobot.getEnergy(), bullet));

        double newX, newY;

        if (otherRobot.getBoundingBox().contains(lastX, lastY)) {
          newX = lastX;
          newY = lastY;

          setX(newX);
          setY(newY);
        } else {
          newX = x;
          newY = y;
        }

        deltaX = newX - otherRobot.getX();
        deltaY = newY - otherRobot.getY();

        break;
      }
    }
  }
  /** onScannedRobot: What to do when you see another robot */
  public void onScannedRobot(ScannedRobotEvent e) {
    System.out.println("START at : " + getTime() + " onScannedRobot----------------------------");
    String nnn = e.getName();
    System.out.println("scan " + nnn);
    double eneX =
        getX() + Math.sin(e.getBearingRadians() + Math.toRadians(getHeading())) * e.getDistance();
    double eneY =
        getY() + Math.cos(e.getBearingRadians() + Math.toRadians(getHeading())) * e.getDistance();
    Enemy_info enem = null;
    if (!isTeammate(nnn)) {
      // 味方への情報送信
      try {
        broadcastMessage(
            nnn
                + ", "
                + e.getBearing()
                + ", "
                + e.getBearingRadians()
                + ", "
                + e.getDistance()
                + ", "
                + e.getEnergy()
                + ", "
                + e.getHeading()
                + ", "
                + e.getHeadingRadians()
                + ", "
                + e.getVelocity()
                + ", "
                + eneX
                + ", "
                + eneY);
      } catch (IOException ignored) {
      }
      // スキャンした車両がLocal敵リストにいるかどうかのフラグ
      boolean flag = false;
      System.out.println("send scanned info");
      // スキャンした敵がLocal敵リストの中に存在するか
      for (Enemy_info temp : enes) {
        if (nnn.equals(temp.get_en_name())) {
          flag = true;
          enem = temp;
          // Local敵リストのアップデート
          temp.updateInformation(
              e.getBearing(),
              e.getBearingRadians(),
              e.getDistance(),
              e.getEnergy(),
              e.getHeading(),
              e.getHeadingRadians(),
              e.getVelocity(),
              eneX,
              eneY);
          System.out.println("	update scanned Info");
        }
      }
      // スキャンした敵がLocal敵リストの中に存在しない場合
      if (!flag) {
        // Local敵リストに新規追加
        enem =
            new Enemy_info(
                nnn,
                e.getBearing(),
                e.getBearingRadians(),
                e.getDistance(),
                e.getEnergy(),
                e.getHeading(),
                e.getHeadingRadians(),
                e.getVelocity(),
                eneX,
                eneY);
        enes.add(enem);
        System.out.println("	add scanned info");
      }
      if (enemy_detected == false) {
        // 共通の敵が設定されていない場合
        enemy_detected = true;
        target_enemy = enem;
        try {
          broadcastMessage("Kill , " + target_enemy.get_en_name() + ", !!");
        } catch (IOException ignored) {
        }
      }

      if (enemy_detected == true) {
        try {
          double enemyX = target_enemy.get_en_expX();
          double enemyY = target_enemy.get_en_expY();
          setTurnRadarLeftRadians(getRadarTurnRemainingRadians());

          System.out.println("abs : eX " + enemyX + " : " + "eY " + enemyY);

          // 共通の敵が設定されている場合
          double enemyBearing = Math.atan((enemyX - getX()) / (enemyY - getY()));
          // if(enemyBearing<0){
          // 	System.out.println("change");
          // 	enemyBearing = Math.PI*2 + enemyBearing;
          // }else if (enemyBearing < Math.PI){

          // }
          // System.out.println("atan " + Math.atan((eneY-getY())/(eneX-getX())));
          // System.out.println("atan1 " + Math.atan((eneX-getX())/(eneY-getY())));
          // System.out.println("trueeee " + (e.getBearingRadians() + this.getHeadingRadians()));
          System.out.println(
              "enerad"
                  + enemyBearing
                  + " ?= "
                  + "enemyBearing "
                  + (this.getHeadingRadians() + e.getBearingRadians()));
          System.out.println(enemyBearing + Math.PI);
          double enemyHeading = target_enemy.get_en_heading(); // 敵の向き
          System.out.println("enemy heading:" + enemyHeading);
          // double enemyBearing = this.getHeadingRadians() +
          // target_enemy.get_en_bearingRadians();// 自分と敵の角度

          // double enemyX = target_enemy.get_en_distance() * Math.sin(enemyBearing);
          // double enemyY = target_enemy.get_en_distance() * Math.cos(enemyBearing);

          enemyX = enemyX - getX();
          enemyY = enemyY - getY();
          System.out.println("Relative : eX " + enemyX + " : " + "eY " + enemyY);

          double battlefieldWidh = getBattleFieldWidth(); // フィールド幅
          double battlefieldHeight = getBattleFieldHeight(); // フィールド高さ

          boolean isHeadingToCenter = (int) enemyHeading % 90 == 0; // 中心を向いている
          boolean isOnWall =
              nearlyEquals(enemyX, 18)
                  || nearlyEquals(enemyX + 18, battlefieldWidh)
                  || nearlyEquals(enemyY, 18)
                  || nearlyEquals(enemyY + 18, battlefieldHeight); // 壁に張り付いている

          // 中心を向いている&&壁際にいる(=Walls)なら射撃
          if (isHeadingToCenter && isOnWall) {
            System.out.println("Walls!!");
          }

          double dis = 0;
          double heading = lastEnemyHeading;
          do {
            dis += Rules.getBulletSpeed(power);
            heading += target_enemy.get_en_headingRadians() - lastEnemyHeading;
            enemyX += target_enemy.get_en_velocity() * Math.sin(heading);
            enemyY += target_enemy.get_en_velocity() * Math.cos(heading);
          } while (dis < Point2D.distance(0, 0, enemyX, enemyY)); //

          // 相対角度に変換した上で砲塔の向きを変える
          setTurnGunRightRadians(
              Utils.normalRelativeAngle(Math.atan2(enemyX, enemyY) - getGunHeadingRadians()));
          setFire(power);
          // lastEnemyHeading = e.getHeadingRadians();
          lastEnemyHeading = target_enemy.get_en_headingRadians();
          System.out.println("lastEnemyHeading " + e.getHeadingRadians());
          System.out.println(lastEnemyHeading);

          // 敵の居る方向へターンする
          // setTurnRightRadians(e.getBearingRadians());
          setTurnRightRadians(enemyBearing - this.getHeadingRadians());
          System.out.println("setTurnRightRadians " + e.getBearingRadians());
          System.out.println(enemyBearing - this.getHeadingRadians());

          // 前進する
          setAhead(moveAmount);
        } catch (NullPointerException ee) {
          System.out.println("NullPointerException");
          System.out.println(target_enemy);
        }
      }
    }

    System.out.println("enemy_detected = " + enemy_detected);
    System.out.println("target is " + target_enemy.get_en_name());
    System.out.println(target_enemy.get_en_expX() + " " + target_enemy.get_en_expY());
    System.out.println("END at : " + getTime() + " onScannedRobot----------------------------");
  }
Esempio n. 26
-1
  public void aceInTheHole(ScannedRobotEvent e) {
    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();

    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()));

    setTurnRadarRightRadians(Utils.normalRelativeAngle(absoluteBearing - getRadarHeadingRadians()));
    setTurnGunRightRadians(Utils.normalRelativeAngle(theta - getGunHeadingRadians()));
    fire(bulletPower);
  }
Esempio n. 27
-1
  private void doShooting() {
    PositionFinder p = new PositionFinder(enemies, this);
    en = p.findNearest();
    if (en == null) return;

    Point2D myPos = new Point2D.Double(getX(), getY());

    if (HoT) {
      /* Perform head on target for gun movement */
      aimingPoint = new Point2D.Double(en.getX(), en.getY());
      double turnGunAmt = (getHeadingRadians() + en.getBearingRadians() - getGunHeadingRadians());
      turnGunAmt = Utils.normalRelativeAngle(turnGunAmt);
      setTurnGunRightRadians(turnGunAmt);
    } else {
      /* Perform circular targeting */
      Rectangle2D battlefield =
          new Rectangle2D.Double(0, 0, getBattleFieldWidth(), getBattleFieldHeight());
      long when = calcTimeToReachEnemy();
      aimingPoint = org.pattern.utils.Utils.getFuturePoint(en, when);
      if (!battlefield.contains(aimingPoint)) {
        HoT = true;
        return;
      }
      double theta =
          Utils.normalAbsoluteAngle(
              Math.atan2(aimingPoint.getX() - getX(), aimingPoint.getY() - getY()));
      setTurnGunRightRadians(Utils.normalRelativeAngle(theta - getGunHeadingRadians()));
    }

    if (getGunHeat() == 0) {
      double firePower = 3.0;
      fire(firePower);
    }
  }