C# - 为什么执行这些不同的代码会给我相同的结果?

时间:2013-02-21 09:59:40

标签: c#

我的第一个代码执行完毕,在我移动之后,计算机总是试图找到Tic Tac Toe板的右下角:

private void ComputersTurn()
    {
        Control.ControlCollection coll = this.Controls;
        foreach (Control c in coll)//for each button in form
        {
            if ((c != null) && (c is Button))//if c is a button and c has a value
            {
                if ((c.Name != "btnNewGame") && (c.Name != "btnExit")) // if the button isnt btn new game or exit
                {

                    if (c.Enabled == true) //if a button has an X
                    {
                        c.Text = "O"; //place an O
                        c.Enabled = false; //in a empty button
                        CheckComputerWinner(); //check if it wins
                        return; //return result
                    }//end of if
               }//end of if 2
            }//end of if 1
        }//end of foreach
    }//end of ComputersTurn

我得到帮助的第二个代码......做了同样的事情:

private void ComputersTurn()
    {
        Control.ControlCollection coll = this.Controls;
        foreach (Control c in coll)//for each button in form
        {
            if ((c != null) && (c is Button))//if c is a button and c has a value
            {
                if ((c.Name != "btnNewGame") && (c.Name != "btnExit")) // if the button isnt btn new game or exit
                {
                    gamefield = new Button[] { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9 };
                    int freeCount = gamefield.Count(b => b.Text != "X");

                    int offset = RandomGenerator.GenRand(0 - 8, freeCount - 1);
                    Button target = gamefield.Where(b => b.Text != "X").Skip(offset).FirstOrDefault(); ;
                    if (target != null)//if target has an X
                    {
                        // check it
                        if (c.Enabled == true)
                        {
                            c.Text = "O"; //O will be inside the button
                            c.Enabled = false; //button can no long be used
                            CheckComputerWinner(); //check if it finishes task
                            return;
                        }
                    }
               }
            }
        }
    }//end of ComputersTurn

随机生成器

public static class RandomGenerator
    {
        private static readonly Random _random = new Random();

        public static int GenRand(int x, int y)
        {
            return _random.Next(x, y);
        }
    }

我不明白为什么。第二个是针对计算机是随机的,第一个是设置为可预测的。为什么他们都做同样的事情?

1 个答案:

答案 0 :(得分:1)

第二种解决方案从不使用target值。它使用当前循环值c。将所有检查逻辑更改为使用target而不是c。您也可以一起消除外部循环和两个外部if语句。