Esempio n. 1
0
 public void logScore(double score, double weight) {
   _rating =
       (double)
           ((_rating * Math.min(_shots, _rollingDepth) + (score * weight))
               / (Math.min(_shots, _rollingDepth) + weight));
   _shots += weight;
 }
Esempio n. 2
0
 public void enemyPosition(ScannedRobotEvent e, double x, double y) {
   // poll subtargetters for their opinions
   virtualBulletTick++;
   lastEnemyScanTime = owner.getTime();
   // only log it when we actually fire: the enemy may respond to that
   if (owner.shouldFireShot(e)) {
     double bulletPower = e.getDistance() > 500.0 ? 2.0 : 3.0;
     for (int i = 0; i < numVirtualGuns; i++) {
       double angle = targetters[i].target(e, bulletPower);
       VirtualBullet bullet = new VirtualBullet();
       bullet.targetter = i;
       bullet.x = owner.getX();
       bullet.y = owner.getY();
       bullet.velX = Targetting.bulletSpeed(bulletPower) * Math.sin(angle);
       bullet.velY = Targetting.bulletSpeed(bulletPower) * Math.cos(angle);
       bullet.lastUpdateTime = lastEnemyScanTime;
       virtualBullets.add(bullet);
     }
   }
   for (int i = 0; i < numVirtualGuns; i++) {
     targetters[i].enemyPosition(e, x, y);
   }
   enemyX = x;
   enemyY = y;
 }
Esempio n. 3
0
 private static Point2D vectorToLocation(
     double angle, double length, Point2D sourceLocation, Point2D targetLocation) {
   targetLocation.setLocation(
       sourceLocation.getX() + Math.sin(angle) * length,
       sourceLocation.getY() + Math.cos(angle) * length);
   return targetLocation;
 }
Esempio n. 4
0
  public void evaluateDistancingControl() {
    double powerTwoHitPercentageThreshold;

    if (_robot.getRoundNum() < 2) {
      _desiredDistance = 420;
      _fearDistance = 175;
      _smoothAwayDistance = 75;
    } else if (normalizedEnemyHitPercentage() > (powerTwoHitPercentageThreshold = 7.5)) {
      _desiredDistance = 525 + (Math.max((ScanLog.avgEnemyPower() - 2), 0) * 165);
      _fearDistance = 250;
      _smoothAwayDistance = 75;
    } else if (normalizedEnemyHitPercentage() > (powerTwoHitPercentageThreshold = 3)) {
      _desiredDistance = 450 + (Math.max((ScanLog.avgEnemyPower() - 2), 0) * 150);
      _fearDistance = 175;
      _smoothAwayDistance = 75;
    } else {
      _desiredDistance = 420;
      _fearDistance = 0;
      _smoothAwayDistance = 0;
    }

    if (_robot.getRoundNum() < 2 || normalizedEnemyHitPercentage() > 7.5) {
      _currentDistancer = _aggressiveDistancer;
    } else {
      _currentDistancer = _subtleDistancer;
    }
  }
Esempio n. 5
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. 6
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. 7
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);
  }
  /** Calculate how repusled the scanning robot is by a nearby object. */
  public double calcObjRepulseSpeed(double robotX, double robotY, double obsX, double obsY) {
    double speed = 0.0;
    double distance = Math.sqrt(Math.pow(robotX - obsX, 2) + Math.pow(robotY - obsY, 2));

    if (distance <= OBJ_DISTANCE) {
      speed = ((OBJ_DISTANCE - distance) / OBJ_DISTANCE) * MAX_SPEED;
    }

    return speed;
  }
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);
 }
  /** Linearly decay the speed of the robot when it nears the goal. */
  public double calcRobotSpeedLinear(double robotX, double robotY, double goalX, double goalY) {
    double speed = 0;

    double distance = Math.sqrt(Math.pow(robotX - goalX, 2) + Math.pow(robotY - goalY, 2));
    if (distance >= GOAL_DISTANCE) {
      speed = MAX_SPEED;
    } else {
      speed = (distance / GOAL_DISTANCE) * MAX_SPEED + 0.5;
    }

    return speed;
  }
  /**
   * When scanning a robot we need to add it to the collection of scanned objects so it can be used
   * later for updates to the bots movement.
   */
  public void onScannedRobot(ScannedRobotEvent e) {
    double targetBearing = getHeading() + e.getBearing();
    double tmpX = getX() + e.getDistance() * Math.sin(Math.toRadians(targetBearing));
    double tmpY = getY() + e.getDistance() * Math.cos(Math.toRadians(targetBearing));
    String name = e.getName();

    if (name.equals(GOAL_NAME)) {
      foundGoal = true;
    }

    obstacles.put(name, new Enemy(tmpX, tmpY, e.getBearing()));

    setTurnRadarRight(getRadarTurnRemaining());
  }
