Handling Mouse Input


Although you've seen a lot of what the livewires package has to offer, you haven't seen the main ingredient of interactivity: user input. One of the most common ways to get input from a user is through the mouse. livewires offers a simple Screen method to do just that.

Introducing the Moving Pan Program

The Screen class has a method that makes reading the mouse position on the graphics screen a piece of cake. With this method, I create the Moving Pan program that allows a user to drag a pan sprite across the screen as he or she moves the mouse. The results of the program are displayed in Figure 11.13.

click to expand
Figure 11.13: The pan sprite follows the mouse around the graphics screen.

Setting Up the Program

The following code should look familiar:

 # Moving Pan # Demonstrates mouse input # Michael Dawson 5/11/03 from livewires import games SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 

As before, I import games and establish global constants for the screen's width and height.

Creating the Pan Class

Next, I create Pan for the pan sprite:

 class Pan(games.Sprite):     """ A pan. Controlled by the mouse. """     def __init__(self, screen, x, y, image):         """ Initialize pan object. """         self.init_sprite(screen = screen, x = x, y = y, image = image)     def moved(self):         """" Move pan to mouse position. """         x, y = self.screen.mouse_pos()         self.move_to(x,y) 

Notice that I omit dx and dy when I invoke the object's init_sprite() method. Since the pan sprite won't have any sort of velocity, I'll let the two attributes each get their default value of 0.

In the moved() method, I invoke the Screen object's mouse_pos() method. The method returns the x- and y-coordinates of the mouse pointer on the graphics screen, which I assign to x and y. Then, I invoke the Pan object's move_to() method with x and y as arguments, which moves the pan to the location of the mouse pointer.

Writing the Main Program

The rest of the program is the familiar main section:

 # main my_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) wall_image = games.load_image("wall.jpg", transparent = False) my_screen.set_background(wall_image) pan_image = games.load_image("pan.bmp") Pan(screen = my_screen,     x = SCREEN_WIDTH/2, y = SCREEN_HEIGHT/2,     image = pan_image) my_screen.mouse_visible(False) my_screen.mainloop() 

Setting up the screen and loading the brick wall background is exactly as before. Next, I load a pan image and create the Pan object. Then I invoke the Screen method mouse_visible() and set the mouse pointer to invisible. As always, I kick everything off by invoking the Screen object's mainloop() method.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net