C#如何缩短这个长时间加载的do while语句

时间:2013-01-26 02:14:18

标签: c# winforms visual-studio-2012

我做了一个tic tac toe游戏,我正在使用更少的代码制作另一个版本。无论如何......这是我的代码......我在do while语句之间采取了一些代码,但是是的......

    var rc = new Random();
    do
    {
        storeRI = rc.Next(1, 9);

        if (storeRI == 1 & button1.Text == "")
        {
            button1.Text = "O";
            Turn = 1;
            TestWin();
            break;
        }
        else if (storeRI == 2 & button2.Text == "")
        {
            button2.Text = "O";
            Turn = 1;
            TestWin();
            break;
        }


    } while (Turn == 2 & button1.Text == "" | button2.Text == "" | button3.Text == "" | button3.Text == "" | button4.Text == "" | button5.Text == "" | button6.Text == "" | button7.Text == "" | button8.Text == "" | button9.Text == "");
}
else
{
    MessageBox.Show("It's a draw");
}

我主要想关注这段代码......缩短......:)

 } while (Turn == 2 & button1.Text == "" | button2.Text == "" | button3.Text == "" | button3.Text == "" | button4.Text == "" | button5.Text == "" | button6.Text == "" | button7.Text == "" | button8.Text == "" | button9.Text == "");

1 个答案:

答案 0 :(得分:4)

从各个按钮创建按钮列表,然后将其更改为

while(Turn==2 && buttons.Any(b => b.Text == ""))

一般情况下,9个按钮可能位于数组或列表中,以便更简单地访问:

Button[] buttons = new Button[] {button1, button2, button3, ... } ;

然后您可以buttons[0]而不是button1等方式访问它。

我会在你的Form初始化程序中执行此操作,而不是具有按需执行此操作的功能。