gpt4 book ai didi

java - 加快随机过程

转载 作者:行者123 更新时间:2023-12-02 12:38:52 25 4
gpt4 key购买 nike

我正在练习一个简单的 Android 游戏,当用户点击它时,屏幕上会随机放置一个圆形按钮。它工作正常,但我想加快放置按钮的过程,以便游戏对用户来说变得更困难......

这是我正在使用的代码 -

public class GameWindow extends Activity implements View.OnClickListener {
static int score;
private Timer t;
private int TimeCounter = 29;
private boolean canMove = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
////Remove title screen for activty.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_game_window);
moveButton();
endonTimeOver();

}


public void endonTimeOver(){
////Activity timer for 60 seconds.

final TextView timer = (TextView) findViewById(R.id.seconds);

t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

////Set string to timer.
@Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
timer.setText(String.valueOf(TimeCounter)); // you can set it to a textView to show it to the user to see the time passing while he is writing.
TimeCounter = TimeCounter - 1;
}
});

}
}, 1000, 1000); // 1000 means start from 1 sec, and the second 1000 is do the loop each 1 sec.

new Timer().schedule(new TimerTask(){
public void run() {
GameWindow.this.runOnUiThread(new Runnable() {
public void run() {
startActivity(new Intent(GameWindow.this, Finished.class));
}
});
}
}, 30000);

}

////Move button.
private void moveButton()
{
if(!canMove){ return; }

runOnUiThread(
new Runnable()
{
@Override
public void run()
{

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

Button button = (Button)findViewById(R.id.button);
Random r = new Random();

int startX = width/2;
int startY = height/2;

if(score==0){
button.setX(startX);
button.setY(startY);
}

else {

int x = r.nextInt(width - 210);
int y = r.nextInt(height - 200);

button.setX(x);
button.setY(y);
}
}
}
);

}




////Display score
public void displayScore(int score) {
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText(String.valueOf(score));
}


@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonsound);
mp.setOnCompletionListener(new OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}

});
mp.start();

score = score + 1;
displayScore(score);
switch (v.getId()) {
case (R.id.button): {
moveButton();
}
}

}

public static int getScore(){
return score;
}}

最佳答案

对不改变的值使用全局变量:

  • findViewById 很慢
  • 没有必要每次都创建新的随机
  • 也不需要每次都获取窗口参数

关于java - 加快随机过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45032723/

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