2013-02-21 51 views
1

我的第一個代碼執行後,我讓我的舉動,計算機總是試圖得到一個井字板的右下角點:C# - 爲什麼執行這些不同的代碼給了我相同的結果?

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 

第二個代碼,這是我得到幫助的.. .does同樣的事情:

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

如何定義'c'? 「同樣的結果」是什麼意思? – antonijn 2013-02-21 10:01:17

+0

因爲不知何故代碼被破壞? '不可預知'意味着它可能工作:-) – 2013-02-21 10:01:57

+0

很難說,爲什麼它不提供隨機結果,當生成隨機值的代碼不可用:( – Evelie 2013-02-21 10:05:12

回答

1

第二種解決方案從不使用target值。它使用當前循環值c。將所有檢查邏輯改爲使用target而不是c。您還可以一起消除外部循環和兩個外部if語句。

+0

這改變了一點。現在它總是選擇左上角。然而,就像舊的第一代碼一樣,它會根據它是贏還是輸(但我沒有編碼)來改變它的位置。 – 2013-02-21 10:12:51

+0

很高興幫助。祝您的項目好運! – 2013-02-21 10:18:44

+0

啊,明白了@Evelie解決了另一個問題。謝謝<3! – 2013-02-21 10:19:03

相關問題