Spencer
Spencer

Reputation: 21

Timer between keyboard actions

I want to make a timer between two actions, for example showing an image and then pressing a key on the keyboard. I have tried to start this by trying to measure the time between pressing space. For example pressing space starts the timer and pressing it again stops the timer. Then print the time.

I am using pygame as a key pressed tracker.

Here is my code, why is it not working?

import time
import pygame
pygame.init()
pygame.event.get()

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if key == pygame.K_SPACE:      
            start = time.time()
            if key == pygame.K_SPACE:
                end = time.time()
                print(end - start)

I thought it may be the way I try to track the space key; and utilized the helpful comment but still can't get it to work:

import time
import pygame
pygame.init()
key=pygame.key.get_pressed()
start_time = None
if key[pygame.K_SPACE]:

        if start_time == None:
            start_time = time.time()
        else:
            print(time.time() - start_time)
            start_time = None

Upvotes: 1

Views: 313

Answers (2)

001
001

Reputation: 13533

First, I'm pretty sure you need a window for pygame to produce any events. Next, you need to loop until you have 2 space presses. Here's an example:

import time
import pygame

pygame.init()

# Open a window
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()

start = None
end = None
# Loop until both keypresses received
while None == end:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:  # Note you had typo here
                if None == start:
                    start = time.time()
                else:
                    end = time.time()
                    print(end - start)

# Close window
pygame.display.quit()
pygame.quit()

Upvotes: 1

Frieder
Frieder

Reputation: 1266

You need to save the state (or start time) of the first event somewhere. Currently both your if-clauses will evaluate to True and the time will always be 0.

start_time = None
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if key == pygame.K_SPACE:
            if start_time == None:
                start_time = time.time()
            else:
                print(time.time() - start_time)
                start_time = None

Upvotes: 1

Related Questions