首页 > 解决方案 > 多次调用 Slot、stop 方法

问题描述

我有一个老虎机代码,它通过随机水果滚动,每个插槽都有一个 maxCount。一旦达到 maxCount,该插槽将停止。但是,有时会多次调用 slot、stop 方法。有任何想法吗?

定时器任务

 TimerTask task = new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new TimerTask() {
            @Override
            public void run() {
                count++;
                if (!slotOneFinished){
                    animate(randomSwitchCount(), slotOne, count);
                }
                if (!slotTwoFinished) {
                    animate(randomSwitchCount(), slotTwo,count);
                }
                if (!slotThreeFinished) {
                    animate(randomSwitchCount(), slotThree,count);
                }
            }
        });
    }
};

停止功能

public void stop(ImageSwitcher slot){
    if (slot.equals(slotOne)){
        slotOneFinished=true;
        Toast.makeText(MainActivity.this, "1",Toast.LENGTH_SHORT).show();
    }
    if (slot.equals(slotTwo)){
        slotTwoFinished=true;
        Toast.makeText(MainActivity.this, "2",Toast.LENGTH_SHORT).show();
    }
    if (slot.equals(slotThree)){
        slotThreeFinished=true;
        Toast.makeText(MainActivity.this, "3",Toast.LENGTH_SHORT).show();
    }
    if (slotOneFinished&&slotTwoFinished&&slotThreeFinished){
        executor.shutdown();
        executor=null;
        roll.setEnabled(true);
        checkWin(getFruits());
        slotOneFinished=false;
        slotTwoFinished=false;
        slotThreeFinished=false;
    }
}

启动功能

 public void start() {
        if(executor==null) {
            count =0;
            executor = Executors.newSingleThreadScheduledExecutor();
            executor.scheduleAtFixedRate(task,10,200,TimeUnit.MILLISECONDS);
        }
    }

动画功能

  public void animate(final int maxCount, final ImageSwitcher slot, int i) {
    if (i<maxCount){
        Animation in = AnimationUtils.loadAnimation(this, R.anim.new_slot_item_in);
        Animation out = AnimationUtils.loadAnimation(this, R.anim.old_item_out);
        slot.setInAnimation(in);
        slot.setOutAnimation(out);
        int fruit = randomFruit();
        slot.setTag(fruit);
        slot.setImageResource(fruit);
    }else {
        stop(slot);
    }
}

Count 在程序开始时设置为 0,randomSwitchCount() 返回一个介于 10 到 40 之间的随机数。我假设我没有运行某些代码的正确顺序。我在测试期间使用 toast 消息来突出我的问题。如果您认为我的功能和逻辑有任何其他问题,我会全神贯注。

谢谢,

圆周率网

标签: androidlogicscheduledexecutorservice

解决方案


计时器计划再运行一次。但是在计时器运行之前,每个时隙的 isFinished 都设置为 false,因此条件变为 true。相反,我仅在滚动按钮完成时将它们设置为 false,以便时间与获胜检测同步。


推荐阅读