Esempio n. 12
0
 public void onHitByBullet(HitByBulletEvent e) {
   if (fitness - getEnergy() > 15) {
     select++;
     if (select == 4) {
       elapsedTime[select - 1] = (int) e.getTime() - time;
       time = (int) e.getTime();
       sortIndividuals();
       for (int i = 1; i < 4; i++)
         if (Math.random() < 0.7) population[i] = crossover(population[0], population[i]);
       for (int i = 0; i < 4; i++)
         if (Math.random() < 0.1) population[i] = mutation(population[i]);
       select = 0;
     }
     fitness = (int) getEnergy();
   }
 }
Esempio n. 13
0
 public int mutation(int individual) {
   int ind2;
   do {
     ind2 = individual + (int) (-1 + 2 * Math.random());
   } while (ind2 < 1 || ind2 >= 6);
   return ind2;
 }
Esempio n. 14
0
  public void run() {
    population = new int[4];
    elapsedTime = new int[4];

    for (int i = 0; i < 4; i++) population[i] = (int) (Math.random() * 4 + 1);

    fitness = (int) getEnergy();

    while (true) {
      time = (int) getTime();
      switch (population[select]) {
        case 1:
          individual = behaviors.FORWARD_AND_REDO;
          break;
        case 2:
          individual = behaviors.CIRCULAR;
          break;
        case 3:
          individual = behaviors.DODGE;
          break;
        case 4:
          individual = behaviors.WALLS;
          break;
        case 5:
          individual = behaviors.CRAZY;
          break;
        default:
          System.out.println("Error!");
          break;
      }

      switch (individual) {
        case CRAZY:
          setTurnGunRight(99999);
          execute();
          crazyMoves();
          break;
        case FORWARD_AND_REDO:
          setTurnGunRight(99999);
          execute();
          forwardAndRedoMoves();
          break;
        case CIRCULAR:
          setTurnGunRight(99999);
          execute();
          circularMoves();
          break;
        case WALLS:
          setTurnGunRight(99999);
          execute();
          betaWallsMoves();
          break;
        case DODGE:
          dodgeMoves();
          break;
      }
    }
  }
Esempio n. 15
0
  public void onScannedRobot(ScannedRobotEvent e) {

    // track if we have no enemy, the one we found is significantly
    // closer, or we scanned the one we've been tracking.
    if (enemy.none()
        || e.getDistance() < enemy.getDistance() - 70
        || e.getName().equals(enemy.getName())) {

      // track him
      enemy.update(e);

      // if the gun is cool and we're pointed at the target, shoot!
      // Note: we can put the firing code before the turning code
      // because we're testing to see if we're aiming at our enemy
      if (getGunHeat() == 0 && Math.abs(getGunTurnRemaining()) < 10)
        setFire(Math.min(400 / enemy.getDistance(), 3));

      //  calculate gun turn toward enemy
      double turn = getHeading() - getGunHeading() + e.getBearing();
      // normalize the turn to take the shortest path there
      setTurnGunRight(normalizeBearing(turn));
    }
  }
 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. 17
0
 private double minWall() {
   return Math.min(
       Math.min(getX(), getBattleFieldWidth() - getX()),
       Math.min(getY(), getBattleFieldHeight() - getY()));
 }
