[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Question about mouse motion
Julien Peeters wrote:
I wonder what is the best way to implement this algorithm:
        
        while true:
                if mouse click:
                        return get rect which mouse is on
                        
Thanks for your answers.
I do something like this:
-Create a "widget_panel" that contains buttons etc., each with a rect 
defining its borders.
-Start an input loop handling different kinds of events.
-In the loop, include:
            ## Mouse events
            elif event.type == MOUSEBUTTONDOWN:
                handled = widget_panel.HandleMouseClick(event.pos)
                if not handled:
                    print "Clicked somewhere other than on a widget."
The HandleMouseClick function returns True for "handled" if it detects 
that the click was in one of its widgets -- in which case it tells the 
widget it was clicked. "event.pos" is part of the Pygame event data, 
which you get from "for event in pygame.event.get():".
In the function below, each widget ("foo") has coordinates x1,y1,x2,y2 
rather than a Pygame rect; eh, sloppy, but you can convert easily, 
probably with the function "Rect.collidepoint(x, y) -> bool".
    def HandleMouseClick(self,pos=(0,0)):
        """Inform any button at these coords that it was clicked."""
        clicked_on_something = False
        x, y = pos
        for foo in self.widgets:
            if (foo.x1 <= x) & (foo.x2 >= x):
                if (foo.y1 <= y) & (foo.y2 >= y):
                    ## This button was clicked.
                    if hasattr(foo,"Click"):
                        foo.Click()
                    clicked_on_something = True
        return clicked_on_something
Hope this is useful.
Kris