Lab Dates: Wednesday-Thursday, 6-7 March 2013

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.

Interactive Graphics

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:

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 Labs in Blackboard and click on the link: Lab 4. Take the 5 question test about the lab. Remember to click the Submit button before closing the lab exercise. You may take the test as many times as you want until you get a perfect score.