Esempio n. 18
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. 19
0
 static double absoluteBearing(Point2D source, Point2D target) {
   return Math.atan2(target.getX() - source.getX(), target.getY() - source.getY());
 }
 public static int getBearingSegment(double bearing) {
   int index = (int) (bearing / (2 * Math.PI) * (BEARINGS));
   return Math.max(0, Math.min(BEARINGS - 1, index));
 }
 public static int getTimeSegment(long time) {
   int index = (int) Math.min(time / 10.0, MOVE_TIMES - 1);
   return index;
 }
 public static int getVelocitySegment(double velocity) {
   return (int) Math.max(0, velocity - 1);
 }
 /** Projects the robots location given distance and bearing */
 public static Point2D.Double project(Point2D.Double source, double angle, double length) {
   double x = source.x + Math.sin(angle) * length;
   double y = source.y + Math.cos(angle) * length;
   return new Point2D.Double(x, y);
 }
  public void run() {
    setAllColors(Color.GREEN);
    setTurnRadarRight(Double.POSITIVE_INFINITY);

    double robotX, robotY;
    double robotHeading, angleToGoal, angleToObs;
    double adjustment;
    double obsAngle, obsAdjustment;
    double angleDiff;
    double speedToGoal, speedFromObs;

    Enemy temp;
    obstacles = new HashMap<String, Enemy>(10);

    while (true) {
      if (foundGoal) {
        robotX = getX();
        robotY = getY();
        goalX = obstacles.get(GOAL_NAME).x;
        goalY = obstacles.get(GOAL_NAME).y;

        // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of
        // the positive y-axis.
        // Also make it so that positive angle indicates a counter clockwise rotation instead of the
        // clockwise style
        // returned by robocode.
        robotHeading = 360 - (getHeading() - 90);
        angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX));
        if (angleToGoal < 0) {
          angleToGoal += 360;
        }

        adjustment = angleToGoal - robotHeading;
        adjustment = normalizeAngle(adjustment);
        speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY);

        // Calculate how the robot's heading and speed should be affected by objects that it has
        // located
        // as it explores the world.
        Iterator it = obstacles.entrySet().iterator();
        while (it.hasNext()) {
          System.out.println("Iterating through objects.");

          Map.Entry pairs = (Map.Entry) it.next();

          // If the current item in the Iterator isn't the goal.
          if (!pairs.getKey().equals(GOAL_NAME)) {
            temp = (Enemy) pairs.getValue();
            speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y);

            // If the robot is in range of the object to be affected by it's repulsion.
            if (speedFromObs != 0) {
              obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x));
              if (obsAngle < 0) obsAngle += 360;

              angleDiff = obsAngle - angleToGoal;
              angleDiff = normalizeAngle(angleDiff);
              adjustment += (angleDiff * (speedFromObs / speedToGoal));
              speedToGoal -= speedFromObs;
            }
          }

          // Was getting a null pointer exception when using this. The internet lied about its
          // usefulness.
          // it.remove(); // avoids a ConcurrentModificationException
        }

        adjustment = normalizeAngle(adjustment);
        setTurnLeft(adjustment);
        // ahead(speedToGoal);
        setAhead(speedToGoal);
      }

      execute();
    }
  }
 /** Computes the angle to target from source */
 public static double absoluteBearing(Point2D.Double source, Point2D.Double target) {
   return Math.atan2(target.x - source.x, target.y - source.y);
 }
 /**
  * Decay the speed "globally." The goal doens't have a range at which it starts to cause a speed
  * drop off. Instead, the entire screen has a scaled gradient.
  */
 public int calcRobotSpeedGlobalFields(double robotX, double robotY, double goalX, double goalY) {
   double distance = Math.sqrt(Math.pow(robotX - goalX, 2) + Math.pow(robotY - goalY, 2));
   return (int) ((distance / MAX_DISTANCE) * MAX_SPEED + 0.5);
 }
 /** Computes the maximum angle to escape */
 public static double maxEscapeAngle(double velocity) {
   return Math.asin(8.0 / velocity);
 }
