Reputation: 11
I am creating a dice game however I am not sure how to randomly generate the images so the results are random. What would be the best way to do this, I heard an array would be good but then do I need the case statements if I have an array.
/When pause completed message sent to callback
class Roll extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
}
//Receives message from timer to start dice roll
Callback callback = new Callback() {
public boolean handleMessage(Message msg) {
//Get roll result
//Remember nextInt returns 0 to 5 for argument of 6
//hence + 1
switch(rng.nextInt(6)+1) {
case 1:
dice_picture.setImageResource(R.drawable.one);
dice_picture2.setImageResource(R.drawable.five);
break;
case 2:
dice_picture.setImageResource(R.drawable.two);
dice_picture2.setImageResource(R.drawable.four);
break;
case 3:
dice_picture.setImageResource(R.drawable.three);
dice_picture2.setImageResource(R.drawable.five);
break;
case 4:
dice_picture.setImageResource(R.drawable.four);
dice_picture2.setImageResource(R.drawable.three);
break;
case 5:
dice_picture.setImageResource(R.drawable.five);
dice_picture2.setImageResource(R.drawable.two);
break;
case 6:
dice_picture.setImageResource(R.drawable.six);
dice_picture2.setImageResource(R.drawable.one);
break;
default:
}
rolling=false; //user can press again
return true;
}
};
Upvotes: 1
Views: 3292
Reputation: 1680
You wouldn't need the case statement if you declare one (or two) array(s) of drawable images like (assuming R.drawable is the correct type):
R.drawable[] dice= {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six};
R.drawable[] dice2= {R.drawable.five, R.drawable.four,...};
Then you can just write:
int randomNumber = rng.nextInt(6);
dice_picture.setImageResource(dice[randomNumber]);
dice_picture2.setImageResource(dice2[randomNumber]);
instead of your switch-code.
As requested a full working example which returns a random text:
import java.util.Random;
public class RandomText {
String[] texts={"Hello", "World", "Cafe-Babe"};
public static void main(String[] args){
RandomText randText = new RandomText();
randText.performRandom();
}
void performRandom(){
Random rand = new Random();
printText(texts[rand.nextInt(texts.length)]);
}
static void printText(String text){
System.out.println(text);
}
}
Upvotes: 3