Pygame-mouse事件中的Python时间计数器 [英] Python time counter in Pygame-mouse events
问题描述
我想计算用户在Pygame中的鼠标事件的时间,如果用户大约15秒钟没有移动鼠标,那么我想在屏幕上显示文本.我为此尝试了time
模块,但是它不起作用.
I want to calculate the time of user's mouse events in Pygame, if user doesn't move his mouse about 15 seconds, then I want to display a text to the screen. I tried time
module for that, but it's not working.
import pygame,time
pygame.init()
#codes
...
...
font = pygame.font.SysFont(None,25)
text = font.render("Move your mouse!", True, red)
FPS = 30
while True:
#codes
...
...
start = time.time()
cur = pygame.mouse.get_pos() #catching mouse event
end = time.time()
diff = end-start
if 15 < diff:
gameDisplay.blit(text,(10,500))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
输出不是我想要的,如果用户不移动鼠标,我不知道如何计算.
Well output is not what I want, I don't know how to calculate it if user doesn't move his mouse.
如果我想在用户的鼠标放在特殊区域内写文本时,它的工作方式就像
If I want to write a text when user's mouse in a special area, it's working like;
if 100 < cur[0] < 200 and 100 < cur[1] < 200:
gameDisplay.blit(text,(10,500))
但是我该如何计算呢?我什至找不到如何告诉Python,用户的鼠标是否在同一坐标上.然后我可以说,如果鼠标坐标发生变化,请启动计时器,如果它大于15,则打印文本.
But how can I calculate? I even couldn't find how to tell Python, user's mouse is on the same coordinates or not.Then I can say, if mouse coordinates changes, start the timer, and if it's bigger than 15, print the text.
您可以在不带Pygame模块的普通Python中进行假设,并假设您具有捕获鼠标事件的功能,然后如何判断Python如果鼠标坐标没有变化,请启动Python.计时器,如果时间大于15秒,请打印文本,然后刷新计时器.
You can assume it in normal Python without Pygame module, assume you have a function that catching the mouse events, then how to tell Python if coordinates of mouse doesn't change, start the timer, if the time is bigger than 15 seconds,print a text, then refresh the timer.
推荐答案
如果pygame窗口中3秒钟内没有鼠标移动,则在屏幕上显示文本:
To display a text on the screen if there is no mouse movement within the pygame window for 3 seconds:
#!/usr/bin/python
import sys
import pygame
WHITE, RED = (255,255,255), (255,0,0)
pygame.init()
screen = pygame.display.set_mode((300,200))
pygame.display.set_caption('Warn on no movement')
font = pygame.font.SysFont(None, 25)
text = font.render("Move your mouse!", True, RED, WHITE)
clock = pygame.time.Clock()
timer = pygame.time.get_ticks
timeout = 3000 # milliseconds
deadline = timer() + timeout
while True:
now = timer()
if pygame.mouse.get_rel() != (0, 0): # mouse moved within the pygame screen
deadline = now + timeout # reset the deadline
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(WHITE)
if now > deadline: # no movement for too long
screen.blit(text, (10, 50))
pygame.display.flip()
clock.tick(60) # set fps
这篇关于Pygame-mouse事件中的Python时间计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!