如何使用PySDL2获取鼠标位置?

Jon*_*ine 2 python sdl pysdl2

完全不明白除了监听事件之外如何实现获取鼠标位置,但是在事件队列为空的情况下,这是如何实现的呢?

pygamers的 pysdl 文档建议使用sdl2.mouse.SDL_GetMouseState()doc here),但此函数实际上需要您想要询问的光标的 x,y 坐标。同时,调用sdl2.mouse.SDL_GetCursor()返回一个光标对象,但我找不到方法从中获取它的坐标(即它只是包装一个 C 对象,因此它有一个空.__dict__属性)。

我一直在尝试我能想到的一切,但我以前从未用C 编程过。我试图生成的简单包装函数只是:

def mouse_pos(self):
            #  ideally, just return <some.path.to.mouse_x_y> 
            event_queue = sdl2.SDL_PumpEvents()
            state = sdl2.mouse.SDL_GetMouseState(None, None)  # just returns 0, so I tried the next few lines
            print state
            for event in event_queue:
                if event.type == sdl2.SDL_MOUSEMOTION:
            #  this works, except if the mouse hasn't moved yet, in which case it's none        
            return [event.x, event.y] 
Run Code Online (Sandbox Code Playgroud)

小智 5

SDL_GetMouseState()是 SDL2 C 函数的包装器。因此,您必须使用 ctypes 从中检索值。原始的SDL2函数接收两个指针(x和y)来存储光标位置。

下面的代码片段将为您做正确的事情:

import ctypes
...
x, y = ctypes.c_int(0), ctypes.c_int(0) # Create two ctypes values
# Pass x and y as references (pointers) to SDL_GetMouseState()
buttonstate = sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y))
# Print x and y as "native" ctypes values
print(x, y)
# Print x and y as Python values
print(x.value, y.value)
Run Code Online (Sandbox Code Playgroud)

`