Game Development Reference
In-Depth Information
As you can see, we first create a
GameObjectGrid
instance, we set the width and
height of a cell within that grid to a given size, and then we start reading the lines
containing the tile information. Now, depending on the character we get from the
expression
currRow[col]
, we need to create different kinds of game objects, and add
them to the grid. We could use an
if
-instruction for that:
if
(currRow[col] == '.')
// create an empty tile
else if
(currRow[col] == ' ')
// create a background tile
else if
(currRow[col] == 'r')
// create a penguin tile
//... and so on
But there is another option that allows us to write this down in a slightly cleaner
way. With the
if
-instruction, we have to write and re-write a similar condition. C#
offers a special kind of instruction for that:
switch
.
22.6.3 The
switch
-Instruction: Handling Alternatives
The
switch
-instruction allows us to specify alternatives, and the instructions that
should be executed for each alternative. For example, the above
if
-instruction with
multiple alternatives can be rewritten as a
switch
-instruction as follows:
switch
(currRow[col])
{
case
'.':
// create an empty tile
break
;
case
'':
// create a background tile
break
;
case
'r':
// create a penguin tile
break
;
}
The
switch
-instruction has a few handy properties that make it very useful to handle
different alternatives. Have a look at the following code example:
if
(x==1) one();
else if
(x==2) { two(); alsoTwo(); }
else if
(x==3 || x==4) threeOrFour();
else
more();
We can rewrite this with a
switch
-instruction as follows: