# Code for Midterm Exam 2, Summer 2009, CS8, P. Conrad, UCSB CS Dept. import cTurtle import math # # # # Here are two functions that will compute the x value (or y value) of the point number i of n points distributed evenly around a circle of radius r, centered at 0,0, with the first point being at 0 degrees on the standard "unit circle" # # # # # # # # function ithOfNPointsOnCircleX (or ithOfNPointsOnCircleY) contract: (int,int,float) => float consumes: i: the point number (between 0 and n-1) n: the number of points r: the radius of the circle (assumed to be centered at 0,0) produces: the x value (or y value) of that point in the cartesian plane def ithOfNPointsOnCircleX(i,n,r): return r * math.cos((i/n)*(2*math.pi)) def ithOfNPointsOnCircleY(i,n,r): return r * math.sin((i/n)*(2*math.pi)) # # # # # # # # # # # # drawPolygon (turtle, float, int) => void consumes: t: a turtle we'll use to draw the polygon r: the radius of the polygon n: the number of sides the polygon has produces: nothing side-effect: the turtle draws a polygon of n sides, centered at 0,0 the size of the polygon is determined by r---it is the right size that it could be inscribed in a circle of radius r the turtle is left at position 0,0, facing right the old position and direction of the turtle is lost. def drawPolygon(t,r,n): # pick up the pen, move to the starting point, and put down the pen t.up(); t.goto(r,0); t.down() # connect the dots for all the points for i in range(1,n): # gives points 1 thorugh n-1 t.goto( ithOfNPointsOnCircleX(i,n,r), ithOfNPointsOnCircleY(i,n,r) ) # That drew almost all the way around---for example, it drew # three sides if we are drawing a square. To finish, we need to # return to the starting point t.goto(r,0); t.up() # # # # # # # # # # # # # # drawStar (turtle, float, int) => void consumes: t: a turtle (that was already constructed) we'll use to draw the polygon r: the radius of the polygon n: the number of points the star has (must be >= 5) produces: nothing side-effect: if n < 5, the function returns without doing anything else: the turtle draws a star of n points, centered at 0,0 the size of the star is determined by r---it is the right size that it could be inscribed in a circle of radius r The star is drawn by connecting each point to a point that is two points away (i.e. we skip one point) def drawStar(t,r,n): # if n < 5, we can't really draw a star, so just return if n<5: return # Doesn't return anything. It just ends the function call # pick up the pen t.up(); # connect the dots for all the points for i in range(n): # gives points 0 through n-1 # pen is up---we move to this point t.goto( ithOfNPointsOnCircleX(i,n,r), ithOfNPointsOnCircleY(i,n,r) ) # put the pen down t.down() # now draw a line to the point two points away from this one t.goto( ithOfNPointsOnCircleX(i+2,n,r), ithOfNPointsOnCircleY(i+2,n,r) ) # lift the pen back up t.up()