So, is anyone here familiar with dependency injection? I have a technical issue I’m trying to solve in my game of which DI seems to be the only clean way to deal with it. Basically I’m trying to make the attacker/victim logic completely self-contained so that I don’t have to duplicate logic to each and every attackable thing in the game. The problem is there’s three branches I’m current working with class-wise:
IActor -> Player
IActor -> NPC -> OldMan
IEnemy -> Crab
IEnemy -> EvilGirl
Player is going to have ‘attacking’ abilities, but oldman is not. But i also want to share the same logic with IEnemy as well… So the ONLY thing I can think is to create an IAttackableActor interface which defines what I need to do my processing (getters/setters for certain things like health and defense, death, etc), then implement that interface on Player, Crab, and EvilGirl. That allow me to do this:
public class AttackLogic {
public static void Attack(final IAttackableActor attacker, final IAttackableActor victim) {
// Do not process attacks on a victim that is currently being staggered
if (victim.getStaggered()) {
return;
}
// Determine the damage that will be dealt
final int damageToDeal =
Math.min(
// This is a bit anal, but make sure damage is never greater than total health.
victim.getHealth(),
// At least 1 damage must take place
Math.max(1, attacker.getAttackStrength() - victim.getAttackDefense())
);
// Apply damage to the victim
victim.setHealth(victim.getHealth() - damageToDeal);
if (victim.getHealth() > 0) {
victim.setStaggered(true);
return;
}
victim.onKilledBy(attacker);
attacker.onVictimKilled(victim);
}
}
Any thoughts on this, or if someone has a better idea on how to cleanly implement this?