2016-12-31 112 views
0

在我的遊戲中,當用戶在5秒內點擊一個按鈕時,用戶可以獲得一個點數。現在我想讓計時器減少用戶獲得的每一點的時間 - 例如,零點時用戶有五秒鐘,當他有一分時,他只有4.5秒再次點擊它並得到第二點。我是否用for循環解決它?android - 隨着時間的推移倒計時

public class GameScreen extends Activity { 
    public int score = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game); 
     Button count = (Button) findViewById(R.id.button1); 
     text = (TextView) this.findViewById(R.id.textView3); 
     tvscore = (TextView) findViewById(R.id.score); 

     timer(); 
    } 

    public void gameover() { 
     Intent intent = new Intent(this, GameOverScreen.class); 
     startActivity(intent); 
    } 

    public void onClick (View view) { 
     score++; 
     tvscore.setText(String.valueOf(score)); 
     timer(); 
    } 

    public void timer(){ 
     new CountDownTimer(5000, 10) { 
      public void onTick(long millisUntilFinished) { 
       text.setText(""+String.format("%02d:%03d", 
         TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)), 
         TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)) 
         )); 
       if(animationRunning) { 
        cancel(); 
       } 
      } 
      public void onFinish() { 
       text.setText("Too slow."); 
       gameover(); 
      } 
     }.start(); 
    } 
} 

回答

1

什麼這樣做:

public void timer(float time) { 
    new CountDownTimer(time, 10) { 
     // YOUR CODE 
    } 
} 

public void onClick (View view) { 
    score++; 
    tvscore.setText(String.valueOf(score)); 
    timer(Math.max(5000-score*500, 2000)); 
} 

我想每一次點擊(分數)將減少時間500毫秒時間...

限制 - Math.max(a, b)會選擇最大的價值。是指當5000-score*500會比2000更低,它會選擇2000米利斯而不是

只有計時器方法:

public void timer() { 
    float time = Math.max(5000-score*500, 2000) 
    new CountDownTimer(time, 10) { 
     // YOUR CODE 
    } 
} 
+0

我可以設定一個上限,以減少?所以它不會少於2秒,例如? –

+0

查看更新回答:) – kristyna

+0

也可以將'timer(Math.max(5000-score * 500,2000));'部分整合到定時器中,而不是在點擊方法中? –

相關問題