Lab Dates: Wednesday-Thursday, 19-20 September 2012
Since we missed lecture this week due to the holiday, today's lab will start with a quick lecture on graphics. We will then focus on the interactive graphics sections of Chapter 4.
We will use the graphics package developed for the book. If you have not already downloaded the graphics.py, work through the directions in Lab 3.
The first program for today is click.py from the book (downloadable from the book's website). Try running the program (remember you need to have the graphics.py file in the same directory. What does it do? Let's look at the program:
# click.py from graphics import *
def main(): win = GraphWin("Click Me!")
for i in range(10): p = win.getMouse() print("You clicked at:", p.getX(), p.getY()) main()
Let's modify this program in several ways:
This last one is more challenging. To draw a line you will need to remember the point from the click before. Lets make a new variable called oldPoint to save the point and use it in the loop body to draw a line:
p = win.getMouse() print("You clicked at:", p.getX(), p.getY()) Line(oldPoint,p).draw(win) oldPoint = p
If your loop body to this, you will get an error. What is it? What is missing? Remember you cannot use a variable until it has a value. So, before your loop, lets give oldPoint a value:
oldPoint = Point(0,0) for i in range(10): ...
Now what happens when you run it? Where does your line start? Try it several times. Does it always start in the same place? To have it start where the user first clicked, we need to get that value before we draw the line. Here is one way to do this:
def main(): win = GraphWin("Click Me!") oldPoint = win.getMouse() oldPoint.draw(win) for i in range(20): p = win.getMouse() print("You clicked at:", p.getX(), p.getY()) Line(oldPoint,p).draw(win) oldPoint = p p.draw(win)
After completing your program, go to Assignments in Blackboard and click on the link: Lab 4. Use the file upload interface to upload your program. Remember to click the Submit button before closing the lab exercise.
With the remaining time, you can work on Problem Set 3.