Mouse Input
- Graphics module has functions for getting mouse and keyboard input
The ‘wait’ function are blocking functions, the program stops running until user input
gaphics.wait_for_button_press() graphics.draw_oval(0, 0, 100, 100, fill="black")
Can also get the current mouse state
graphics.mouse_x() graphics.mouse_y()
But this isn’t useful unless repeatedly checking the value inside of a loop
for i in range(100): x = graphics.mouse_x() y = graphics.mouse_y() graphics.clear() graphics.draw_oval(x, y, 100, 100, fill="black") graphics.wait()
This runs a fixed number of frames, it would be better to run as long as the user wants
while graphics.window_open(): x = graphics.mouse_x() y = graphics.mouse_y() graphics.clear() graphics.draw_oval(x, y, 100, 100, fill="black") graphics.wait()
Can also get the button state
x = 0 y = 0 while graphics.window_open(): if graphics.button_down(1): x = graphics.mouse_x() y = graphics.mouse_y() graphics.clear() graphics.draw_oval(x, y, 100, 100, fill="black") graphics.wait()
The 1 argument to the button_down function tests if the left mouse button is down
Keyboard Input
- Like mouse input, there are blocking and non-blocking keyboard input functions
The blocking functions stop the program until the user presses or releases a key
graphics.wait_for_key_press() graphics.draw_oval(0, 0, 100, 100, fill="black")
To get keyboard input in a program that uses a loop to create animations, use the non-blocking functions
while graphics.window_open(): graphics.clear() if graphics.key_down('space'): graphics.draw_oval(x, y, 100, 100, fill="black") graphics.wait()
Image Velocity
- To create images that can change direction, need to store the direction the image is moving in variables
- This is the velocity of the image, the number of pixels it moves in the x and y direction each frame of animation
The oval in the following example moves 2 pixels right and 1 pixel down every frame of animation
x = 0 y = 0 x_velocity = 2 y_velocity = 1 while graphics.window_open(): x = graphics.mouse_x() y = graphics.mouse_y() graphics.clear() graphics.draw_oval(x, y, 100, 100, fill="black") graphics.wait()
- Change
x_velocity
andy_velocity
to change the direction and speed of the circle Can get the circle to ‘bounce’ off of the edges of the window by computing new velocity when it hits an edge