CPSC150A
Scientific Computing

Activity 5

Functions

Triangle

Create the function draw_triangle(pen) that uses turtle graphics to draw a triangle. The parameter pen is a turtle object to use to draw the triangle. The triangle can be any orientation and can be any size.

Example

myrtle = turtle.Turtle()
draw_triangle(myrtle)
turtle.up()
turtle.forward(50)
turtle.down()
draw_triangle(myrtle)

Circle

Create the function draw_circle(pen, x_loc, y_loc, radius) that uses turtle graphics to draw a circle. The parameter pen is a turtle object which you can use to draw the circle. The parameters x_loc and y_loc are the center of the circle. The parameter radius is the radius of the circle. Note that the function should work no matter the turtle’s location and heading when the function is called. Do not use the tutle circle function. Instead, draw a regular polygon with many sides.

Example Output

myrtle = turtle.Turtle()
num_circles = 3
size = 50
y = 0
for i in range(num_circles):
    x = size * i
    draw_circle(myrtle, x, y, size)

draw_circle.png

Fun Output

myrtle = turtle.Turtle()
num_circles = 100
size = 100
RADIANS_IN_CIRCLE = 2.0 * math.pi
for i in range(num_circles + 1):
    x = size * math.cos((i / num_circles) * RADIANS_IN_CIRCLE)
    y = size * math.sin((i / num_circles)* RADIANS_IN_CIRCLE) - (size * 2.0)
    draw_circle(myrtle, x, y, size)

Fill Square

Another benefit of functions is to save on repeated code. There are some things we do A LOT in our programs, and many things that we do across many programs. One of these is drawing a filled square, which you will implement today.

Details

Download and open the Python program called checkerboard.py. In this file, there is an empty function definition fill_square(pen, color, x_loc, y_loc, size). This function has the parameters pen, a turtle object, color, a string representing a turtle color, x_loc and y_loc, integers representing a location on the turtle window, and size, an integer > 0 which is the size of one of the sides of the square. Your function should draw a filled square of the correct dimensions centered at the point (x_loc, y_loc).

Run your program and make sure you get the correct output.

Example

chekcerboard.png

Hint

  • The (x_loc, y_loc) parameters to the function specify the center of the square. You need to shift the position of the turtle by half of the size in both the x and y directions to center the square drawn.

  • Drawing the square is pretty easy, you just need to go forward and turn right 4 total times.

  • Make sure you use the color, begin_fill and end_fill functions for setting the turtles color, as well as causing the shape to get filled in with color afterwards.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect functionality will be accepted as complete.