Reputation: 213
I was making a simple timer in pygame that goes in seconds, and increments for every 1000 milliseconds that pass, although if I phrased my if-statement in a certain way, the elapsed time would remain at 0 milliseconds.
I created these two variables before the main loop
seconds=0
timer=0
The below executes in the pygame loop
time_elapsed= clock.tick()
timer+= time_elapsed
if timer>=1000 or time_elapsed==0:
screen.fill((255,255,255))
text(screen, "Timer: " + str(seconds))
seconds+=1
timer=0
text
is a custom function a created that displays the timer on the screen.
I wanted text to be displayed when the elapsed time was 0 milliseconds, so the 0 seconds would be shown. However, the screen then kept updating this at least 50 times per second. When it's just
if timer>=1000
The program runs fine, and the timer increments by 1 every 1 second. I then realised time_elapsed
was causing me problems, so I modified the if-statement to check for time_elapsed
's value only, and the same problem persisted.
This didn't make any seconds, because every time the loop reiterates, the value of time_elapsed
should never be 0, except for the first time the loop executes.
Interestingly, whenever I added a print statement to the loop, I wouldn't experience any issues. For example, I included an else statement whereby time_elapsed
wasn't 0 and printed its value, which caused the initial if-statement to never be executed unless it was the first execution of the loop.
So my question is, is that why does the time in milliseconds since the previous call of clock.tick()
remain at 0 seconds if I test it in an if-statement, unless I intervene with a print statement.
Note: I know there are other ways I could have written this program.
EDIT:
In response to the first answer's edit, I forgot to mention that
if time_elapsed==0:
screen.fill((255,255,255))
text(screen, "Timer: " + str(seconds))
seconds+=1
timer=0
Will also repeatedly get executed, meaning the if-statement block doesn't seem to be playing a part in making clock.tick()
0 or not.
Upvotes: 1
Views: 322
Reputation: 128
My guess is that the time between executions of clock.tick()
is so short that time_elapsed evaluates to 0 in the if statement. The print statement was probably slowing down the execution just enough so that time_elapsed==0
evaluated to false.
A possible solution to this would be to add a framerate of frames per second such as clock.tick(60)
. I believe this would cause the program to execute 60 loops per second, although I'm not too familiar with pygame.
Edit: since you said clock.tick returns a whole integer I think I see what's happening:
When the if block is executed, the time between each clock.tick() is >1, when the block is not executed, it is <1, which causes clock.tick() to return 0. This creates an alternating loop of the if block being executed every other time. When you added the else statement, it caused clock.tick() to always be greater than 0.
Upvotes: 2