I have a slot machine code where it rolls through random fruits with a maxCount for each slot. Once the maxCount is reached that slot will stop. However, sometimes the slot, stop method is called more than once. Any ideas?
TimerTask
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);
}
}
});
}
};
Stop function
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;
}
}
Start function
public void start() {
if(executor==null) {
count =0;
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(task,10,200,TimeUnit.MILLISECONDS);
}
}
Animate function
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 is set to 0 at the beginning of the program and randomSwitchCount() returns a random number between 10 and 40. I am assuming that I do not have the correct order of running some code. I used the toast messages to highlight my problem during testing. If there is anything else which you see wrong with my functions & logic, I am all ears.
Thanks,
Pi Net
The timer was scheduled to run one more time. But isFinished was set to false for every slot just before the timer ran so the condition became true. Instead, I set them to false only when the roll button was finished so that the time was in sync with the win detection.