Exemple #1
0
  /**
   * Helper method to move the animal from the edge of the arena, based on its current x and y
   * coordinates
   *
   * @param x - coordinate of the animal's current location
   * @param y - coordinate of the animal's current location
   */
  private Command moveFromEdge(
      int x, int y, ArenaWorld world, ArenaAnimal animal, Location currentLocation) {
    Location eastOf = new Location(currentLocation, Direction.EAST);
    Location southOf = new Location(currentLocation, Direction.SOUTH);
    Location westOf = new Location(currentLocation, Direction.WEST);
    Location northOf = new Location(currentLocation, Direction.NORTH);

    Location randomLoc;

    // if fox is at top left quadrant, move east
    if (y <= world.getHeight() / 2
        && x <= world.getWidth() / 2
        && isLocationEmpty(world, animal, eastOf)) {
      return new MoveCommand(animal, eastOf);
    }
    // if fox is at top right quadrant, move south
    else if (y <= world.getHeight() / 2
        && x >= world.getWidth() / 2
        && isLocationEmpty(world, animal, southOf)) {
      return new MoveCommand(animal, southOf);
    }
    // if fox is at bottom right quadrant, move west
    else if (y >= world.getHeight() / 2
        && x >= world.getWidth() / 2
        && isLocationEmpty(world, animal, westOf)) {
      return new MoveCommand(animal, westOf);
    }
    // if fox is at bottom of arena, move north
    else if (y >= world.getHeight() / 2
        && x <= world.getWidth() / 2
        && isLocationEmpty(world, animal, northOf)) {
      return new MoveCommand(animal, northOf);
    }
    // move in random direction
    else {
      int count = 0;
      do {
        randomLoc = Util.getRandomEmptyAdjacentLocation((World) world, currentLocation);
        if (randomLoc == null) {
          return new WaitCommand();
        }
        count++;
      } while (randomLoc.getDistance(currentLocation) > 1 && count < 4);

      if (Util.isValidLocation(world, randomLoc)
          && Util.isLocationEmpty((World) world, randomLoc)
          && count < 4) {
        return new MoveCommand(animal, randomLoc);
      } else {
        return new WaitCommand();
      }
    }
  }