Better way to generate enemies of different sub-classes

Posted by KDiTraglia on Game Development See other posts from Game Development or by KDiTraglia
Published on 2012-09-19T22:12:57Z Indexed on 2012/09/20 3:52 UTC
Read the original article Hit count: 325

Filed under:
|
|

So lets pretend I have an enemy class that has some generic implementation and inheriting from it I have all the specific enemies of my game. There are points in my code that I need to check whether an enemy is a specific type, but in Java I have found no easier way than this monstrosity...

//Must be a better way to do this
if ( enemy.class.isAssignableFrom(Ninja.class) ) { ... }

My partner on the project saw these and changed them to use an enum system instead

public class Ninja extends Enemy {
    //EnemyType is an enum containing all our enemy types
    public EnemyType = EnemyTypes.NINJA;
}

if (enemy.EnemyType = EnemyTypes.NINJA) { ... }

I also have found no way to generate enemies on varying probabilities besides this

for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        enemy = createEnemy(types.getEnemyType());
        break;
    }
}

private static Enemy createEnemy(EnemyType type) {
    switch (type) {
        case NINJA:
            return new Ninja(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case GORILLA:
            return new Gorilla(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case TREX:
            return new TRex(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
     //etc
    }
return null
}

I know java is a little weak at dynamic object creation, but is there a better way to implement this in a way such like this

for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        //Change enemyTypes to hold the classes of the enemies I can spawn
        enemy = types.getEnemyType().class.newInstance()
        break;
    }
}

Is the above possible? How would I declare enemyTypes to hold the classes if so? Everything I have tried so far as generated compile errors and general frustration, but I figured I might ask here before I completely give up to the huge mass that is the createEveryEnemy() method. All the enemies do inherit from the Enemy class (which is what the enemy variable is declared as). Also is there a better way to check which type a particular enemy that is shorter than enemy.class.isAssignableFrom(Ninja.class)?

I'd like to ditch the enums entirely if possible, since they seem repetitive when the class name itself holds that information.

© Game Development or respective owner

Related posts about java

Related posts about android