def funcName( arg1, arg2, arg3 ): # Header statement1 # Body statement2 statement3
# Draw an eyeball at position x, y def eyeball(x, y): stroke(0) fill(255) ellipse(x, y, 50, 40) # Sclera fill(0, 255, 0) ellipse(x, y, 25, 25) # Iris fill(0) ellipse(x, y, 10, 10) # Pupil
from Processing import * window(350, 300) # Draw an eyeball at position x, y def eyeball(x, y): stroke(0) fill(255) ellipse(x, y, 50, 40) # Sclera fill(0, 255, 0) ellipse(x, y, 25, 25) # Iris fill(0) ellipse(x, y, 10, 10) # Pupil eyeball(100, 100) eyeball(250, 100)
Note:
|
![]() |
def square(x): y = x * x return y toSquare = 10 result = square(toSquare) print("The result of ", toSquare, " squared is ", result)See ch04_square How to Think Like a Computer Scientist
If a function has no return statement, it returns None when complete
What does eyeball() return?
rv = eyeball(100, 100)
print( rv ) # rv has the value None
onMousePressed | : raised when the mouse goes down |
onMouseReleased | : raised when the mouse is released |
onMouseMoved | : raise when the mouse is moved |
onMouseClicked | : raised when the is pressed and released in the same location |
onMouseDragged | : raised when the mouse is pressed and moved |
onKeyPressed | : raised when a key is pressed |
onKeyReleased | : rasied when a key is released |
onLoop | : raised on a predetermined time interval |
def myFunction(o, e):
pass # pass by, do nothing
onMousePressed += myFunction
onMousePressed -= myFunction
Functions that handle events must take two arguments: object (o), and eventData (e)
# clickEllipse.py from Processing import * window(300, 300) # Draw a randomly colored ellipse # at the current mouse location def draw(o, e): fill(random(255), random(255), random(255)) ellipse(mouseX(), mouseY(), 30, 30) # Hook draw function to the mousepressed event onMousePressed += draw
Use pmouseX() and pmouseY() to build a drawing program
# draw.py - A simple drawing program from Processing import * window(500, 500) # Draw lines from previous to current mouse def doDragged(o, e): x1 = pmouseX() y1 = pmouseY() x2 = mouseX() y2 = mouseY() line(x1, y1, x2, y2) # Handle mouse dragged onMouseDragged += doDragged
# randomEllipse.py from Processing import * window(300, 300) # Draw ellipses on frame rate def draw(o, e): fill(random(255), random(255), random(255)) ellipse(mouseX(), mouseY(), 30, 30) frameRate(10) # Set loop rate to 10/second onLoop += draw # Handle the loop event loop() # Start looping
# lineRotate.py from Processing import * from math import * window(500, 500) # Globals and settings angle, dangle = 0.0, 0.01 strokeWeight(20) stroke(0, 255, 0) # Draw the line at the current angle def rotate(o, e): global angle background(255) x1 = cos(angle)*200+250 y1 = sin(angle)*200+250 x2 = cos(angle + PI)*200+250 y2 = sin(angle + PI)*200+250 line(x1, y1, x2, y2) angle = angle + dangle # Set up the loop frameRate(100) onLoop += rotate loop()
/
#