내 첫 번째 코드는 실행하고 나는 내 이동을 한 후, 컴퓨터가 항상 박하 사탕 발가락 보드의 오른쪽 아래 자리 얻기 위해 시도 :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. 두 번째는 컴퓨터를 무작위로 만들기위한 것이고, 첫번째는 예측 가능하도록 설정되어 있습니다. 왜 둘 다 똑같은 짓을하는거야?
'c'는 어떻게 정의되어 있습니까? 그리고 "같은 결과"가 무슨 뜻입니까? – antonijn
어떻게 든 코드가 손상 되었기 때문에? '예측할 수 없음'은 작동 할 수 있음을 의미합니다 :-) –
무작위 값을 생성하는 코드를 사용할 수없는 경우 임의의 결과를 제공하지 않는 이유는 무엇입니까? ( – Evelie