Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a highscore system that's saves the data

Tags:

c#

save

store

I was wondering how I would go about creating a high score system. I've made a simple game with score's, but I want to have the highscores saved in a file, so when the application runs you can see the high score with the name. My code for the game so far, if needed:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Guess_the_number_1
{
    public partial class Form1 : Form
    {
        int randomNumber;
        int score;

        Random random;

        public Form1()
        {
            InitializeComponent();
            random = new Random();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            score = 0;
            label1.Text = score.ToString();
        }

        private void buttonCheckGuess_Click(object sender, EventArgs e)
        {
            randomNumber = random.Next(0, 10);

            if (Convert.ToInt32(textboxGuess.Text) == randomNumber)
            {
                MessageBox.Show("Your Guessed Correctly! The Number Is: " + textboxGuess.Text);
                score += 10;
            }
            else if (Convert.ToInt32(textboxGuess.Text) < randomNumber)
            {
                MessageBox.Show("The Number Is Larger Than: " + textboxGuess.Text);
                score -= 2;
            }
            else if (Convert.ToInt32(textboxGuess.Text) > randomNumber)
            {
                MessageBox.Show("The Number Is Smaller Than: " + textboxGuess.Text);
                score -= 2;
            }
            else
            {
                MessageBox.Show("Your Guessed Incorrectly. The Random Number Is Not: " + textboxGuess.Text);
            }
            label1.Text = score.ToString();
        }

        private void buttonScore_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Your score is " + score);
        }

        private void listScore_SelectedIndexChanged(object sender, EventArgs e) { }

        private void label1_Click(object sender, EventArgs e) { }
    }
}
like image 871
kbkasey Avatar asked Jan 24 '26 19:01

kbkasey


2 Answers

The way I would do it is to serialize it to XML. This will allow you to save several high scores, in addition, storing other info, such as the player's initials. To do this, first make a class like this:

[Serializable()]
public class HighScore {
    public int Score { get; set; }
    public string Initials { get; set; }
}

public List<HighScore> _highScores = new List<HighScore>();

You will add all your scores to the collection class:

// To save a high score
var score = new HighScore() { Score = 100, Initials = 'MAJ' };
_highScores.Add(score);
// ... add more scores if needed

Then when your application exits (or whenever you want to save the high scores), you serialize your high scores to XML:

var serializer = new XmlSerializer(_highScores.GetType(), "HighScores.Scores");
using (var writer = new StreamWriter("highscores.xml", false))
{
    serializer.Serialize(writer.BaseStream, _highScores);
}

Finally, when your application loads (or whenever), you use this code to deserialize the XML back into a high scores collection:

// To Load the high scores
var serializer = new XmlSerializer(_entities.GetType(), "HighScores.Scores");
object obj;
using (var reader = new StreamReader("highscores.xml"))
{
    obj = serializer.Deserialize(reader.BaseStream);
}
_highScores = (List<HighScore>)obj;
like image 80
Icemanind Avatar answered Jan 27 '26 09:01

Icemanind


For loading the best score use the function below

using(System.IO.StreamReader sr=new System.IO.StreamReader("fileYouHaveSavedTheScore.txt")
     this.label1.Text=sr.ReadLine();

For saving the score you can do something like this:

System.IO.StreamReader sr = new System.IO.StreamReader("fileYouHaveSavedTheScore.txt");
if(Convert.ToInt32(sr.ReadLine())<Convert.ToInt32(this.label1.Text)
{
    sr.Close();
    using(System.IO.StreamWriter sw=new StreamWriter("fileYouHaveSavedTheScore.txt",false))
        sw.WriteLine(this.label1.Text);
}

EDIT

Don't use all that Convert.ToInt32(string), it's better use the method int.TryParse(string, int out). Here you can find the reference of this method

like image 38
Tinwor Avatar answered Jan 27 '26 07:01

Tinwor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!