0

First of all, I don't know if that's the correct name for the question. I just couldn't find a better one that is not too long. I am writing an RPG game in Java and I just started to code a random level generator. My idea is to create some enumerated types (let's call them DungeonStyle) which contain all the information required for the generator to create the level. This information includes, as an example, the density of rooms and corridors. Another information I want to store in this enumerated type is which creatures can be spawned by a Spawner Tile inside such a level. I also have to say that the way I implemented creatures was by making a class for each specific creature which inherits from the Creature class. Now I will explain the problem (which is applicable for any kind non-static objects, not only creatures).

The only way I could find to do this separation of possible creatures by DungeonStyle is inside the SpawnerTile code. I would pass a DungeonStyle as an argument to the SpawnerTile's constructor and would make distinctions inside the spawn() method. Something like this:

if (style == Style_A) {
  level.add(new Creature_A());
}

if (style == Style_B) {
  level.add(new Creature_B());
}

That would work fine, but obviously not as I wanted. The creature information is not inside the DungeonStyle. It's being created outside of it. I just can't find a way to store possible classes (of Creatures) inside the DungeonStyle to make instances of them. I think my question is somewhat related to the "<>" when we create an ArrayList< some_object>.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Thiago
  • 471
  • 1
  • 7
  • 20
  • You could use the `newInstance` method of `Class` pbjects but be warned: http://stackoverflow.com/questions/195321/why-is-class-newinstance-evil – Sinkingpoint Dec 05 '13 at 03:18

1 Answers1

0

You can use an enum of possible monsters, doing something like

abstract class MonsterAbstract {//Class that all Monsters extend
    ....
}
enum Monster {
    FOO, BAR;
    public MonsterAbstract spawn() {
        switch(this) {
            case FOO: return new Foo();
            case BAR: return new Bar();
            default: return null; //should never get here
        }
    }
}
void SpawnerTileSpawn(Set<Monster> allowedMonsters) {//allowedMonsters stored within DungeonStyle
    for (Monster m : allowedMonsters) {
        m.spawn();
    }
}
Vitruvie
  • 2,327
  • 18
  • 25