简体   繁体   中英

Interface implementing comparable?

We are a couple of friends designing a game for fun. In our game we have all enemies implement a Combatable interface letting implementors decide how they would like to do combat, this has made the addition of different kinds of enemies very easy. We have (we are at the testing stage) a turret that shoots at the closest enemy every second if that enemy is within range.

We would like to somehow let this interface implement Comparable<Combatable> so that we can sort our collection by distance from tower so we only need to check if the first element in the collection is within attackrange. We realized a simple solution would be to create a wrapper class for the combatable that does nothing else besides implement Comparable but do we really have to do this? I realize it makes little sense to think of an interface implementing another interface but sense aside it is very convenient for this specific use.

An interface can't implement another interface, but it can extend any amount of other interfaces.

Just do

interface Combatable extends Comparable<Combatable> {

interface extends another interface but not implements it, because interface won't contain the implementation. So you can just extend comparable.

  • Use interfaces to define types.

  • Create a new type (Measurable) defining Things that are sortable wrt a tower (or one if its supertypes such as Building ) position.

  • Then let your Enemy class implemet the Combatable and Measurable interfaces. Now your enemies are sortable wrt towers.
  • Write your new comparator which sorts Enemies wrt a tower position.

.

interface Measurable { 

   // Compute the distance from a turret.
   // It would be better if you use a superclass of Turret to make your method more general
   double distance(Turret p);

};

class Enemy extends Measurable, Combatable {
};

class Turret {

  ...

  Position pos() { return pos; }

  boolean isInRange(Combatable c) { ... }

  void hit(Combatable combatable) { ... }

};



DistFromTurretComparator implements Comparable<Enemy> { 

  DistFromTurretComparator(Turret turret) { 
      this.turret = turret;
  }


  private int compareTo(Enemy other) {
      int dist = distance(turret);
      int oDist = other.distance(turret);

      return  dist > oDist ? + 1 : (dist < oDist ? -1 : 0);
  }

  private final Turret turret;

};

// Main
Tower tower = new Toweer(); 
List<Combatable> enemies = new ArrayList<>(Arrays.asList(enemy1, enemy2, ...));

Collections.sort(enemies, new DistFromTurretComparator(tower));
Enemy nearestEnemy = enemies.get(0);


if (tower.hasInRange(enemy)) {
    tower.hit(enemy);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM