![Screebshot] [1]]
无论如何,每当我调用下面的gamePlay()
方法时,我可以将不同的数字生成为x,介于0和3之间? gameplay
方法在一个循环中,我想要它,以便每次调用该方法时,都会创建一个介于0和3之间的x的新值。我在下面的代码中尝试了很多东西,比如随机生成器,但我无法弄明白。
public class MainActivity extends AppCompatActivity {
final Handler h = new Handler();
RelativeLayout rLayout;
Button play, retry;
TextView title, lose, score;
ImageView rc, gc, bc, yc, tyc, trc, tgc, tbc,tblc;
int gscore = 0;
protected void gamePlay(){
x = r.nextInt(4);
if(x == 0){
tbc.setVisibility(View.VISIBLE);
}
else if(x == 1){
tgc.setVisibility(View.VISIBLE);
}
else if(x == 2){
trc.setVisibility(View.VISIBLE);
}
else if(x == 3){
tyc.setVisibility(View.VISIBLE);
}
rLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(x == 0){
if(tbc.getY() < bc.getY()+50 && tbc.getY() > bc.getY()-50){
gscore = gscore+1;
score.setText(String.valueOf(gscore +""));
tgc.setY(tblc.getY());
tbc.setY(tblc.getY());
trc.setY(tblc.getY());
tyc.setY(tblc.getY());
}
else{
gameLost();
}
}
else if(x==1)
if(tbc.getY() < gc.getY()+50 && tbc.getY() > gc.getY()-50){
gscore = gscore+1;
score.setText(String.valueOf(gscore+"" ));
tgc.setY(tblc.getY());
tbc.setY(tblc.getY());
trc.setY(tblc.getY());
tyc.setY(tblc.getY());
}
else{
gameLost();
}
else if(x==2)
if(tbc.getY() < rc.getY()+50 && tbc.getY() > rc.getY()-50){
gscore = gscore+1;
score.setText(String.valueOf(gscore +""));
tgc.setY(tblc.getY());
tbc.setY(tblc.getY());
trc.setY(tblc.getY());
tyc.setY(tblc.getY());
}
else{
gameLost();
}
else if(x==3)
if(tbc.getY() < yc.getY()+50 && tbc.getY() > yc.getY()-50){
gscore = gscore+1;
score.setText(String.valueOf(gscore +""));
tgc.setY(tblc.getY());
tbc.setY(tblc.getY());
trc.setY(tblc.getY());
tyc.setY(tblc.getY());
}
else{
gameLost();
}
}
});
}
答案 0 :(得分:0)
问题是,每次调用gamePlay()
时,您都要使用相同的种子创建一个新的随机数生成器。那将每次给你相同的随机数序列。保证。
使保持随机数生成器的变量引用实例变量,并初始化一次。
此外,Random.nextInt(4)
将返回0,1,2或3.我不知道&#34; 0到4&#34之间是什么意思;
我建议您花点时间阅读Random
的{{3}}。
有人建议您可以删除seed
构造函数的Random
参数。但是,这意味着您每次都会从操作系统中获取随机种子。这是相对昂贵的,并且(在某些情况下)可能会因耗尽操作系统的熵源而导致问题。
在Android AP中可能没问题,其中呼叫由用户事件触发。但这不是一个好主意。
答案 1 :(得分:0)
如果您想在0
和4
之间获取随机数,请将参数更改为5
。
返回一个伪随机数,在0之间均匀分布的int值 (包括)和指定值(不包括)
int x = r.nextInt(5);
同时删除final关键字,因为您希望即使在分配了值之后也要更改它。
如果它给你错误,那么把它变成一个字段变量并且不要让它成为最终的。这应该可以解决你的问题。
...
}
});}
Random r = new Random(seed+gscore);
//initialize it in constructor below `seed` and `gscore` variables;
private int x; //move the declaration to class instead of method
protected void gamePlay(){
x = r.nextInt(5);
...
此外,您只需设置seed
一次。如果你总是设置种子,那么它将继续给你相同的答案。
修改强>
您也可以切换到Math.random()
以生成随机数。
x = (int)(Math.random()*10)%5;