Section #5 Solutions


Written by Nick Parlante and Elyse Cornwall

                
def draw_v(canvas, left, top, width, height):
    """
    Given a canvas and left,right and width,height.
    Draw the "v" figure with that location and size.
    """
    # Draw outer rectangle
    canvas.draw_rect(left, top, width, height, color='blue')

    # Mid is halfway across, 1/3 way down
    mid_x = left + 0.5 * (width - 1)
    mid_y = top + (1 / 3) * (height - 1)
    # Draw lines from upper-left to mid, mid to upper-right
    canvas.draw_line(left, top, mid_x, mid_y, color='red')
    canvas.draw_line(mid_x, mid_y, left + width - 1, top, color='red')


def draw_horn(canvas, left, top, width, height, n):
    """
    Given a canvas and left,right and width,height
    and n. Draw the horn figure with that location 
    and size, with n lines.
    """
    # Draw outer rectangle
    canvas.draw_rect(left, top, width, height, color='blue')

    # Mid is 1/3 across, half way down
    start_x = left + (1 / 3) * (width - 1)
    start_y = top + 0.5 * (height - 1)

    for i in range(n):
        y_add = (i / (n - 1)) * (height - 1)
        canvas.draw_line(start_x, start_y, left + width - 1, top + y_add, color='green')


def draw_diagonal(width, height, n):
    """
    Creates a canvas of the given size.
    Draw the diagonal figure of n horn figures.
    """
    canvas = DrawCanvas(width, height, title='Diagonal')

    # How big will each patch be
    patch_width = width / n
    patch_height = height / n

    for i in range(n):
        left = i * patch_width
        top = i * patch_height
        draw_horn(canvas, left, top, patch_width, patch_height, n)

# BONUS
def draw_diagonal(width, height, n):
    """
    Creates a canvas of the given size.
    Draw the diagonal figure of n
    alternating "v" and horn figures.
    """
    canvas = DrawCanvas(width, height, title='Diagonal')

    # How big will each patch be
    patch_width = width / n
    patch_height = height / n

    for i in range(n):
        left = i * patch_width
        top = i * patch_height
        if i % 2 == 0:
            draw_v(canvas, left, top, patch_width, patch_height)
        else:
            draw_horn(canvas, left, top, patch_width, patch_height, n)