FrontEnd-Python
FrontEnd-Python

Reputation: 55

Handling None as position in pygame

The built in pygame function: pygame.mouse.get_pos() returns the X and Y coordinates in a tuple when I am moving the mouse, but if I stop moving the mouse, the function returns None.

But, I want the computer to keep returning the current coordinates over and over again.

How do I do that?

What I am trying to do is write a function that makes it easier to get the mouse coordinates.

I want to be able to do following:

Xpos, Ypos = mouse_pos()

What I have right now is:

def mouse_pos():
    for event in pygame.event.get():
        pos = pygame.mouse.get_pos()

    if pos != None:
        x=a[0]
        y=a[1]

        return x, y

    else:
#here I want code that says: if pos is NoneType, x=(latest x-value) and y=(latest y-value)

So, how can i get pygame to not return None (and return current coordinates) even if mouse is stationary?

Thanks in advance!

Upvotes: 0

Views: 180

Answers (2)

sloth
sloth

Reputation: 101052

Remove your function. Just use pygame.mouse.get_pos().

It's not pygame.mouse.get_pos() that returns None, it's your own function.

It will only set pos if there's an event in the event queue. If not, pos will be None.

But even worse is that every time you call your mouse_pos function, the event queue will be cleared. That will lead to events getting lost.

Upvotes: 2

Matan Shahar
Matan Shahar

Reputation: 3240

You are using the API wrong, the fact that there are events doesn't mean any of them is a mouse event, and pygame fills the mouse position on mouse events.

The function get_pos shouldn't be calle to find out where the mouse is but rather to update your knowledge when it is changed.

The correct way to keep track of mouse position will be to have the following in you main game loop:

mouse_position = (0, 0) # initial value

while game_is_running: # your main game loop
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            mouse_position = pygame.mouse.get_pos()

Upvotes: 2

Related Questions