Search code examples
androidrandomunique

Random images with no repetition (image guessing)


Hello guys I'm new to android development and java programming. I hope someone can help me. I'm developing an app which is an image guessing game. I have 100 images stored in my drawable.

I currently have this code that will randomly generate an image and it will be displayed in the images view:

ImageView random_image = (ImageView) findViewById (R.id.random_level);
final int[] images = { R.drawable.img1, R.drawable.img2...R.drawable.img100 };
Random generator = new Random();
random_image.setImageResource(images[generator.nextInt(images.length - 1)]);

My question now is how can I avoid duplication of image in every level? My game composes of 25 levels.


Solution

  • Maybe create an ArrayList of those Image id's and whenever a user guesses an image, just remove that Image id position from that ArrayList

    Example:

    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(R.drawable.your_images);  //keep adding that, maybe using a loop would be better to add
    int position = new Random().nextInt(list.size());
    imageViewObject.setImageResource(Integer.intValue(list.get(position)));
    //while starting next level
    list.remove(position);
    

    That's all!