我有一个if else声明,标识用户是否赢得了我的tic tac toe游戏,但这是我的使命! :)使代码更紧凑,更容易阅读,我有很多重复的代码块,减少了我的代码量。
这是我的一些代码:
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;
}
}
我想也许我可以把它放在私人方法中?但不确定你是否真的可以,我不知道如何调用该方法,甚至是一个类?
答案 0 :(得分:1)
试试这个:
Button[] greenButtons = new Button[0]; // buttons to color in green
bool enabled = true; // value of Enabled for each of addButtons() to set
if (button1.Text == "X" & button2.Text == "X" & button3.Text == "X")
{
greenButtons = new[] { button1, button2, button3 };
enabled = false;
}
else if (button1.Text == "X" & button4.Text == "X" & button7.Text == "X")
{
greenButtons = new[] { button1, button4, button7 };
enabled = false;
}
else if (button1.Text == "X" & button5.Text == "X" & button9.Text == "X")
{
greenButtons = new[] { button1, button4, button7 };
enabled = false;
}
foreach (Button button in addButton())
{
button.Enabled = enabled;
}
foreach (Button button in greenButtons)
{
button.BackColor = Color.Green;
}
答案 1 :(得分:1)
使用基础数据模型来表示您的数据。让我们说一系列的整数。
int[,] board = new int[,] {{0,0,0}, {0,0,0},{0,0,0}};
然后,只要播放X
,您就可以将数组中的位置设置为1。
每当播放O
时,您将位置设置为-1。
要检查获胜者,您只需循环结束您的获胜组合,横越,向下和2个交叉模式,如果他们= 3 X
获胜,如果他们= -3,那么O
获胜