Confused with a piece of code form a tetris game controling the speed of the block

StackOverflow https://stackoverflow.com/questions/12189268

  •  29-06-2021
  •  | 
  •  

Question

        if(loopCount % (20 - loopCount / 100) == 0) {
            if(dropBlock() == false) {
                mode = -1;
                loopCount = 1;
            }
            if(loopCount == 1900)
                loopCount--;
        }
        loopCount++;

A tetris program from a book written by java. I just can't understand why using such a piece of code to control the droping speed of a block and how it works. Thank you !

The initial value of loopCount is 1 and dropBlock will return false if the game ends. This piece is contained in the main loop. And the mode is not relevant. I am sorry but I just can't gvie the whole program here.

Was it helpful?

Solution

It appears that it is set to have loopcount start at one, and lets use a table to examine the effect of if(loopCount % (20 - loopCount / 100) == 0) {

loopCount < 100, loopCount/100 = 0, so loopCount % 20 returns true for 20, 40, 60 and 80. Lets say loopCount is 100 - 199. Now we're checking if it's divisible by 19, for 200-300 divisible by 18. I'm not sure what exactly he is trying to achieve with this though. Then it checks if it fails to drop the block maybe, (dropBlock possibly tried to drop the block, and returns true for success, false for failure. Then if it fails it sets mode to -1 (maybe exits?). Then once loopCount reaches 1900, it prevents it from going up (by decreasing to 1899 right before the loopCount++;, which essentially decreased then increases, so does nothing (holding it at 1900)

OTHER TIPS

The code is a good example of how not to write good code. It's full of magic numbers (1900, 20, 100) which make it hard to reason why you are doing what you are doing.

But implementing this, and printing out the value shows that the value of loopCount just keeps growing from 1 to 1900 and once it hits 1900, it stays there.

So it looks to me that what the logic does is decrement to 1899 and increment to 1900 every iteration once 1900 is reached.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top