oop - Interfaces to allow unit's ability to attack ground, air, or both in Java using Design Patterns -


im making text game has abstract fighter class. within fighter have variable called protected boolean isground. have 2 abstract classes extend fighter called airfighter , groundfighter set isground true or false, depending on if ground units or not.

i want set game in battle phase game checks if player 1's speed faster player 2, , depending on faster p1.attack(p2), , print out stats of battle, remaining health of each player or that.

i want way airfighters attack air, or attack air , ground, , want groundfighters attack ground only, or ground , air. how go doing while staying loosely coupled? design pattern's class , frustrating me. there design pattern me this?

think of game starcraft, that's game mimicing, units marine can attack ground , air, air units can attack air, can both. want able without having nasty if else checking statement.

an easy way have method in base fighter can used check if fighter can attack another:

public abstract class fighter {     public abstract boolean isground ();     public abstract boolean canattack (fighter target); } 

subclasses can override canattack , make appropriate decision. example:

public class surfacetoairlauncher extends fighter {     @override public boolean isground () {         // missile launcher on ground         return true;      }     @override public boolean canattack (fighter target) {         // can attack air targets         return (target != null && !target.isground());     } }  public class dragon extends fighter {     @override public boolean isground () {         // dragons in air         return false;      }     @override public boolean canattack (fighter target) {         // dragons can attack every target.         return (target != null);     } }  public class knight extends fighter {     @override public boolean isground () {         // knights on ground         return true;      }     @override public boolean canattack (fighter target) {         // knights can attack dragons         return (target != null && target instanceof dragon);     } } 

you remove check null if know target never null. included completeness.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -