我有一个数组,正在其中加载 10 张图像,如下所示:
int maxImages = 10; // Total # of images
int imageIndex = int(random(10)); // Initial image to be displayed is the first
// Declaring an array of images.
PImage[] images = new PImage[maxImages];
// Loading the images into the array
for (int i = 0; i < images.length; i ++ ) {
images[i] = loadImage( "assets/images/image" + i + ".jpg" );
}
当满足某些条件时,我将使用random()
生成一个新值并将其保存在名为imageIndex
的新变量中。如下所示:
imageIndex = int(random(images.length));
生成后,我将通过以下方式使用新的随机数调用图像:
gameimages = loadImage( "assets/images/image" + imageIndex + ".jpg" );
上面的实现工作得很好,但是有时会多次生成随机数,我希望它们在 1-10 之间唯一随机化。谁能建议我实现这个的最佳方法?
最佳答案
使用集合随机播放:
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i < images.length; i++) {
numbers.add(i+1);
}
Collections.shuffle(numbers);
关于java - random() 中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27304520/