2016-09-16 49 views
-1

我正在嘗試做一個whackamole類型的遊戲。我已經啓用了ImageViews hole1> hole 9.調用swapFace()隨機交換ImageView隨時發生。對於whackamole遊戲CountDownTimer有問題

我想通過調用start()來開始,onTick會調用newPopup()。經過長達五秒的隨機間隔後,newpopup()應該調用swapface()。

在自己的作品上調用swapface完全像它應該那樣,但是調用start()會導致不交換。我有一種感覺,我錯過了一些明顯的東西,並會欣賞一個指針。

private void start(){ 

    CountDownTimer myCount = new CountDownTimer(60000, 800){ 

     @Override 
     public void onTick(long millisUntilFinished) { 

      newPopup(); 
     } 

     @Override 
     public void onFinish(){} 
    }; myCount.start(); 
} 

private void newPopup(){ 

    Random rand = new Random(); 

    int w = rand.nextInt(5000); 

    CountDownTimer myCount3 = new CountDownTimer(w, 100) { 
     @Override 
     public void onTick(long millisUntilFinished) { 

     } 

     @Override 
     public void onFinish() { 

      swapFace(); 

     } 
    }; 
} 

private void swapFace(){ 

    Random rand = new Random(); 
    int holeNo = rand.nextInt(9); 

    final ImageView x; 

    if (holeNo ==0){ x = (ImageView) findViewById(R.id.hole1);} 
    else if (holeNo ==1){ x = (ImageView) findViewById(R.id.hole2);} 
    else if (holeNo ==2){ x = (ImageView) findViewById(R.id.hole3);} 
    else if (holeNo ==3){ x = (ImageView) findViewById(R.id.hole4);} 
    else if (holeNo ==4){ x = (ImageView) findViewById(R.id.hole5);} 
    else if (holeNo ==5){ x = (ImageView) findViewById(R.id.hole6);} 
    else if (holeNo ==6){ x = (ImageView) findViewById(R.id.hole7);} 
    else if (holeNo ==7){ x = (ImageView) findViewById(R.id.hole8);} 
    else { x = (ImageView) findViewById(R.id.hole9);} 

    x.setImageResource(R.drawable.sad); 

    int timeUp = rand.nextInt(3000) + 500; 

    CountDownTimer myCount = new CountDownTimer(timeUp, 100){ 

     @Override 
     public void onTick(long millisUntilFinished) { 

     } 
    } 
} 
+0

你是否可以在之前的'CountTimer'完成之前調用'newPopup()'? – c0der

+0

見http://stackoverflow.com/help/someone-answers – c0der

回答

0

我想你想阻止newPopup()之前調用其CountTimer實例完成。 您可以通過使用​​,或使蜱在myCount大於w(5000)做到這一點:

CountDownTimer myCount = new CountDownTimer(60000, 6000) 

,或者介紹現場

private newPopupRunning = false; 

並使用它:

private void newPopup(){ 

    if(newPopupRunning) return; 
    newPopupRunning=true; 

    Random rand = new Random(); 
    int w = rand.nextInt(5000); 

    CountDownTimer myCount3 = new CountDownTimer(w, 100) { 
     @Override 
     public void onTick(long millisUntilFinished) { 

     } 

     @Override 
     public void onFinish() { 

      newPopupRunning=false; 
      swapFace(); 

     } 
    }; 
}