Reading mouse buttons¶
Information about the currently pressed mouse buttons is provided by the pg.mouse.get_pressed()
function. This function returns a tuple of three elements (an ordered triple), which are used as logical values. The tuple elements correspond to the left, middle and right mouse buttons respectively. A value of True indicates that a button is currently pressed, and False that it is not.
The example below shows how to read which mouse buttons are pressed. This is the part of the program where that happens:
The pressed_mouse_button tuple gets three values returned by the pg.mouse.get_pressed() function. We then typically use these values in if statements. For example, if pressed_mouse_button[2] means “if right button is pressed” (0 for left, 1 for middle, and 2 for right).
Examples and tasks¶
Example - put the ball into the box:
While the left mouse button is held pressed, the ball moves away from the cursor. The goal is to put the ball into the red box by moving the mouse and pressing the left button. Pressing the right button returns the game to the beginning.
First, study the new_frame() function carefully, and then have a look at the other parts of the code as well. Try the program out and see if it works as you expected after reading the description.
Task - to and from the mouse:
Complete the program so that it works as shown in the example (“Play task” button).
When the left mouse button is pressed, the ball should move away from the mouse, as in the “put the ball into the box” example above, but not by half distance, but only by a tenth of the distance to the mouse.
When the left mouse button is not pressed, the ball should move closer by one tenth of the distance to the mouse (as in the “towards mouse” task in the previous lesson).
Task - laser:
Complete the program so that it works as shown in the example (“Play task” button).
While the left mouse button is held pressed, the “laser” is on, otherwise it is off. While the laser is on, its energy decreases by 1 (but not below 0), and when it’s off the energy increases by 2 (but not over 100).