Something like this
import pygame
import time
#create window
win = pygame.display.set_mode((500, 500))
#take start time, end time and bool is mouse is pressed
def get_time(start, end, pressed):
#calculate time
timer = end - start
#return timer if it is pressed
if pressed:
return timer
#get start time
start = time.time()
while True:
pygame.event.get()
#get if RMB is pressed
pressed = pygame.mouse.get_pressed()[2]
#calculate current time
now = time.time()
#call the function and store the return value in a variable
timepressed = get_time(start, now, pressed)
#print the value
print(timepressed)
EDIT:: I have left the code above as well for reference but below is the code that only returns the value when mouse is released. It used pygame.MOUSEBUTTONDOWN
and pygame.MOUSEBUTTONUP
. I also made it a class just to avoid having to declare everything global.
import pygame
import time
#create window
win = pygame.display.set_mode((500, 500))
class Timer:
def __init__(self):
#start time
self.start = time.time()
#timer is the amount of time passed after mouse is pressed
self.timer = 0
#mouse button up
self.up = False
#mouse button down
self.down = False
#if rmb is held down
self.rmb = False
#now
self.now = 0
#update now
def update(self):
self.now = time.time()
def timeRMB(self):
#if rmb is pressed and pygame mouse button down is true
if self.rmb:
if self.down:
#actual timer
self.timer = self.now - self.start
else:
#if mouse button up is true
if self.up:
#reset the timer
self.start = self.now
return self.timer
#get start time
timer = Timer()
while True:
events = pygame.event.get()
#get if RMB is pressed
timer.rmb = pygame.mouse.get_pressed()[2]
#get mouse events
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
timer.down = True
if not event.type == pygame.MOUSEBUTTONDOWN:
timer.down = False
if event.type == pygame.MOUSEBUTTONUP:
timer.up = True
if not event.type == pygame.MOUSEBUTTONUP:
timer.up = False
timer.update()
#call the function and store the return value in a variable
timepressed = timer.timeRMB()
print(timepressed)