我想计算 Pygame 中用户鼠标事件的时间,如果用户在大约 15 秒内没有移动鼠标,那么我想在屏幕上显示文本。我为此尝试了 time
模块,但它不起作用。
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()
输出不是我想要的,如果用户不移动他的鼠标,我不知道如何计算它。
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,则打印文本。
Edit: 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 秒,则在屏幕上显示文本:
#!/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 鼠标事件中的 Python 时间计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852757/