2014-10-11 146 views
0
SetType(type); 

     for (int x = (Globals.tileSize + (int)position.X); x < ((int)position.X + (Globals.screenWidth - Globals.tileSize)); x += Globals.tileSize) 
     { 

      for (int y = (Globals.tileSize + (int)position.Y); y < ((int)position.Y + (Globals.screenHeight - Globals.tileSize)); y += Globals.tileSize) 
      { 
       tileType = tileFillTypes[random.Next(1, tileFillTypes.Count())]; 
       Tile tile = new Tile(new Vector2(x, y), tileType, false); 
       tiles.Add(tile); 
      } 
     } 

地圖生成調用此類來在一個方框中繪製隨機拼貼。 SetType(type)被調用,它是這樣做的:C#XNA - 隨機房生成

void SetType(int type) 
    { 
     if (type == 1) //ROOM TYPE 
     { 
      tileWallTypesBottom = new string[] { "", "stonewallBottom1", "stonewallBottom2", "stonewallBottom3" }; 

      tileFillTypes = new String[] { "" }; 
     } 
     else if (type == 2) 
     { 
      tileWallTypesBottom = new string[] { "", "stonewallBottom1", "stonewallBottom2", "stonewallBottom3" }; 
      tileWallTypesLeft = new string[] { "", "stonewallLeft1", "stonewallLeft2", "stonewallLeft3" }; 
      tileWallTypesRight = new string[] { "", "stonewallRight1", "stonewallRight2", "stonewallRight3" }; 
      tileWallTypesTop = new string[] { "", "stonewallTop1", "stonewallTop2", "stonewallTop3" }; 
      tileFillTypes = new String[] { "", "dirt1", "dirt1", "dirt1", "dirt1", "dirt1", "dirt1", "dirt1", "dirt1", "dirt1", "dirt2", "dirtGrassPatch", "dirt4", "dirt4", "dirt4", }; 
      tileWallCornerType = new string[] { "", "stonewallTopLeft", "stonewallTopRight", "stonewallBottomRight", "stonewallBottomLeft" }; 

     } 

    } 

這設置我的數組,我可以隨機選擇哪些貼圖。 我的問題是當我在房間的每個實例中使用此代碼生成多個房間時,房間不會從彼此隨機出來。我試過設置random = new Random();在每種情況下,它們總是具有相同的瓦片輸出。

+0

不要創建一個新的** **隨機每次,因爲它不會特別隨意。 _ [你想知道更多嗎?](http://www.dotnetperls.com/random)_ – MickyD 2014-10-11 05:12:14

回答

1

這種資源應該解釋一下你的問題的原因和解決方案常見:

http://csharpindepth.com/Articles/Chapter12/Random.aspx

相關片段:

Random類是不是真正的隨機數發生器。這是一個 僞隨機數字發生器。 Random的任何實例都有一定的 狀態量,當你調用Next(或NextDouble或NextBytes) 時,它將使用該狀態返回一些隨機的數據,這些數據看起來是 ,相應地改變其內部狀態,以便在接下來 稱你會得到另一個明顯隨機的數字。

所有這些都是確定性的。如果從具有相同初始狀態(可以通過種子提供)的Random 的實例開始,並且 對其進行相同的方法調用序列,則會得到相同的 結果。

那麼在我們的示例代碼中出了什麼問題?我們在循環的每次迭代中都使用了一個新的實例 Random。 Random的無參數構造函數 將當前日期和時間作爲種子 - 在內部計時器 計算出當前日期和時間已更改之前,您通常可以執行相當數量的代碼。因此,我們是 重複使用相同的種子 - 並重復獲得相同的結果 。

一個例子解決方案:

// Somewhat better code... 
Random rng = new Random(); 
for (int i = 0; i < 100; i++) 
{ 
    Console.WriteLine(GenerateDigit(rng)); 
} 
... 
static int GenerateDigit(Random rng) 
{ 
    // Assume there'd be more logic here really 
    return rng.Next(10); 
} 
+0

我不知道我在跟隨你的解釋。我的代碼有什麼問題?它會隨機生成精緻的房間,但所有房間的結果與第一個房間產生的結果完全相同。我將如何刷新隨機值? – user2578216 2014-10-11 02:04:13

+0

簡短的答案是避免每次都創建一個新的Random,因爲它會重置它。長久的回答是,Random不是隨機化的最佳提供者,並且您最好創建或使用更復雜的隨機數生成過程,這需要花費一點努力和學習。 – 2014-10-11 03:03:17

+0

@SilasReinagel關於** Random **的一個很好的描述,但考慮在上下文中稍微編輯一下OP – MickyD 2014-10-11 05:15:22