Interaction with the mouse and keyboard in Processing Python Mode
the examples in this lesson are written for Processing Python Mode. If you work in the recommended environment Thonny + py5, most of the code stays the same, and names with a capital letter in the middle are written in lower case with an underscore:
mouseX → mouse_x, noStroke() → no_stroke(). See the table of differences.Why is interaction important?
So far we have drawn and animated objects. Now we learn how to react to:
- the position of the mouse
- a mouse click
- pressing a key
This is the basis for making games and interactive projects.
The position of the mouse — mouseX and mouseY
def setup():
size(600, 400)
def draw():
background(240)
ellipse(mouseX, mouseY, 40, 40)
mouseX and mouseY are built-in variables that track the position of the cursor.
Detecting a click — mousePressed
def setup():
size(600, 400)
def draw():
background(240)
if mousePressed:
fill(255, 0, 0)
else:
fill(0, 150, 255)
ellipse(300, 200, 120, 120)
mousePressed is a logical variable (True/False).
The mousePressed() function
We can define a special function that is called when the user clicks:
def mousePressed():
print("Click at position:", mouseX, mouseY)
mousePressed→ a state (whether the button is pressed)mousePressed()→ an event (a click has happened)
Example: a click adds a circle
circles = []
def setup():
size(600, 400)
def draw():
background(240)
for c in circles:
ellipse(c[0], c[1], 30, 30)
def mousePressed():
circles.append((mouseX, mouseY))
Interaction with the keyboard — key and keyPressed()
x = 300
def setup():
size(600, 400)
def draw():
global x
background(240)
ellipse(x, 200, 50, 50)
def keyPressed():
global x
if key == 'a':
x -= 10
if key == 'd':
x += 10
We use:
key— which key was pressedkeyPressed()— the function that is triggered
keyCodeAdvanced: holding a key down
def draw():
global x
background(240)
if keyPressed:
if key == 'a':
x -= 3
if key == 'd':
x += 3
ellipse(x, 200, 50, 50)
Here the object moves while we hold the key down.
Mini project: an interactive scene
- a ball follows the mouse
- a click changes the colour
- the keys move another object
Mini project (more advanced): a click changes the direction
dx = 2
def mousePressed():
global dx
dx *= -1 # changes the direction of movement
A click can change how an object behaves — this is the basis for games.
Comparison with the Java version
The same principles apply in Java Processing:
Processing with Java — interaction
Next lesson
Simple physics: gravity and bouncing →
Related topics
- Mini project: the basics of the Pong game
- Animation and variables
- Shapes and colours
- Processing with Java
Check your knowledge
Open the quiz
Mini quiz: the mouse and the keyboard
1. Which variable gives the x position of the mouse in Python Mode?
2. When is the function mousePressed() called?
