Game Development Reference
In-Depth Information
You first create a
GameObjectGrid
instance and set the width and height of a cell in that grid to a
given size. Then you start reading the characters containing the tile information.
Now, depending on the character you get from the expression
levelData.tiles[row][col]
, you
need to create different kinds of game objects and add them to the grid. You could use an
if
instruction for that:
if (levelData.tiles[row][col] === '.')
// create an empty tile
else if (levelData.tiles[row][col] === ' ')
// create a background tile
else if (levelData.tiles[row][col] === 'r')
// create a penguin tile
//... and so on
In principle, this code would work. But every time, you have to write a complex condition. It's easy
to make a mistake such as misspelling the variable name or forgetting to include brackets. There is
another option that allows you to write this in a slightly cleaner way. JavaScript offers a special kind
of instruction for handling cases:
switch
.
Note
When defining levels in a text-based format, you have to decide what kind of object each character
represents. These decisions influence the work of both level designers, who have to enter the characters in
the level data files, and developers, who have to write the code to interpret that level data. This shows how
important documentation is, even during active development. A “cheat sheet” is nice to have so that when
you write this code, you don't have to remember all the ideas you had for level design. Such a cheat sheet is
also useful if you work with a designer, to make sure you're both on the same page.
Using
switch
to Handle Alternatives
The
switch
instruction allows you to specify alternatives, and the instructions that should be
executed for each alternative. For example, the previous
if
instruction with multiple alternatives can
be rewritten as a
switch
instruction as follows:
switch(levelData.tiles[row][col]) {
case '.': // create an empty tile
break;
case ' ': // create a background tile
break;
case 'r': // create a penguin tile
break;
}
Search WWH ::
Custom Search