I have spent hours making a tic tac toe game just using mainly if else statements, some of the code I just copy and pasted…
How would I just create one instance of the code, then refer to it later on? – when I need that code, instead of just copy and pasting massive lines of code each time. In this block of code, I am getting a random number between 1 to 10 this number will be stored in RI… then when it’s Ai’s turn the computer will randomly input an X in the button, then using this code it will check to determine if the computer has won. I hope that make sense =)
do
{
storeRI = rc.Next(0, 10); //storing random number into storeRI so it can be used later on in life.
if (storeRI == 1 && btn1.Text == "")
{
btn1.Text = "X";
Turn = 1;
if (btn1.Text == "X" & btn2.Text == "X" & btn3.Text == "X")
{
btn1.BackColor = Color.Green;
btn2.BackColor = Color.Green;
btn3.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
else if (btn1.Text == "X" & btn4.Text == "X" & btn7.Text == "X")
{
btn1.BackColor = Color.Green;
btn4.BackColor = Color.Green;
btn7.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
}
}
for example this code, is some of the code, that I have copied atleast 10 times, and it just makes me code look ugly and really hard to read.
Any time you have copied code, you should try to move it into a method. You can then just call the method directly. In your case, a method could easily accept the three buttons to affect, and work on them directly.