Animations and Interactive Programming

Interactive Programming: Clicks and Keyboard

In addition to pointer interaction, it is possible to include keyboard keys in interactive programming.

import turtle
import random
import math

turtle.setup(500, 500)
screen = turtle.Screen()
turtle.title("Turtle Keys")
turtle.pensize(3)

colors = ("orange", "pink", "yellow", "green", "blue", "purple", "magenta", "cyan")
drawing = False


def goto_and_do_whatever_required(x, y):
    global drawing
    if (drawing):
        return
    if (y > 150):
        return
    drawing = True
    turtle.goto(x, y)
    turtle.color(colors[random.randint(0, len(colors) - 1)])
    drawing = False


def upkeyfunc():
    turtle.forward(15)


def leftkeyfunc():
    turtle.left(15)


def rightkeyfunc():
    turtle.right(15)


def downkeyfunc():
    turtle.back(15)


def u_keyfunc():
    turtle.penup()


def d_keyfunc():
    turtle.pendown()


turtle.onkeypress(upkeyfunc, "Up")
turtle.onkeypress(leftkeyfunc, "Left")
turtle.onkeypress(rightkeyfunc, "Right")
turtle.onkeypress(downkeyfunc, "Down")

turtle.onkeypress(u_keyfunc, "U")
turtle.onkeypress(u_keyfunc, "u")

turtle.onkeypress(d_keyfunc, "D")
turtle.onkeypress(d_keyfunc, "d")

turtle.listen()

screen.onscreenclick(goto_and_do_whatever_required)

turtle.done()

The keys "U" and "u" can be used to call penup()function, and similarly the keys "D" and "d" can be used for calling the pendown() function.

Exercise: Add a function that can be called by pressing the keys "C" or "c" to change the color of the turtle pen to a random color.

You may also prefer to change the color in round-robin fashion, one after the other in a successive order, instead of using a random index, by keeping track of the color index at each color change. In order to do so, define a function for changing the color and call that function from both the pointer (mouse, touchpad, touchscreen) clicks and the color change method call by keys "C" and "c" you will implement in this exercise.