mardi 19 janvier 2016

How to generate a random image in Java

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;
    }
};




Aucun commentaire:

Enregistrer un commentaire