0

可能重复:
当我设置种子时,Java random 总是返回相同的数字?

在我的游戏中,有 4 个怪物正在移动到相同的随机生成坐标。这意味着随机不工作。

 public void run() {
    while (true) {

                    // paints all Sprites, and graphics
        updateScreen(getGraphics());

        try {
            Thread.sleep(sleep);

        } catch (Exception e) {
        }
    }
}


private void updateScreen(Graphics g) {

     loops through all monsters and moves them a bit
     for (int gi = 0; gi < bottX.length; gi++) {

      bot(gi); // moves a  specified monster or gets new coordinates
     }

}

private void bot(int c) {

// some stuff to move a monster



 // if a monster is in desired place, generate new coordinates

    if(isInPlace()){
       // g]randomly generates new coordinates X and Y
        botX(c);
    botY(c);

    }


 }



public void botX(int c) {

           // monsters walking coordinates are between 30 px from the spawn zone.
    Random r1 = new Random();
    int s = r1.nextInt(3);
    // number 0 - left 1 - right 2 - don`t go in X axis
            // monster spawn coordinate
    int botox = spawnnX[c];
    int einamx;


    if (s == 0) {

        einamx = r1.nextInt(30) + (botox - 30); 
                    // [botox-30; botox)
    } else if (s == 1) {
        einamx = r1.nextInt(29) + (botox + 1); // (botoX+1 botoX+30]
    } else {
        einamx = botox;
    }



            // sets to where the monster should go
    einammX[c] = einamx;
    return;




          }

所以在这个游戏中是 4 个怪物,它们的生成坐标是相等的,你只能看到 1 个怪物,因为它们移动相同。顺便说一句,如果我设置不同的生成坐标,我可以看到 4 个移动相同的怪物。

4

4 回答 4

1

I suspect strongly that Random does work! From here

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

and

Two Random objects created within the same millisecond will have the same sequence of random numbers.

So I suspect you're creating multiple Random instances with the same seed, and so you're getting the same sequence of random numbers each time.

于 2012-10-30T16:28:38.967 回答
1

With older versions of Java 1.4.2 and previous, and possibly the version you are using, the Random was seeded with the System.currentTimeMillis() This meant if you creating multiple Random to within the resolution of this call, between 1 and 16 ms, you would get the same seed.

A simple work around is to create one Random and re-use it. This is more efficient and ensures each call will give a random value.

Java 5.0 fixed this by using System.nanoTime() and an AtomicLong counetr to ensure the seed is different each time.

于 2012-10-30T16:29:58.697 回答
1

Try to create one Random and reuse that instead of creating a new every time (if you have multiple threads create one per thread).

于 2012-10-30T16:30:25.593 回答
1

应该是种子问题。使用new Random(seed) 构造函数

也许你可以用类似的东西来称呼它

new Random(System.currentTimeMillis());

尽管如果您在同一毫秒内多次调用它,您将遇到同样的问题。我认为您不需要多次调用。只需重用该对象。

于 2012-10-30T16:30:31.077 回答