Web Hosting Talk







View Full Version : Highscore In C#


latheesan
11-29-2006, 10:42 AM
Im developing a simple snake game in C# (Console Program).

Im currently working on Highscores table for the game.

This is how the highscore should work:

- Workout Current score after game ended
- Open the highscores.txt file and assign every line of text into array
- Run a for loop to check if current score is higher than any nth element in the array of high scores
- Re-Order the array elements by highest score first to lowest score last
- Write the new ordered high score list to file

This is my first time at C#, so far i could only do this much. My code doesn't do the re-order part of the requirement, however it should do the rest. but it doesnt for some reason...

static string[] Line = new string[10];
static int[] topScore = new int[10];

static void Write()
{
// Create A Reader And Open The File
TextReader tr = new StreamReader("highscores.txt");

// Read From File
for (int i = 0; i < 10; i++)
{
Line[i] = tr.ReadLine();
}

// Close File
tr.Close();

// Convert Lines To topScore
for (int i = 0; i < 10; i++)
{
topScore[i] = int.Parse(Line[i]);
}

// New Score
int Score = 100;

// Workout If New Score Is High Score
for (int i = 0; i < 10; i++)
{
if (topScore[i] > Score)
{
topScore[i] = Score;
}
}

// Create A Writer And Open The File
TextWriter tw = new StreamWriter("highscores.txt");

// Write To File
for (int i = 0; i < 10; i++)
{
tw.WriteLine(topScore[i]);
}

// Close File
tw.Close();

// Wait
Console.ReadKey();

Can someone help me get this to work. i dont know where i am going wrong...

MrMan
11-30-2006, 02:27 AM
Using an ArrayList would make it much easier since it has a built-in sort function, add function, etc.

What part doesn't work. I assume that if you have less than 10 lines in that text file (such as no high scores yet), then you will be getting errors since it is reading nulls.

Also, a tip:


// Read From File
for (int i = 0; i < 10; i++)
{
Line[i] = tr.ReadLine();
}

// Close File
tr.Close();

// Convert Lines To topScore
for (int i = 0; i < 10; i++)
{
topScore[i] = int.Parse(Line[i]);
}


can be simplified to

for (int i = 0; i < 10; i++)
{
topScore[i] = int.Parse(tr.ReadLine());
}


That way, you don't have to run the loop twice and do not need the string array.

the--dud
11-30-2006, 05:48 AM
Also you should statically rely on your for loop running over 10 lines, because if the (l)user somehow manages to edit that file and remove a line or two... You'd probably see your application throwing lots of errors.

Never did fancy C# myself, but I presume it has some sort of method to read the length of a file aye, or the number of lines if you wanna go down that road?