Game Development Reference
In-Depth Information
public final List<Coin> coins;
public Castle castle;
public final WorldListener listener;
public final Random rand;
public float heightSoFar;
public int score;
public int state;
Next up are all the members of the World class. It keeps track of Bob; all the platforms, springs,
squirrels, and coins; and the castle. Additionally, it has a reference to a WorldListener and an
instance of Random , which we'll use to generate random numbers for various purposes. The last
three members keep track of the highest height Bob has reached so far, as well as the World 's
state and the score achieved.
public World(WorldListener listener) {
this .bob = new Bob(5, 1);
this .platforms = new ArrayList<Platform>();
this .springs = new ArrayList<Spring>();
this .squirrels = new ArrayList<Squirrel>();
this .coins = new ArrayList<Coin>();
this .listener = listener;
rand = new Random();
generateLevel();
this .heightSoFar = 0;
this .score = 0;
this .state = WORLD _ STATE _ RUNNING ;
}
The constructor initializes all members and also stores the WorldListener passed as a
parameter. Bob is placed in the middle of the world horizontally and a little bit above the ground
at (5,1). The rest is pretty much self-explanatory, with one exception: the generateLevel()
method.
Generating the World
You might have wondered already how we actually create and place the objects in our world.
We use a method called procedural generation. We came up with a simple algorithm that will
generate a random level for us. Listing 9-16 shows the code.
Listing 9-16. Excerpt from World.java; the generateLevel() Method
private void generateLevel() {
float y = Platform. PLATFORM _ HEIGHT / 2;
float maxJumpHeight = Bob. BOB _ JUMP _ VELOCITY * Bob. BOB _ JUMP _ VELOCITY
/ (2 * - gravity .y);
while (y < WORLD _ HEIGHT - WORLD _ WIDTH / 2) {
int type = rand.nextFloat() > 0.8f ? Platform. PLATFORM _ TYPE _ MOVING
: Platform. PLATFORM _ TYPE _ STATIC ;
float x = rand.nextFloat()
 
Search WWH ::




Custom Search