Mechraf

Currently in /2019/02/23/animations/


Animations!

What’s more awesome than movies? It’s well known that movie is an acronym for MOVIng picturE. The concept of fast moving pictures is not new. Currently, some well known dedicated software is used for movie production. An example is. You can use Turtle Graphics to create animations, which are essentially moving pictures, therefore, movies.

Let’s Proceed

Our algorithm to create a basic animation goes like this.

  1. We draw a square on the screen.
  2. We move the turtle forward by a very small distance.
  3. The previous square is cleared and another, simultaneously drawn
  4. The three processes above are looped.

This shouldn’t be hard right?

The final script uses two screen functions:

  1. The tracer() function.
  2. The update() function

The tracer function is controls animation. It can be a substitute for the speed() function when a complex animation is to be drawn. It takes two arguments.

tracer(n = None, delay = None)
None is applied by python when no value is given

n is the number of times screen updates are performed. delay is the approximate time interval between two consecutive canvas updates. Setting the value of n to zero with no delay argument means the update() function would be used. The update function is used when the tracer() function is turned off. i.e when this code is written.

tracer(0)

As usual, we start by importing the turtle graphics module. Then define a drawSquare function. Then move the turtle to an initial position. Assign a count variable which would be useful in the while loop. Finally, we implement our algorithm.

from turtle import *

def drawSquare(side):
    for i in range(4):
        fd(side)
        lt(90)

pu(), goto(-300, 0), pd() #moving the pen to a starting position
ht(), width(5)

count = 40000

while count > 0:
    clear()
    drawSquare(100)
    fd(20)
    count -= 1    #decrement to avoid an infinite loop

Running this code reveals a procedural motion. It doesn’t look like an animated square. Rather, it looks like a continuous drawing of squares. That’s where the tracer and update functions come in.

The final code

from turtle import *

def drawSquare(side):
    for i in range(4):
        fd(side)
        lt(90)

tracer(0)
pu(), goto(-300, 0), pd()
ht(), width(5)

count = 40000

while count > 0:
    clear()
    drawSquare(100)
    update()
    fd(0.02)
    count -= 1

Mess around with the code. You could draw a pentagon instead. You could also disable the clear() function. The code is available for download here.