Square Spiral

By Monty, 18th April 2015

SpiralSquareThis is a very simple introduction to Turtle graphics. The turtle starts in the middle of the window, moves forward a small distance, turns right, moves forward a slightly longer distance, right again, even further this time… until the distance equals or exceeds a given limit.

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.

# Spiral outwards in an ever-expanding square
#   using Turtle graphics
#   https://docs.python.org/3/library/turtle.html
#   Authour:    Alan Richmond, Python3.codes

from turtle import *

lineLen = inc = 20      # Line starts this long, grows this much
max = 800               # until it's this long
turn = 90               # try different numbers, e.g. 120

#   The line grows longer until it fills the window
while lineLen < max:
    #   https://docs.python.org/3/library/turtle.html#turtle.forward
    forward(lineLen)
    #   https://docs.python.org/3/library/turtle.html#turtle.right
    right (turn)
    lineLen += inc

#   https://docs.python.org/3/library/turtle.html#turtle.done
done()
Wikipedia:

Overview

A spiral drawn with an iterative turtle graphics algorithm

The turtle has three attributes: a location, an orientation (or direction), and a pen. The pen, too, has attributes: color, width, and on/off state.

The turtle moves with commands that are relative to its own position, such as "move forward 10 spaces" and "turn left 90 degrees". The pen carried by the turtle can also be controlled, by enabling it, setting its color, or setting its width. A student could understand (and predict and reason about) the turtle's motion by imagining what they would do if they were the turtle. Seymour Papert called this "body syntonic" reasoning.

A full turtle graphics system requires control flow, procedures, and recursion: many turtle drawing programs fall short. From these building blocks one can build more complex shapes like squares, triangles, circles and other composite figures. The idea of turtle graphics, for example is useful in a Lindenmayer system for generating fractals.

Turtle geometry is also sometimes used in graphics environments as an alternative to a strictly coordinate-addressed graphics system.

What do you think?

Leave a Reply

%d bloggers like this: