jeudi 27 mai 2021

Having trouble with my reaction test in C# Win Form [duplicate]

I am brand new to programming and have set out to learn C#. I decided to create a reaction speed test, simple "click the box when the colour changes". That all works fine...the only issue I am having is if the user clicks before the screen has changed colour (Stopwatch has started) I get an error.

I understand the error (stopwatch was null), I think! It is being caused because of the if statement trying to stop the stopwatch, when it hasn't yet been started. Problem is I'm not sure of a fix.

Any help would be appreciated, code below.

namespace Reaction_Test
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void InfoLabel_Click(object sender, EventArgs e)
    {

    }


    Timer timer;
    Stopwatch stopwatch;
    bool isTicking;


    private void ReactionButton_Click(object sender, EventArgs e)
    {
        ReactionButton.BackColor = Color.Red; //sets the click area to blue when test has started
        List<double> reactionResult = new();

        //prog crashes when button is click before it turns red, find a way of giving a "too soon" error and change colour

        if (isTicking)
        {

            stopwatch.Stop();
            ReactionButton.BackColor = Color.Aqua;
            TimeLabel.Text = stopwatch.Elapsed.TotalMilliseconds.ToString();
            reactionResult.Add(double.Parse(TimeLabel.Text));

            foreach (double react in reactionResult)
            {
                Debug.WriteLine(react);
            }
            

            isTicking = false;
        }
        else
        {
            Random random = new();
            timer = new();
            timer.Tick += Timer_Tick;
            timer.Interval = random.Next(2000, 7000);
            timer.Start();
            isTicking = true;
        }

        int index = 0;
        foreach (double react in reactionResult)
        {

            double num1 = reactionResult[index];



            if (index + 1 < reactionResult.Count)
            {

                double num2 = reactionResult[index + 1];


            }

            index++;

        }
    }






    private void Timer_Tick(object sender, EventArgs e)
    {
        ReactionButton.BackColor = Color.Green;
        timer.Stop();
        stopwatch = new();
        stopwatch.Start();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void Restart_Click(object sender, EventArgs e)
    {
        this.Controls.Clear();

        this.InitializeComponent();

        timer.Stop();
        isTicking = false;

    }

    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

}

}

Aucun commentaire:

Enregistrer un commentaire