pygame 中(左)鼠标按钮按下时如何检查鼠标移动(和方向)?

how to check mousemotion (and direction) while (left) mouse button is down in pygame?

我正在尝试检查鼠标左键按下时鼠标是否移动,然后 return 方向。我尝试在 'while True' 循环中两次检查鼠标位置,但这不起作用。这是我的代码:

import pygame
from pygame import*

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            try:
                X, Y = pygame.mouse.get_pos()
                print(X,Y)  #just a check
                pygame.time.wait(20)
                try:
                    x, y = pygame.mouse.get_pos()
                    print(x,y)  #just a check
                    if x-X != 0 or y-Y != 0:
                        print('moved')
                        print(x-X, y-Y)

                    elif x-X == 0 and y-Y == 0:
                        print('not moved')
                except AttributeError:
                    pass
            except AttributeError:
                pass

但它始终return没有动过。我做错了什么?

你需要反其道而行之,检查运动,然后按下按钮:

if event.type == pygame.MOUSEMOTION and event.buttons[0]:

鼠标指示方向。

#!/usr/bin/env python3
import pygame

pygame.init()
width, height = 640, 480
display = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

PRINT_MOUSE=True
USE_MOTION=True

mouse_pos=[(1,1),(2,2)]
#mouse meter
matrix = [
    [0,0,0],
    [0,0,0],
    [0,0,0]
]
def mdir(mouse_pos):
    global matrix
    #x+y
    if(mouse_pos[0][0] > mouse_pos[1][0]): #x right
        matrix[1][0]+=1
    if(mouse_pos[0][1] > mouse_pos[1][1]): #y down
        matrix[0][1]+=1
    if(mouse_pos[0][0] < mouse_pos[1][0]): #x left
        matrix[1][2]+=1
    if(mouse_pos[0][1] < mouse_pos[1][1]): #y up
        matrix[2][1]+=1
    #corners
    if(matrix[1][2] > 0 and matrix[2][1] > 0): #right down
        matrix[2][2]+=1
    if(matrix[1][2] > 0 and matrix[0][1] > 0): #right up
        matrix[0][2]+=1
    if(matrix[1][0] > 0 and matrix[2][1] > 0): #left down
        matrix[2][0]+=1
    if(matrix[1][0] > 0 and matrix[0][1] > 0): #left up
        matrix[0][0]+=1
    if(PRINT_MOUSE):    
        print(matrix[0])
        print(matrix[1])
        print(matrix[2])
        print("")
    reset_mouse()

def reset_mouse():
    #reset mouse meter
    global matrix
    matrix = [
        [0,0,0],
        [0,0,0],
        [0,0,0]
    ]

while True:
    
    pos=pygame.mouse.get_pos()
    if(len(mouse_pos) >= 3):
        mouse_pos.pop(0)
    else:
        mouse_pos.append(pos)
    if not USE_MOTION:    
        mdir(mouse_pos)
    
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit() 
            exit(0)
        if(USE_MOTION):
            if event.type == pygame.MOUSEMOTION:
                mdir(mouse_pos)        
    clock.tick(60)