/**
 * Robocode robot that locates and navigates toward a goal while also avoiding obstacles that it
 * gets near.
 */
public class VectorFieldsMultMovObsAvoid extends AdvancedRobot {
  private static final int SCREEN_WIDTH = 600;
  private static final int SCREEN_HEIGHT = 600;
  private static final double MAX_DISTANCE =
      Math.sqrt(Math.pow(SCREEN_WIDTH, 2) + Math.pow(SCREEN_HEIGHT, 2));
  private static final int MAX_SPEED = 5;
  private static final int GOAL_DISTANCE = 50;
  private static final int OBJ_DISTANCE = 200;
  private static final String GOAL_NAME = "VectorFields.VectorFieldsMovingGoal*";

  private double goalX, goalY;
  private double obsX, obsY;
  private boolean foundGoal = false;
  private boolean foundObstacle = false;

  private Map<String, Enemy> obstacles;

  public void run() {
    setAllColors(Color.GREEN);
    setTurnRadarRight(Double.POSITIVE_INFINITY);

    double robotX, robotY;
    double robotHeading, angleToGoal, angleToObs;
    double adjustment;
    double obsAngle, obsAdjustment;
    double angleDiff;
    double speedToGoal, speedFromObs;

    Enemy temp;
    obstacles = new HashMap<String, Enemy>(10);

    while (true) {
      if (foundGoal) {
        robotX = getX();
        robotY = getY();
        goalX = obstacles.get(GOAL_NAME).x;
        goalY = obstacles.get(GOAL_NAME).y;

        // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of
        // the positive y-axis.
        // Also make it so that positive angle indicates a counter clockwise rotation instead of the
        // clockwise style
        // returned by robocode.
        robotHeading = 360 - (getHeading() - 90);
        angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX));
        if (angleToGoal < 0) {
          angleToGoal += 360;
        }

        adjustment = angleToGoal - robotHeading;
        adjustment = normalizeAngle(adjustment);
        speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY);

        // Calculate how the robot's heading and speed should be affected by objects that it has
        // located
        // as it explores the world.
        Iterator it = obstacles.entrySet().iterator();
        while (it.hasNext()) {
          System.out.println("Iterating through objects.");

          Map.Entry pairs = (Map.Entry) it.next();

          // If the current item in the Iterator isn't the goal.
          if (!pairs.getKey().equals(GOAL_NAME)) {
            temp = (Enemy) pairs.getValue();
            speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y);

            // If the robot is in range of the object to be affected by it's repulsion.
            if (speedFromObs != 0) {
              obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x));
              if (obsAngle < 0) obsAngle += 360;

