Search code examples
c#winformsrestart

(C# Windows Forms Apps) How to Restart App


I just finished an exercise from Head First C# where I built a Typing Game. The book leaves it to the reader to figure out how to make it so the player can start a new game once they've lost. After the user loses the game, the window shows the message "Game Over". I would like to have a new window pop up and ask the user if they would like to play again once they've closed out of the game over screen. I'd like there to be two buttons; one that says "no" and one that says "yes". What I'm stuck on is how I should (or would) go about restarting the app if the user decides they want to play again. I'll copy and paste my code below:

namespace _7HeadFirstProject
{
    public partial class Form1 : Form
    { 
        Random random = new Random();
        Stats stats = new Stats();

        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // Add a random key to the ListBox
            listBox1.Items.Add((Keys)random.Next(65, 90));
            if (listBox1.Items.Count > 7)
            {
                listBox1.Items.Clear();
                listBox1.Items.Add("Game Over");
                timer1.Stop();
            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            // If the user pressed a key that's in the ListBox... 
            // ... remove it and then make the game a little faster
            if (listBox1.Items.Contains(e.KeyCode))
            {
                listBox1.Items.Remove(e.KeyCode);
                listBox1.Refresh();
                if (timer1.Interval > 400)
                    timer1.Interval -= 10;
                if (timer1.Interval > 250)
                    timer1.Interval -= 7;
                if (timer1.Interval > 100)
                    timer1.Interval -= 2;
                difficultyProgressBar.Value = 800 - timer1.Interval;

                // The user pressed a correct key, so update the Stats object...
                // ...by calling its Update() method with the argument true
                stats.Update(true);
            }
            else
            {
                // The user pressed an incorrect key, so update the Stats object...
                // ...by calling its Update() method with the argument false
                stats.Update(false);
            }

            // Update the labels on the StatusStrip
            correctLabel.Text = "Correct: " + stats.Correct;
            missedLabel.Text = "Missed: " + stats.Missed;
            totalLabel.Text = "Total: " + stats.Total;
            accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            MessageBox.Show("Would you like to play again?");
            if

        }
    }
}

DIFFERENT CLASS:

namespace _7HeadFirstProject
{
    class Stats
    {
        public int Total = 0;
        public int Missed = 0;
        public int Correct = 0;
        public int Accuracy = 0;

        public void Update(bool correctKey)
        {
            Total++;

            if (!correctKey)
            {
                Missed++;
            }
            else
            {
                Correct++;
            }

            Accuracy = 100 * Correct / Total;
        }
    }
}

Solution

  • You have the whole game working so leave that form alone. Add another form to your project and then set the new form as the startup form. You can set it as the startup form by opening Program.cs and modifying this line:

     // Instead of Form1 put the name of your new form
    Application.Run(new Form1());
    

    Double click the new form and put this code in it:

    // Note: Your load method may have a different name.
    private void Form2_Load(object sender, EventArgs e)
    {
        this.StartNewGame();
    }
    
    private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (MessageBox.Show("Continue?", "Continue?", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            this.StartNewGame();
        }
    }
    
    private void StartNewGame()
    {
        // Your game form may have a different name so change this to that name
        var gameForm = new Form2();
        gameForm.FormClosed += GameForm_FormClosed;
        gameForm.Show();
    }
    

    Every time the user presses the yes button on the dialog, you are creating a brand new instance of the form (of the game). In this new form, you can also have an array which keeps track of the total number of games and what the score of each game was so you can show it in case the user selected No. All you need is something like this:

    var games = new List<Stats>();
    // keep adding to it every time you call StartNewGame() method.