A simple turtle in generativepy
This section is now obsolete, as generativepy now contains a turtle implementation. Please refer to that.
In this post we will create a simple turtle graphics in generativepy, and use it to recursively plot a Koch curve.
The turtle will be useful for exploring L Systems.
Turtle graphics
You will probably be familiar with turtle graphics. The idea is that you have a graphics cursor that can draw lines as it moves around.
The cursor has an (x, y) position, and also a direction it is pointing in (the heading). The you can tell the turtle to move forward by a certain distance, or to turn through a certain angle to the left or right. By issuing a series of instructions, you can draw various shapes.
To allow for recursive drawing (to create fractal images) turtle graphics can push the current state onto a stack. At some later stage it can pop its previous state (position and heading) and continue from there.
generativepy implementation
Here is the Python code to implement a simple turtle:
import math
from generativepy.geometry import Line
from generativepy.color import Color
import math
class Turtle():
def __init__(self, ctx):
self.ctx = ctx
self.heading = 0
self.x = 0
self.y = 0
self.stack = []
def push(self):
state = self.heading, self.x, self.y
self.stack.append(state)
def pop(self):
state = self.stack.pop()
self.heading, self.x, self.y = state
def forward(self, distance):
p1 = self.x, self.y
self.x += distance*math.cos(self.heading)
self.y += distance*math.sin(self.heading)
Line(self.ctx).of_start_end(p1, (self.x, self.y))\
.stroke(Color('darkblue'), 1)
def move(self, distance):
self.x += distance*math.cos(self.heading)
self.y += distance*math.sin(self.heading)
def move_to(self, x, y):
self.x = x
self.y = y
def left(self, angle):
self.heading -= angle
def right(self, angle):
self.heading += angle
This class uses self.x
and self.y
to store the position, and self.heading
to store the current direction. It draws on a generativepy drawing.Canvas
object.
push
andpop
save and restore the current state (x
,y
andheading
) as a tuple, using a list as a stack.forward
moves forward a certain distance, drawing a line on the canvas.move
is similar toforward
but moves without leaving a line.moveTo
moves straight to a new (x, y) position without drawing anything.left
andright
move the turtle direction throughangle
, to the k=left or right.
The turtle will draw lines using the stroke colour and weight that is defined when the turtle functions are called.
Drawing a simple figure
Here is some code that draws a simple figure using the turtle (assuming we have a suitable canvas object):
turtle.forward(10)
turtle.left(math.pi/2)
turtle.forward(10)
turtle.right(math.pi/2)
turtle.forward(10)
turtle.right(math.pi/2)
turtle.forward(10)
turtle.left(math.pi/2)
turtle.forward(10)
This sequence (forward, left, forward, right, forward, right, forward, left, forward ) will draw a shape something like this:
Making the figure recursive
We can draw this figure recursively using the following code:
def plot(turtle, level):
if level < 1:
turtle.forward(10)
else:
plot(turtle, level-1)
turtle.left(math.pi/2)
plot(turtle, level-1)
turtle.right(math.pi/2)
plot(turtle, level-1)
turtle.right(math.pi/2)
plot(turtle, level-1)
turtle.left(math.pi/2)
plot(turtle, level-1)
Calling the function with level set to 0
If we call this function with level
set to 0, the if statement will be true and the function will just call turtle.forward
, which just draws a single line.
Calling the function with level set to 1
If we call the function with level set to 1, the second part of the if statement will execute. This executes the following steps:
- calls
plot
recursively withlevel
set to 0 - draws a single line - turn left
- calls
plot
recursively withlevel
set to 0 - draws a single line - turn right
- etc
These steps are identical to the original code. This will draw the same figure as before:
Calling the function with level set to 2
If we call the function with level set to 2, things get more interesting. The second part of the if statement will execute. This executes the following steps:
- calls
plot
recursively withlevel
set to 1 - draws the original figure - turn left
- calls
plot
recursively withlevel
set to 1 - draws the original figure rotated to the left - turn right
- calls
plot
recursively withlevel
set to 1 - draws the original figure back at the original orientation - turn right
- calls
plot
recursively withlevel
set to 1 - draws the original figure rotated to the right - turn left
- calls
plot
recursively withlevel
set to 1 - draws the original figure back at the original orientation
The result is shown below, with the original figure shown in a different colour for each iteration:
The full code
Here is the full code that you can run for yourself. You will also need the turtle code from earlier in this post, which you should save in a file called turtle.py in the same folder.
from generativepy.drawing import make_image, setup
from generativepy.color import Color
from turtle import Turtle
import math
def plot(turtle, level):
if level < 1:
turtle.forward(10)
else:
plot(turtle, level-1)
turtle.left(math.pi/2)
plot(turtle, level-1)
turtle.right(math.pi/2)
plot(turtle, level-1)
turtle.right(math.pi/2)
plot(turtle, level-1)
turtle.left(math.pi/2)
plot(turtle, level-1)
def draw(ctx, width, height, frame_no, frame_count):
setup(ctx, width, height, background=Color(1))
turtle = Turtle(ctx)
turtle.move_to(10, 290)
plot(turtle, 3)
make_image("turtle-koch-curve.png", draw, 800, 300)
You should be able to run this yourself if you have generativepy installed. Here is the output you will get:
Iteration level 1
Iteration level 2
Iteration level 3
Iteration level 4
Note that when the level is set to 4, the image is too big to fit the image size we are using. You can either increase the image size, or make the image smaller, or even try a combination of both.
In this case we have made the image smaller by setting the forward
distance to to 4 rather than 10 (the turtle.forward(10)
line in the plot
function).
Conclusion
We have defined a simple turtle system, and used it to draw a Koch curve in generativepy. You can use this to try drawing other fractals such as the Sierpinski triangle. See the article on L Systems for a way to make this easier.
See also
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added:
Popular tags
2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest