Reputation: 6870
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.
Upvotes: 0
Views: 609
Reputation: 10170
Use interfaces to define types.
Create a new type (Measurable) defining Things that are sortable w.r.t a tower (or one if its supertypes such as Building) 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);
}
Upvotes: 1
Reputation: 1355
interface extends another interface but not implements it, because interface won't contain the implementation. So you can just extend comparable.
Upvotes: 2
Reputation: 46209
An interface can't implement another interface, but it can extend any amount of other interfaces.
Just do
interface Combatable extends Comparable<Combatable> {
Upvotes: 3