2013-02-21 7 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 

두 번째 코드, 내가 도움을 받았습니다 ..

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); 
     } 
    } 

내가 왜 이해가 안 : 똑같은 일을 .does. 두 번째는 컴퓨터를 무작위로 만들기위한 것이고, 첫번째는 예측 가능하도록 설정되어 있습니다. 왜 둘 다 똑같은 짓을하는거야?

+1

'c'는 어떻게 정의되어 있습니까? 그리고 "같은 결과"가 무슨 뜻입니까? – antonijn

+0

어떻게 든 코드가 손상 되었기 때문에? '예측할 수 없음'은 작동 할 수 있음을 의미합니다 :-) –

+0

무작위 값을 생성하는 코드를 사용할 수없는 경우 임의의 결과를 제공하지 않는 이유는 무엇입니까? ( – Evelie

답변

1

두 번째 솔루션에서는 target 값을 사용하지 않습니다. 현재 루프 된 값 c을 사용합니다. 모든 체크 로직을 변경하여 c 대신 target을 사용하십시오. 외부 루프와 두 개의 외부 if 문을 함께 제거 할 수 있습니다.

+0

조금 바뀌 었습니다. 이제는 항상 왼쪽 상단을 선택합니다. 그러나 오래된 첫 번째 코드와 마찬가지로이 코드가이기거나 잃는 지 (코드를 작성하지 않은 코드)에 따라 위치가 변경됩니다. –

+0

도움이 된 것을 기쁘게합니다. 귀하의 프로젝트와 함께 행운을 빈다. –

+0

아, 알았어 @ 에블리가 다른 문제를 해결했다. 감사합니다 <3! –

관련 문제