Everytime you have a flip (not matter if it’s previously a “top” or “bottom”), then you are resetting the other one. This is wrong. You will only need to reset it if the previous flip is different than the current flip and the total number of flips is less than 3. The condition in your loop is also wrong, it should be:
while (($top != 3) && ($bottom != 3))
1
solved Multiple conditions in while loop don’t work properly