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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class AttackLogic { public static void Attack(final IAttackableActor attacker, final IAttackableActor victim) {
if (victim.getStaggered()) { return; }
final int damageToDeal = Math.min( victim.getHealth(), Math.max(1, attacker.getAttackStrength() - victim.getAttackDefense()) );
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?