right now, I’m going to make a scoreboard for my game.
the program will displayed data from text file.
in the program, I have arrays of string for player name and score.
this is my streamreader code look like :
public void ReadHighScores()
{
try
{
using (StreamReader sr = new StreamReader("highscore.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(',');
for (int i = 0; i < 5; i++)
{
highScores.PlayerName[i] = parts[0];
highScores.Score[i] = parts[1];
}
}
}
}
catch (FileNotFoundException ex)
{
//IntializeHighScores();
//WriteHighScores();
}
catch (Exception ex)
{
// Handle unexpected exception
}
finally
{
// Close the file
}
}
and this is how I draw that scoreboard :
for (int i = 0; i < 5; i++)
{
spriteBatch.DrawString(spriteFont, i + 1 + ". " + highScores.PlayerName[i].ToString()
+ "......" + highScores.Score[i].ToString(), new Vector2(350, 150 + 50 * (i)), Color.Red);
}
when I run the game. the succesfully read the data from text file. but it only displayed last data in the text file.
my text file contain :
Alpha, 3500
Beta, 3600
Gamma, 2200
Delta, 3400
Epsilon, 3600
and the program only display the last data in loop like :
Epsilon 3600
Epsilon 3600
Epsilon 3600
Epsilon 3600
Epsilon 3600
what must I do to display all data from the text file, not only the last one ???
You’re almost right, but for every line you read from the file, you assign each member of the high scores array with the same data (in the
forloop). You need to figure out which line you are on (just have a counter that gets incremented on every loop of the file reading loop) and only update the respectivePlayerNameandScore.