Reputation: 33
I've created a simple game in Pygame that displays an image of a certain emotion for x amount of time, before giving participants the opportunity to select which emotion was displayed by pressing a button. However, I'm having trouble maintaining the display time for images. I use clock.tick() to get a value for delta time, but it seems that it's 3x slower than it should be. If I set the timer to 1000ms, for example, the image is displayed for ~3 seconds, whereas I only want it to display for 1 second. I can always divide the display time by 3 to get it roughly correct, but I want to understand what's causing this. Here's the main game loop:
def mainGame(images):
dt = 0 #delta time is set to 0 to begin
timer = displayTime #displayTime by default is 1000ms
imageNumber = 0
gameState = States.VIEWING #this is the game state where a participant views a question
running = True
while running:
mouse = pygame.mouse.get_pos()
screen.fill((255, 255, 255))
mainDisplay() #this displays the answer buttons
clock = pygame.time.Clock()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if ( gameState == States.VIEWING):
dt = clock.tick_busy_loop(30) #should increase delta time by however many ms have passed
timer -= dt #minus delta time from the timer
if timer >= 0: #if the timer remains above 0, continue displaying image
askQuestion(images, imageNumber)
else: #when timer reaches 0, stop displaying image and move to answering state
gameState = States.ANSWERING
elif (gameState == States.ANSWERING): #this is where participants select their answer
timer = displayTime #reset the timer
screen.fill((255, 255, 255))
mainDisplay() #displays answer buttons
for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not
if event.type == pygame.MOUSEBUTTONDOWN:
if rects.collidepoint(mouse): #if a button is clicked
gameState = States.VIEWING #switch back to viewing state
answers.append(emotion) #add answer to answer list
imageNumber += 1 #move to the next image
elif not any(rect.collidepoint(mouse) for rect in rectList): #if a button is not clicked
print("You did not select an answer")
break
if practice == True: #if in practice mood, stop when number of practice questions is reached
if len(answers) == pnumberofQuestions:
break
elif practice == False: #if in main game loop, stop when number of questions is reached
if len(answers) == numberofQuestions:
break
pygame.display.update()
Upvotes: 2
Views: 338
Reputation: 2779
You are creating a new clock each pass through the while
loop.
Move
clock = pygame.time.Clock()
out of your
while running:
and put it somewhere above it.
Upvotes: 3