java - j2me随机不起作用

标签 java random

Possible Duplicate:
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 个移动相同的怪物。

最佳答案

尝试创建一个 Random 并重复使用它,而不是每次都创建一个新的(如果您有多个线程,每个线程创建一个)。

关于java - j2me随机不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13143470/

相关文章:

c# - 这是生成一串随机字符的好方法吗?

java - 无法从 START_OBJECT token 中反序列化 java.lang.Class 的实例

java - 对 DataStore 异常执行查询

java - 使用 Jackson JSR310 模块反序列化 LocalDateTime

代码可以运行,但有一些小错误,我不知道它在哪里?

javascript - 使用 window.crypto.getRandomValues 在 JavaScript 中洗牌扑克牌

python - 如何使用随机选择颜色

math - 如何为游戏生成随机算术表达式

java - 如何从 DatePickerDialog 显示月份名称 - Android Studio

java - 为什么 GUI 应用程序使用左上角而不是左下角?