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);
 }
Exemple #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);
  }
Exemple #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);
 }
  private static double getAcceleration(
      LXXRobotState robot, double turnRateRadians, double robotHeading) {
    final double speed = min(robot.getVelocityModule(), Rules.MAX_VELOCITY);
    final double acceleratedSpeed = min(speed + 1, Rules.MAX_VELOCITY);
    final double deceleratedSpeed1 = max(speed - 1, 0);
    final double newHeading = Utils.normalAbsoluteAngle(robotHeading + turnRateRadians);
    final int acceleration;
    if (robot
        .getBattleField()
        .contains(robot.project(newHeading, LXXUtils.getStopDistance(acceleratedSpeed) + 12))) {
      acceleration = 1;
    } else if (robot
        .getBattleField()
        .contains(robot.project(newHeading, LXXUtils.getStopDistance(speed) + 12))) {
      acceleration = 0;
    } else if (robot
        .getBattleField()
        .contains(robot.project(newHeading, LXXUtils.getStopDistance(deceleratedSpeed1) + 12))) {
      acceleration = -1;
    } else {
      acceleration = -2;
    }

    if (robot.getVelocityModule() + acceleration > Rules.MAX_VELOCITY) {
      return Rules.MAX_VELOCITY - robot.getVelocityModule();
    }
    if (robot.getVelocityModule() + acceleration < 0) {
      return -robot.getVelocityModule();
    }

    return acceleration;
  }
 /**
  * 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();
   }
 }
    public void onHitWall(HitWallEvent event) {
      double angle = peer.getBodyHeading() + event.getBearingRadians();

      hitWallAngle = (int) (Math.toDegrees(Utils.normalAbsoluteAngle(angle)) + 0.5);
      hitWallBearing = (int) (event.getBearing() + 0.5);
      JuniorRobot.this.onHitWall();
    }
  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, но я противник функций с сайд
    // эффектами и стараюсь
    // минимизировать их количество
  }
 /** 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);
 }
Exemple #9
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);
  }
Exemple #10
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();
  }
Exemple #11
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);
 }
Exemple #12
0
  private final Bullet setFireImpl(double power) {
    if (Double.isNaN(power)) {
      println("SYSTEM: You cannot call fire(NaN)");
      return null;
    }
    if (getGunHeatImpl() > 0 || getEnergyImpl() == 0) {
      return null;
    }

    power = min(getEnergyImpl(), min(max(power, Rules.MIN_BULLET_POWER), Rules.MAX_BULLET_POWER));

    Bullet bullet;
    BulletCommand wrapper;
    Event currentTopEvent = eventManager.getCurrentTopEvent();

    nextBulletId++;

    if (currentTopEvent != null
        && currentTopEvent.getTime() == status.getTime()
        && !statics.isAdvancedRobot()
        && status.getGunHeadingRadians() == status.getRadarHeadingRadians()
        && ScannedRobotEvent.class.isAssignableFrom(currentTopEvent.getClass())) {
      // this is angle assisted bullet
      ScannedRobotEvent e = (ScannedRobotEvent) currentTopEvent;
      double fireAssistAngle =
          Utils.normalAbsoluteAngle(status.getHeadingRadians() + e.getBearingRadians());

      bullet =
          new Bullet(
              fireAssistAngle, getX(), getY(), power, statics.getName(), null, true, nextBulletId);
      wrapper = new BulletCommand(power, true, fireAssistAngle, nextBulletId);
    } else {
      // this is normal bullet
      bullet =
          new Bullet(
              status.getGunHeadingRadians(),
              getX(),
              getY(),
              power,
              statics.getName(),
              null,
              true,
              nextBulletId);
      wrapper = new BulletCommand(power, false, 0, nextBulletId);
    }

    firedEnergy += power;
    firedHeat += Rules.getGunHeat(power);

    commands.getBullets().add(wrapper);

    bullets.put(nextBulletId, bullet);

    return bullet;
  }
  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);
  }
  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);
    }
  }
    public void onScannedRobot(ScannedRobotEvent event) {
      scannedDistance = (int) (event.getDistance() + 0.5);
      scannedEnergy = Math.max(1, (int) (event.getEnergy() + 0.5));
      scannedAngle =
          (int)
              (Math.toDegrees(
                      Utils.normalAbsoluteAngle(peer.getBodyHeading() + event.getBearingRadians()))
                  + 0.5);
      scannedBearing = (int) (event.getBearing() + 0.5);
      scannedHeading = (int) (event.getHeading() + 0.5);
      scannedVelocity = (int) (event.getVelocity() + 0.5);

      JuniorRobot.this.onScannedRobot();
    }
Exemple #16
0
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Wave wave = (Wave) o;

    if (launchTime != wave.launchTime) return false;
    if (!Utils.isNear(wave.speed, speed)) return false;
    if (sourceState != null ? !sourceState.equals(wave.sourceState) : wave.sourceState != null)
      return false;
    if (targetState != null ? !targetState.equals(wave.targetState) : wave.targetState != null)
      return false;

    return true;
  }
  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);
  }
Exemple #18
0
  public double getAbsoluteAimAngle(
      Wave aimWave, BotScan scan, BotScan enemyScan, double bulletPower) {

    if (_lastFireTime == aimWave.fireTime) {
      return _lastAimAngle;
    }

    _lastAimAngle =
        Utils.normalAbsoluteAngle(
            aimWave.absBearingRadians
                + aimWave.guessAngleFromIndex(getAimBin(aimWave, scan, enemyScan, bulletPower)));

    _lastFireTime = aimWave.fireTime;

    return _lastAimAngle;
  }
  @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);
   }
 }
Exemple #21
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);
    }
  }
  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);
  }
Exemple #23
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;
    }
Exemple #24
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;
    }
  @Override
  public void onScannedRobot(ScannedRobotEvent event) {

    info = new EnemyInfo(en, getTime());
    Enemy enemy = enemies.get(event.getName());

    if (enemy == null) {
      enemy = new Enemy(event, this);
      enemies.put(enemy.getName(), enemy);
      storages.put(enemy.getName(), new VisitCountStorage());
    }

    if (getTime() - enemy.getLastUpdated() < Costants.TIME_THRESHOLD
        && (enemy.getEnergy() - event.getEnergy()) > 0.
        && (enemy.getEnergy() - event.getEnergy()) < 3.1) {

      GBulletFiredEvent gBulletFiredEvent = new GBulletFiredEvent();
      gBulletFiredEvent.setFiringRobot(enemy);
      gBulletFiredEvent.setEnergy(enemy.getEnergy() - event.getEnergy());
      gBulletFiredEvent.setVelocity(20 - 3 * (enemy.getEnergy() - event.getEnergy()));
      gBulletFiredEvent.setFiringTime(getTime() - 1);
      gBulletFiredEvent.setFiringPosition(enemy.getPosition()); // TODO this or the updated one?
      gBulletFiredEvent.setTargetPosition(new Point2D.Double(getX(), getY()));
      org.pattern.utils.Utils.setWaveMAE(gBulletFiredEvent, getHeading(), getVelocity(), this);
      waves.addWave(gBulletFiredEvent);
    }

    enemy.updateEnemy(event, this);
    enemies.put(enemy.getName(), enemy);

    if (!meleeRadar) {
      Double radarTurn = getHeading() - getRadarHeading() + enemy.getBearing();
      setTurnRadarRight(Utils.normalRelativeAngleDegrees(radarTurn));
    }

    doShooting();
  }
Exemple #27
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);
  }
Exemple #28
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;
  }
  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);
    }
  }
Exemple #30
-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);
  }