              angleDiff = obsAngle - angleToGoal;
              angleDiff = normalizeAngle(angleDiff);
              adjustment += (angleDiff * (speedFromObs / speedToGoal));
              speedToGoal -= speedFromObs;
            }
          }

          // Was getting a null pointer exception when using this. The internet lied about its
          // usefulness.
          // it.remove(); // avoids a ConcurrentModificationException
        }

        adjustment = normalizeAngle(adjustment);
        setTurnLeft(adjustment);
        // ahead(speedToGoal);
        setAhead(speedToGoal);
      }

      execute();
    }
  }

  /**
   * When scanning a robot we need to add it to the collection of scanned objects so it can be used
   * later for updates to the bots movement.
   */
  public void onScannedRobot(ScannedRobotEvent e) {
    double targetBearing = getHeading() + e.getBearing();
    double tmpX = getX() + e.getDistance() * Math.sin(Math.toRadians(targetBearing));
    double tmpY = getY() + e.getDistance() * Math.cos(Math.toRadians(targetBearing));
    String name = e.getName();

    if (name.equals(GOAL_NAME)) {
      foundGoal = true;
    }

    obstacles.put(name, new Enemy(tmpX, tmpY, e.getBearing()));

    setTurnRadarRight(getRadarTurnRemaining());
  }

  /** Linearly decay the speed of the robot when it nears the goal. */
  public double calcRobotSpeedLinear(double robotX, double robotY, double goalX, double goalY) {
    double speed = 0;

    double distance = Math.sqrt(Math.pow(robotX - goalX, 2) + Math.pow(robotY - goalY, 2));
    if (distance >= GOAL_DISTANCE) {
      speed = MAX_SPEED;
    } else {
      speed = (distance / GOAL_DISTANCE) * MAX_SPEED + 0.5;
    }

    return speed;
  }

  /**
   * Decay the speed "globally." The goal doens't have a range at which it starts to cause a speed
   * drop off. Instead, the entire screen has a scaled gradient.
   */
  public int calcRobotSpeedGlobalFields(double robotX, double robotY, double goalX, double goalY) {
    double distance = Math.sqrt(Math.pow(robotX - goalX, 2) + Math.pow(robotY - goalY, 2));
    return (int) ((distance / MAX_DISTANCE) * MAX_SPEED + 0.5);
  }

  /**
   * Normalize an angle so it falls in the range -180 to 180 in the least efficient manner possible.
   */
  public double normalizeAngle(double angle) {
    if (angle <= -360) {
      angle += 360;
    } else if (angle >= 360) {
      angle -= 360;
    }

    if (angle < -180) {
      angle += 360;
    } else if (angle > 180) {
      angle -= 360;
    }

    return angle;
  }

  /** Calculate how repusled the scanning robot is by a nearby object. */
  public double calcObjRepulseSpeed(double robotX, double robotY, double obsX, double obsY) {
    double speed = 0.0;
    double distance = Math.sqrt(Math.pow(robotX - obsX, 2) + Math.pow(robotY - obsY, 2));

    if (distance <= OBJ_DISTANCE) {
      speed = ((OBJ_DISTANCE - distance) / OBJ_DISTANCE) * MAX_SPEED;
    }

    return speed;
  }
}
 /** Computes a value within min and max */
 public static double limit(double min, double val, double max) {
   return Math.max(min, Math.min(val, max));
 }
Esempio n. 30
0
  public double getTreeValue(int[] f, int[][] links, int node) {
    double r1, r2, r3, r4;
    double res;

    r1 = 0;
    r2 = 0;
    r3 = 0;
    r4 = 0;

    switch (f[node]) {
      case 7:
        r4 = getTreeValue(f, links, links[node][3]);

      case 3:
      case 5:
        r3 = getTreeValue(f, links, links[node][2]);

      case 2:
      case 4:
      case 6:
        r2 = getTreeValue(f, links, links[node][1]);

      case 0:
      case 1:
        r1 = getTreeValue(f, links, links[node][0]);
        break;

      default:
        r1 = 0;
        r2 = 0;
        r3 = 0;
        r4 = 0;
        break;
    }

    switch (f[node]) {
      case 0:
        res = 1 / (1 + Math.exp(-r1));
        break;

      case 1:
        res = -r1;
        break;

      case 2:
        res = r1 + r2;
        break;

      case 3:
        res = r1 + r2 + r3;
        break;

      case 4:
        res = r1 * r2;
        break;

      case 5:
        res = r1 * r2 * r3;
        break;

      case 6:
        res = (r1 > r2) ? r2 : r1;
        break;

      case 7:
        res = (r1 > r2) ? r3 : r4;
        break;

      case 8:
        res = env.x;
        break;

      case 9:
        res = env.y;
        break;

      case 10:
        res = env.dr;
        break;

      case 11:
        res = env.tr;
        break;

      case 12:
        res = env.w;
        break;

      case 13:
        res = env.dh;
        break;

      case 14:
        res = env.GH;
        break;

      case 15:
        res = env.h;
        break;

      case 16:
        res = env.d;
        break;

      case 17:
        res = env.e;
        break;

      case 18:
        res = env.E;
        break;

      case 19:
        res = 0;
        break;

      case 20:
        res = 0.5;
        break;

      case 21:
        res = 1;
        break;

      case 22:
        res = 2;
        break;

      case 23:
        res = 5;
        break;

      case 24:
        res = 10;
        break;

      default:
        res = 0;
        break;
    }

    return res;
  }