Friday, August 26, 2016

Square spiral - drawing with 3D effect (turtle graphics)

By Vasudev Ram

I was doing some work with Python turtle graphics for a project, and came up with this simple program that draws a square-ish spiral in multiple colors. It has a bit of a 3D effect. You can see it as a pyramid with you above, the levels ascending toward you, or you can see it (again from above) as a well with steps, going downward.

Here is the code and a screenshot of its output:
'''
square_spiral.py
A program that draws a "square spiral".
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''

import turtle
t = turtle

colors = ['blue', 'green', 'yellow', 'orange', 'red']

def pause():
    _ = raw_input("Press Enter to exit:")

def spiral(t, step, step_incr, angle):
    color_ind = 0
    colors_len = len(colors)
    t.pencolor(colors[color_ind])
    while True:
        t.forward(step)
        step = step + step_incr
        if step > 500:
            break
        t.right(angle)
        color_ind = (color_ind + 1) % colors_len
        t.pencolor(colors[color_ind])

    t.hideturtle()
    pause()

t.speed(0)
spiral(t, 20, 5, 90.2)


- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



No comments: