2014-05-10 87 views
1

我不明白爲什麼消息箱會一直顯示0.對於每個序列都有一個方向。隨機函數的目的是找到開始新序列的最佳點。我的自由功能似乎有問題,我不明白問題所在,請幫助我。在井字遊戲最終項目中的隨機函數

public int howfree(int x, int y) 
    { 
     int freenum = 0; 
     int counter = 0; 
     foreach (GameForm.direction dirs in (GameForm.direction[]) Enum.GetValues(typeof(GameForm.direction))) 
     { 

      for (int j = 0; j < 5; j++) 
      { 
       y += Directions[(int)dirs, 0]; 
       x += Directions[(int)dirs, 1]; 
       if (InBoard(y, x) && cells[y,x].cellType == Type.EMPTY) 
       { 
        counter++; 
       } 
       else 
        break; 
      } 
      if (counter == 5) 
      { 
       freenum++; 
      } 
      counter = 0; 
     } 
     return freenum; 
    } 

/////////////////////// ////////////////////////////////////

public Cell Randomize() 
    { 
     int row=0; 
     int col=0; 
     Random random = new Random(); 
     int rand = 0; 
     //bool Found = false; 
     int max = 0; 
     int fff=0; 
     List<Cell> Options = new List<Cell>(); 
     foreach (Cell CCC in cells) 
     { 
      fff=howfree(CCC.row,CCC.col); 
      if (fff > max) 
       max = fff; 
     } 
     foreach (Cell c in cells) 
     { 
      if (howfree(c.row, c.col) == max) 
      { 
       Options.Add(new Cell(c.row, c.col)); 
      } 
     } 

     // while (!Found) 
     // { 
      rand = (int)random.NextDouble() * (Options.Count - 1); 
      //row = random.Next() * (Settings.Rows); 
      //col = random.Next() * (Settings.Cols); 
      MessageBox.Show(rand.ToString()); 
      row = Options[rand].row; 
      col = Options[rand].col; 
     //} 
     return new Cell(row, col); 
    } 

回答

0

你做錯了。

rand = (int)random.NextDouble() * (Options.Count - 1); 

Random.NextDouble()將產生0到小於1.0之間的數字。 這意味着它可以得到高達0.999(你明白我的意思),但絕不會是1

當您使用一小部分明確INT投小於0且小於1大,你總是會得到0

因此,現在將期權的數量後的int投

rand = (int)(random.NextDouble() * (Options.Count - 1)); 

你應該已經做到了這個樣子。

2

爲什麼不使用專爲整數設計的重載?

rand = random.Next(Options.Count); 

MSDN documentation

返回非負隨機整數小於指定的最大。