Faria Armin

Faria Armin

  • NA
  • 6
  • 754

Code for traffic lights

Dec 11 2021 11:04 PM

Hi,

I am trying to control two traffic lights in C#. Here is my code:

 public Form1()
        {
            InitializeComponent();
            RedStopLight.Visible = true;
            YellowStopLight.Visible = false;
            GreenStopLight.Visible = false;
            RedStopLight1.Visible = true;
            YellowStopLight1.Visible = false;
            GreenStopLight1.Visible = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (RedStopLight1.Visible == true)
            {
                RedStopLight.Visible = false;
                YellowStopLight.Visible = false;
                GreenStopLight.Visible = true;
                RedStopLight1.Visible = true;
                YellowStopLight1.Visible = false;
                GreenStopLight1.Visible = false;


            }
            if (GreenStopLight.Visible == true)
            {
                RedStopLight.Visible = false;
                YellowStopLight.Visible = true;
                GreenStopLight.Visible = false;
                RedStopLight1.Visible = true;
                YellowStopLight1.Visible = false;
                GreenStopLight1.Visible = false;
            }
            if (YellowStopLight.Visible == true)
            {
                RedStopLight.Visible = true;
                YellowStopLight.Visible = false;
                GreenStopLight.Visible = false;
                RedStopLight1.Visible = false;
                YellowStopLight1.Visible = false;
                GreenStopLight1.Visible = true;
            }

            if(GreenStopLight1.Visible==true)
            {
                RedStopLight.Visible = true;
                YellowStopLight.Visible = false;
                GreenStopLight.Visible = false;
                RedStopLight1.Visible = false;
                YellowStopLight1.Visible = true;
                GreenStopLight1.Visible = false;
            }
            if(YellowStopLight1.Visible==true)
            {
                RedStopLight.Visible = false;
                YellowStopLight.Visible = false;
                GreenStopLight.Visible = true;
                RedStopLight1.Visible = true;
                YellowStopLight1.Visible = false;
                GreenStopLight1.Visible = false;
            }

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void GreenStopLight_Click(object sender, EventArgs e)
        {

        }

So when I am running the code, only the green light of one traffice signal and the red light of another traffic signal is showing, Other lights aren't visible for next conditions. Can you tell me where I am wrong?


Answers (2)