Game Development Reference
In-Depth Information
states such as the player dying or completing the level, and other aspects of the
general game loop. All of these things belong to the
Level
class, so splitting them
in different classes just to increase readability does not make sense. On the other
hand: placing all this code in a single source file will lead to a less readable class
definition. For these kinds of cases, C# provides so-called
partial classes
. Partial
classes allow us to spread the definition of a class over different source files. In
this example, we have done that for the
Level
class, which is spread over three dif-
ferent source files:
Level.cs
,
LevelGameLoop.cs
, and
LevelLoading.cs
, where the latter
file contains the code for loading the level from a file. The
Level.cs
file for now
only contains the constructor, but we will add other generic things such as prop-
erties to this file. The
LevelGameLoop
contains the game loop methods of the
Level
class.
If you look inside the
Level.cs
file, you see that the keyword
partial
is written
in front of the class definition. This indicates that we are dealing with a partial
definition of the class, and that other partial definitions might be located in different
source files. If you open the
LevelGameLoop.cs
and
LevelLoading.cs
files, you will
see the same keyword being used there as well. The
partial
keyword does nothing
besides allowing the code to be spread over different source files. The compiler
will combine all these source files into a single
Level
class when it compiles the
files.
25.7 Creating the
Level
Object
In the constructor of the
Level
class, we are going to do a couple of things:
•
create the background sprite game object;
•
add a 'quit' button;
•
load the tiles from a text file.
For loading the tiles from the text file, we are going to use an approach similar
to the one we used in
Penguin Pairs
, except that one text file contains one level.
Retrieving the data from the file is done in the
Level
class by calling the
LoadTiles
method. Depending on the level index, a different file is loaded. In order to read the
tiles from the text file, we create a
StreamReader
:
StreamReader fileReader =
new
StreamReader(path);
Now as a first step, we are going to read all the lines of text from the file and store
them in a list. For this, we use a
while
-instruction to continue reading while there
are lines available:
List<
string
> textlines =
new
List<
string
>();
string
line = fileReader.ReadLine();
int
width = line.Length;
while
(line !=
null
)