Game Development Reference
In-Depth Information
22.6 Reading the Levels from the Text File
22.6.1 The
loadLevels
Method
In the previous chapter, we have seen how to add different game states to a game
and how to switch between them. We are going to add a new game state in this
chapter, the
playing
game state. This game state is then responsible for loading
and displaying the levels. We added a method called
LoadLevels
to this class which
creates a
StreamReader
instance to read the file. The first step is to read the first line
in the file, which contains the number of levels to be loaded. What we will then do is
create for each level an instance of a class that we added to the project called
Level
,
and
we pass the
StreamReader
instance as a parameter to the constructor
. Inside the
Level
constructor, we will then read the relevant lines from the text file to create the
Level
object. Once we are done, we close the file reader. The complete
LoadLevels
method is given as follows:
public void
LoadLevels(
string
path)
{
StreamReader fileReader =
new
StreamReader(path);
string
line = fileReader.ReadLine();
int
nrLevels =
int
.Parse(line);
for
(
int
currLevel = 1; currLevel <= nrLevels; currLevel++)
{
levels.Add(
new
Level(currLevel, fileReader));
}
fileReader.Close();
}
22.6.2 Creating the Level Object
Inside the
Level
constructor, we then create the different game objects belonging to
each level. First, we add a background image to the game world, then we read the
first few lines of information from the level text file, using the stream reader that
was passed as a parameter:
string
levelTitle = reader.ReadLine();
string
levelHelp = reader.ReadLine();
int
nrpairs =
int
.Parse(reader.ReadLine());
Then, we read the width and height of the level. In order to extract the
int
values
from the line that we read, we use the
Split
method: