solution_017a.py

#!/usr/bin/python3
# ==================================================================
# Draw a square spiral
# ==================================================================

import graphics as gr
import user_interface as ui
import coordinate_conversion as cc
import draw_axes as ax

window_width  = 801
window_height = 801

color = ['red','green','blue','black','purple']


# -------------------------------------------------------------------
# ---- draw line
# -------------------------------------------------------------------

def draw_line(win,x1,y1,x2,y2,color):

    wx1,wy1 = cc.center_to_win_coords(x1,y1,
              window_width,window_height)
    wx2,wy2 = cc.center_to_win_coords(x2,y2,
              window_width,window_height)

    l = gr.Line(gr.Point(wx1,wy1),gr.Point(wx2,wy2))

    l.setWidth(3)

    l.setFill(color)

    l.draw(win)

# -------------------------------------------------------------------
# ---- draw a square spiral 
# -------------------------------------------------------------------

def draw_a_square_sprial(win,x,y,l):

    c = 0                       # line color
    d = 0                       # draw direction

    # ---- draw the lines

    x1 = x                      # start of line x coord
    y1 = y                      # start of line y coord
    ll = 0                      # length of line

    for _ in range(16):

        if d == 0:

            ll += l

            x2 = x1             # end of line x coord
            y2 = ll + y1        # end of line Y coord
            draw_line(win,x1,y1,x2,y2,color[c])
            x1 = x2
            y1 = y2
            d  = 1

        elif d == 1:

            x2 = ll + x1
            y2 = y1
            draw_line(win,x1,y1,x2,y2,color[c])
            x1 = x2
            y1 = y2
            d  = 2

        elif d == 2:

            ll += l

            x2 = x1
            y2 = -(ll - y1)
            draw_line(win,x1,y1,x2,y2,color[c])
            x1 = x2
            y1 = y2
            d  = 3

        elif d == 3:

            x2 = -(ll - x1)
            y2 = y1 
            draw_line(win,x1,y1,x2,y2,color[c])
            x1 = x2
            y1 = y2
            d  = 0

        ##ui.pause()

        c += 1
        if not (c < len(color)):
            c = 0


# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

win = gr.GraphWin("Draw Square Spiral",window_width,window_height)
win.setBackground("white")

ax.draw_xy_axes(win,True)

draw_a_square_sprial(win,0,0,50)

ui.pause()

win.close()