gpt4 book ai didi

java - 如何在 Java 中生成随机图像

转载 作者:行者123 更新时间:2023-11-29 04:52:32 26 4
gpt4 key购买 nike

我正在创建一个骰子游戏,但我不确定如何随机生成图像以便结果是随机的。执行此操作的最佳方法是什么,我听说数组会很好,但是如果我有一个数组,我还需要 case 语句吗?

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

最佳答案

如果声明一个(或两个)可绘制图像数组(假设 R.drawable 是正确的类型),则不需要 case 语句:

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

然后你就可以写:

int randomNumber = rng.nextInt(6);
dice_picture.setImageResource(dice[randomNumber]);
dice_picture2.setImageResource(dice2[randomNumber]);

而不是你的开关代码。

根据要求返回随机文本的完整工作示例:

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

关于java - 如何在 Java 中生成随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com