2014-10-11 144 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