Smith College Computer Science 111 - Lab8. Fall Semester, 2006
The purpose of today's lab is to use graphics and become acquainted with object-oriented programming. You will implement the logo programming environment. First you'll work on the graphics part. Refer to ch5 of your textbooks. Section 5.8 of the textbook has a nice summary of the graphics objects.Part 1. Boot into Linux
from graphics import *When we use the from graphics import * statement, we can use graphics functions and objects without putting graphics. in front of each one.
maxPix = 400
# Create a graphics window
win = GraphWin("Avatars", maxPix, maxPix)
win.setBackground("white")
win.setCoords(0,0,maxPix,maxPix) # now 0,0 is in lower left corner
home = Point(50,50) # set the home point
angle = 0 # heading angle is initialized to 0
filename = "franklinTurtleSmall.gif"
turtle = Image(home, filename)
turtle.draw(win)
These are the statements that create a GraphWin object, set the
coordinates, initialize variables, etc., and draw the turtle.
getcopy graphics.py getcopy franklinTurtleSmall.gifbefore you can use it. Exit from emacs and invoke the python interpreter, import Lab5 and run main(). Do you see a window with Franklin the Turtle drawn in it? If not, fix it before going to the next part.
Part 2. do some more graphics
angRad = (2.0*math.pi)*angle/360.0Do you remember that we went over this in class? To use the cos and sin functions, place
import mathat the top of your program and then after computing the angle in radians, insert these two lines:
dx = num * math.cos(angRad) dy = num * math.sin(angRad)Finally, add a statement to move the turtle to the new location:
turtle.move(dx,dy)To test this part, add a temporary statement to the top of the program that lets the user type in a value for num and for angle (both should be integers). Run this program and see if the turtle moves where it should.
pd = True
And if the command is pu, you will have one statement:
pd = False
location = turtle.getAnchor()
If pd is True, the program should create a line when the turtle moves forward.
The Line class
expects two Point objects, the beginning and end points.
The beginning point is location (where the turtle is now)
and the endpoint is
calculated in this way:
newX = location.getX() + dx
newY = location.getY() + dy
endlocation = Point(newX,newY)
In other words, we get the x coordinate of the
beginning point (where the turtle is) and add dx, and we get
the y coordinate of the beginning point and add dy.
We make a new Point out of the new coordinates and
assign it to endlocation.
if pd==True:
l = Line(location, endlocation)
l.draw(win)
turtle.move(dx,dy)
else:
turtle.move(dx,dy)
Type this all in and try it with both values of pd.pd = True fd 150 angle = angle + 90 fd 150 angle = angle + 90 fd 150 angle = angle + 90 fd 150This should cause the turtle to draw a square.