I have an if else statement that identifies whether or not users have won my tic tac toe game however it’s my mission! 🙂 to make the code more compact and easier to read and I have lots of duplicate blocks of code and reduce the amount of code I have.
here’s some of my code:
if (button1.Text == "X" & button2.Text == "X" & button3.Text == "X")
{
foreach (Button button in addButton())
{
button1.BackColor = Color.Green;
button2.BackColor = Color.Green;
button3.BackColor = Color.Green;
button.Enabled = false;
}
}
else if (button1.Text == "X" & button4.Text == "X" & button7.Text == "X")
{
foreach (Button button in addButton())
{
button1.BackColor = Color.Green;
button4.BackColor = Color.Green;
button7.BackColor = Color.Green;
button.Enabled = false;
}
}
else if (button1.Text == "X" & button5.Text == "X" & button9.Text == "X")
{
foreach (Button button in addButton())
{
button1.BackColor = Color.Green;
button4.BackColor = Color.Green;
button7.BackColor = Color.Green;
button.Enabled = false;
}
}
I was thinking maybe I could put this in a private method? But not sure if you actually can and I wouldn’t know how to call upon the method, or even a class?
Use an underlying data model to represent your data. Let’s say an array of ints.
Then anytime an
Xis played, you set that position in the array to 1.Anytime an
Ois played, you set the position to -1.To check for a winner, you simply loop over your winning combinations, across, down, and the 2 cross patters and if they = 3
Xwins and if they = -3 thenOwins.