【问题标题】:Updating an double everytime a Object is added to a ArrayList每次将对象添加到 ArrayList 时更新双精度
【发布时间】:2013-05-17 14:53:15
【问题描述】:

在我的游戏中,我希望所有僵尸都有随机颜色。我已经想出了如何改变僵尸的颜色,但问题是我不希望它们都有不同的颜色,但现在一种颜色应用于多个僵尸,下一种颜色需要一些时间应用于下一个僵尸。下面的代码是我目前用来添加僵尸的代码。

    public void initZombie(){ 
     for(int i = 0; i < player.getZombies(); i++){
      int thaXSize = xSize + 800;
      randomXSpawn = Math.random() * thaXSize + xSize;
      randomYSpawn = Math.random() * ySize;
      zombies.add(new Zombie(randomXSpawn,randomYSpawn));
      randR = Math.random() * 255;
      randG = Math.random() * 255;
      randB = Math.random() * 255;
     }
for(int i = 0; i < zombies.size(); i++){
            Zombie z = (Zombie) zombies.get(i);
            int j, k, red, green, blue, alpha;
            for(j = 0; j < 64; j++){
                for(k = 0; k < 64; k++){
                    Color c = new Color(z.getBrImage().getRGB(j, k));
                    red = c.getRed();
                    green = c.getGreen();
                    blue = c.getBlue();
                    alpha = c.getAlpha();
                    int rgb = new Color((int) randR, (int) randG, (int) randB, alpha).getRGB();
                    if(red == 0 && green == 0 && blue == 178){
                        z.getBrImage().setRGB(j, k, rgb);
                    }
                }
            }
        }
    }

我希望 randRrandGrandB 变量在每次添加一个僵尸时更新,这样它们中的任何一个都不会具有相同的颜色,我将如何实现?

【问题讨论】:

  • 真的需要加0吗?
  • 作为一个附带问题,如果程序不平凡,我认为最好避免使用 Math.random(),而不是可能获得 java.util.Random 的默认种子.如果使用 Math.random(),每次运行都是不同的,这会妨碍调试和性能测量。

标签: java variables arraylist double updates


【解决方案1】:

我们可以尝试将 RGB 颜色添加到僵尸类本身,以便每次创建新的僵尸时它都有自己的颜色。这可以由构造函数完成,如下所示:

class Zombie{

    int randR;
    int randG;
    int randB;

    double randomXSpawn;
    double randomYSpawn;

    public Zombie(double randomXSpawn, double randomYSpawn) {
        super();
        this.randomXSpawn = randomXSpawn;
        this.randomYSpawn = randomYSpawn;

        randR = (int)Math.random() * 255;
        randG = (int)Math.random() * 255;
        randB = (int)Math.random() * 255;
    }   
}

【讨论】:

    【解决方案2】:

    很难说,你在做什么,但是这个

    zombies.add(new Zombie(randomXSpawn,randomYSpawn));
    randR = Math.random() * 255 + 0;
    randG = Math.random() * 255 + 0;
    randB = Math.random() * 255 + 0;
    

    看起来随机颜色分量不是之前添加的新僵尸的属性。

    一个想法是向僵尸构造函数添加一个Color rgb 参数,并在您真正创建它时设置颜色。

    【讨论】:

    • 也许它还需要为每个 rgb 值转换(int)
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2016-08-02
    • 1970-01-01
    • 2013-10-10
    • 2019-08-19
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多