Question

I am using this method i created to randomly create different sprites to be added to my scene using andEngine.

 Random randItem = new Random();



     face = null;
     float x = rand.nextInt((int) mCamera.getWidth() - mBallTextureRegion.getHeight());
        int ItemNumber = randFruit.nextInt(6) + 1;

        if(ItemNumber == 1){
            face = new Sprite(x,0, this.mBallTextureRegion);


        }else if(ItemNumber == 2){


            face = new Sprite(x,0,this.strawberryTextureRegion);

        }else if(ItemNumber == 3){

            face = new Sprite(x,0,this.grapeTextureRegion);

            }else if(ItemNumber == 4){
                face = new Sprite(x,0, this.watermelonRegion);

            }else if(ItemNumber == 5){
                face = new Sprite(x,0, this.cherryRegion);


            }else if(ItemNumber == 6){
                Sprite poison = new Sprite(x,0,this.poisionRegion);







            }

What i am doing is randomly generating numbers 1 - 6. And testing each time to see which number is generated and then i add the correct sprite according to the numbER.

So the problem is..Since this is for a game project using AndEngine. I want to randomly generate bonus items that are randomly generated but not generated as often as the sprites above. This should only happen in like once every few 100 sprites that are added.

Is there a better way to go about doing this? Like a class created just for this purpose?

Or am i on the right track? Any help will be greatly apprecciated!

Was it helpful?

Solution

You should probably use a switch statement rather than nested if-statements to check which item you want.

You can implement a chance to drop additional random generated items every x percentage if you want aswell, rather than putting a hard-counter on it (e.g. every 100), consider something like this:

int itemNumber = randFruit.nextInt(6) + 1;

switch(itemNumber) {
   case 1:
      //Item 1 code
      break;
   case 2: 
      //Item 2 code
      break;
   //etc. . . 
 }

//Generate random number from 1 - 100
int randomItem = (int)(Math.Random()*100);

if (randomItem >= 90 && <= 100) {
  //Generate your item
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top