使用CountDownTimer进行whackamole游戏时遇到问题

时间:2016-09-16 23:45:30

标签: java android-studio methods countdowntimer

我正在尝试做一个whackamole类型的游戏。我已经启用了ImageViews hole1>第9洞。调用swapFace()会像我想要的那样随机交换ImageView。

我想首先调用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) {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想你想阻止newPopup()在之前的CountTimer实例完成之前被调用。 您可以使用synchronizedmyCount中的勾号大于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();

        }
    };
}