可能重复:
Java random always returns the same number when I set the seed?
在我的游戏中有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个移动相同的怪物。
答案 0 :(得分:1)
我强烈怀疑Random
有效!来自here
如果使用相同的种子创建了两个Random实例,那么 为每个方法调用相同的方法调用,它们将生成和 返回相同的数字序列。
和
在同一毫秒内创建的两个随机对象将具有 相同的随机数序列。
所以我怀疑你是在创建具有相同种子的多个Random
实例,因此每次都会得到相同的随机数序列。
答案 1 :(得分:1)
对于旧版本的Java 1.4.2及之前版本,以及可能使用的版本,随机播放了System.currentTimeMillis()
这意味着如果您在此调用的分辨率内创建多个Random,则在1之间和16毫秒,你会得到相同的种子。
一个简单的解决方法是创建一个Random
并重新使用它。这样效率更高,并确保每次调用都会产生随机值。
Java 5.0通过使用System.nanoTime()和AtomicLong counetr修复此问题,以确保每次种子都不同。
答案 2 :(得分:1)
尝试创建一个Random并重用它而不是每次都创建一个新的(如果你有多个线程为每个线程创建一个)。
答案 3 :(得分:1)
这可能是种子问题。使用new Random(seed)
constructor。
也许你可以用类似
之类的东西来称呼它new Random(System.currentTimeMillis());
虽然如果你在同一毫秒内多次调用它,你会遇到同样的问题。我不认为你需要多次打电话。只需重用该对象。