Allgemein,  drawings,  general,  Programmieren,  programming,  Zeichnungen

Python Turtle Drawing Program / Programm zum Zeichnen

This post is about Python Turtle again. This time it’s not about patterns, as in the previous post (“Python Turtle”), but about an interactive program where the player can draw something freely.

In diesem Post geht es wieder um Python Turtle. Dieses Mal geht es allerdings nicht um Muster, so wie im vorigen Post (“Python Turtle”), sondern um ein interaktives Programm, bei dem der Spieler etwas frei heraus zeichnen kann.

Skip to finished code / zum fertigen Code springen

The first thing to do is to set the title that will appear at the top of the window.

Als erstes wird der Titel, der am oberen Rand des Fensters erscheint, festgelegt.

turtle.title("Drawing")

Optionally, the size of the window can also be changed in turtle.setup(). For example:

Optional kann auch die Größe des Fensters in turtle.setup() geändert werden. Zum Beispiel:

turtle.setup(1000, 1000)

Then we need to import all the needed packages. This is first of all turtle, but also again the module cycle from itertools. Here it is necessary that we write from turtle import * and not only import turtle (it is not bad if both are there), because otherwise we cannot use all modules of turtle.

Dann werden alle benötigten Pakete importiert. Das ist zunächst einmal turtle, aber auch wieder das Modul cycle von itertools. Hier ist es allerdings nötig, dass wir from turtle import * und nicht nur import turtle schreiben (es ist nicht schlimm, wenn beides dasteht), da wir sonst nicht alle Module der Turtle nutzen können.

import turtle
from turtle import *
from itertools import cycle

After that, variables are defined that are used to set the heading at a certain distance from the edge of the screen, independent of the size of the window. For this, the screen width and height are halved and then added to 40 for positioning. The variables x and y then define the positioning of the beginning of the heading.

Danach werden Variablen definiert, die dafür verwendet werden, die Überschrift unabhängig von der Größe des Fensters mit einem bestimmten Abstand zum Bildschirmrand setzt. Hierfür wird die Bildschirmbreite und -höhe halbiert und anschließend für die Positionierung zu 40 addiert. Die Variablen x und y definieren dann die Positionierung des Anfangs der Überschrift.

screen = Screen()
screenMinX = -screen.window_width()/2
screenMinY = -screen.window_height()/2
screenMaxX = screen.window_width()/2
screenMaxY = screen.window_height()/2

x = screenMinX+40
y = screenMaxY-40

turtle.penup()
turtle.speed(0)
turtle.goto(x,y)
turtle.pendown()
turtle.write("Turtle Drawing", align='left', font=('times new roman', 20))
turtle.penup()

Next, 2 lists are created, colours for the colours of the pen and bgcolours for those of the background. After that the initial colour of the background is defined, the shape of the turtle (optional) and the colour of the pen. turtle.color() includes next(), a part of the package cycle imported at the beginning, so that later the colour of the pen changes.

Als nächstes werden 2 Listen erstellt, colours für die Farben des Stiftes und bgcolours für die des Hintergrunds. Danach wird die anfängliche Farbe des Hintergrunds definiert, die Form der turtle (optional) und die Farbe des Stiftes. turtle.color() beinhaltet next(), ein Teil des zu Beginn importierten Paketes cycle, damit später die Farbe des Stiftes wechselt.

colours = cycle(['white', 'cyan', 'blue', 'green', 'yellow', 'orange', 'red', 'magenta', 'purple'])
bgcolours = cycle(['navy','blue', 'black', 'white'])

turtle.bgcolor("black")
turtle.shape("turtle")
turtle.color(next(colours))

Then the turtle and therefore the pen is brought into position and the speed is set.

Anschließend wird die turtle und somit der Stift in Position gebracht und die Geschwindigkeit festgelegt.

turtle.goto(0,0)
turtle.pendown()
turtle.speed(0.6)

Now it is important that the turtle moves by mouse click, but also by keyboard and performs commands. First on_screen_click(x, y) is defined, after which the turtle moves to the point (x|y). In addition, screen.onclick() must contain the coordinates x and y of on_screen_click() to be able to control the turtle by mouse click.

Nun ist es wichtig, dass sich die turtle per Mausklick, aber auch per Tastatur bewegt und Befehle aufführt. Zuerst wird on_screen_click(x, y) definiert, wonach die turtle zu dem Punkt (x|y) fährt. Zudem muss screen.onclick() die Koordinaten x und y von on_screen_click() enthalten, um die turtle per Mausklick steuern zu können.

def on_screen_click(x, y):
    turtle.goto(x, y)
    
screen.onclick(on_screen_click)

All commands that are to be executed via keyboard, as by pressing a certain key, will now be defined. This is always done according to the same pattern. First there is the keyword def, followed by the name of the command, for example goup(). After that the : must not be missing at the end of the line. In the lines below it is now specified what is to be done after the keystroke. In the example, where the turtle is to go up by 10, the following command would be turtle.forward(10).

The command turtle.listen() makes sure that the turtle remains light-hearted (so to speak) and prevents that the turtle stops responding after a keystroke, but executes any number of commands.

Finally, the key after whose pressure the command is to be executed is determined . For the turtle to go up 10, the “W” key must be pressed. This means that turtle.onkeypress(goup, "w") means that goup, that is, that the turtle goes up 10, is executed after the “W” key is pressed.

Zuletzt werden alle Kommandos, die per Tastatur, als per Drücken einer bestimmten Taste, ausgeführt werden sollen, definiert. Dies erfolgt immer nach dem selben Muster. Zunächst steht das Schlagwort def, nachdem der Name des Befehls angeführt wird, zum Beispiel goup(). Danach darf der : am Ende der Zeile nicht fehlen. In den Zeilen darunter wird nun festgelegt, was nach dem Tastendruck gemacht werden soll. In dem Beispiel, bei dem die turtle um 10 nach oben gehen soll, hieße das folgende Kommando turtle.forward(10).

Das Kommando turtle.listen() sorgt dafür, dass die turtle so zu sagen hellhörig bleibt, als nicht nach einem Tastendruck nicht mehr reagiert, sondern beliebig viele Befehle ausführt.

Zum Schluss wird die Taste bestimmt, nach dessen Druck der Befehl ausgeführt werden soll. Damit die turtle um 10 nach oben geht, muss die Taste “W” gedrückt werden. Das heißt, dass turtle.onkeypress(goup,"w") bedeutet, dass goup, also, dass die turtle 10 nach oben geht, ausgeführt wird, nachdem die Taste “W” gedrückt wird.

def goup():
    turtle.forward(10)

turtle.listen()

turtle.onkeypress(goup,"w")

Finished Code / Fertiger Code

turtle.title("Drawing")

turtle.setup(1000, 1000)

import turtle
from turtle import 
from itertools import cycle

screen = Screen()
screenMinX = -screen.window_width()/2
screenMinY = -screen.window_height()/2
screenMaxX = screen.window_width()/2
screenMaxY = screen.window_height()/2

x = screenMinX+40
y = screenMaxY-40

turtle.penup()
turtle.speed(0)
turtle.goto(x,y)
turtle.pendown()
turtle.write("Turtle Drawing", align='left', font=('times new roman', 20))
turtle.penup()

colours = cycle(['white', 'cyan', 'blue', 'green', 'yellow', 'orange', 'red', 'magenta', 'purple'])
bgcolours = cycle(['navy','blue', 'black', 'white'])

turtle.bgcolor("black")
turtle.shape("turtle")
turtle.color(next(colours))

turtle.goto(0,0)
turtle.pendown()
turtle.speed(0.6)

def on_screen_click(x, y):
    turtle.goto(x, y)
    
screen.onclick(on_screen_click)

def goup():
    turtle.forward(10)
def godown():
    turtle.backward(10)
def goleft():
    turtle.left(10)
def goright():
    turtle.right(10)

def change():
    turtle.color(next(colours))

def penup():
    turtle.penup()
def pendown():
    turtle.pendown()
def pensize():
    p = turtle.numinput("Change Pensize", "Type a number for the pensize", default=1)
    turtle.pensize(p)
    turtle.listen()

def back():
    turtle.bgcolor(next(bgcolours))

def hide():
    turtle.hideturtle()
def show():
    turtle.showturtle()

def clear():
    c = turtle.textinput("Clear Screen", "Do you want to clear the screen ?? (yes/no)")
    if c == 'yes':
        turtle.clear()
    elif c == 'no':
        turtle.shape("turtle")
    turtle.listen()

def text():
    t = turtle.textinput("Text Input", "Type a text")
    f = turtle.textinput("Text Input", "Choose a font")
    n = turtle.numinput("Text Input", "Size of the text", default=20, minval=1)
    turtle.write(t, font=("times new roman", int(n)))
    turtle.listen()

r = 10 #Loops & Squares
n = 10 #Loops & Squares

def circle():
    c = turtle.numinput("Circle Input", "Type a number for the size of the circle", default=100, minval=0)
    turtle.circle(c)
    turtle.listen()

def square():
    v = turtle.numinput("Square Input", "Type a number for the size of the square", default=100, minval=0)
    for i in range(4):
        turtle.forward(v)
        turtle.left(90)
    turtle.listen()

def rectangle():
    x = turtle.numinput("Rectangle Input", "Type a number for the length of the rectangle", default=100, minval=1)
    y = turtle.numinput("Rectangle Input", "Type a number for the width of the rectangle", default=100, minval=1)
    for i in range(2):
        turtle.forward(y)
        turtle.left(90)
        turtle.forward(x)
        turtle.left(90)
    turtle.listen()

def begin_fill():
    turtle.begin_fill()
    def end_fill():
        turtle.end_fill()

###################### HERE SOME EXTRAS ######################
def loops():
    loop = turtle.textinput("Loops", "Do you want the loops in different colours ?? (yes/no)")
    if loop == 'yes':
        for i in range(1, n + 1, 1):
            turtle.circle(r * i)
            turtle.color(next(colours))
    elif loop == 'no':
        for i in range(1, n + 1, 1):
            turtle.circle(r * i)
    turtle.listen()

def spyrograph():
    turtle.speed(0)
    spyro = turtle.textinput("Spyrograph", "Do you want the circles in different colours ?? (yes/no)")
    if spyro == 'yes':
        for i in range(36):
            for i in range(36):
                turtle.forward(10)
                turtle.left(10)
            turtle.left(10)
            turtle.color(next(colours))
    if spyro == 'no':
        for i in range(36):
            for i in range(36):
                turtle.forward(10)
                turtle.left(10)
            turtle.left(10)

    turtle.right(5)
    turtle.circle(57)
    turtle.color(next(colours))
    turtle.speed(0.6)
    turtle.listen()

def triangles():
    triangle = cycle(['blue', 'red', 'yellow'])
    tri = turtle.textinput("Triangles", "Do you want the triangles in different colours ?? (yes/no)")
    turtle.speed(0)
    if tri =='yes':
        for i in range(500):
            turtle.color(next(triangle))
            turtle.width(0.5)
            turtle.forward(i)
            turtle.left(121)
    if tri =='no':
        for i in range(500):
            turtle.width(0.5)
            turtle.forward(i)
            turtle.left(121)
    turtle.speed(0.6)
    turtle.listen()  


def squares():
    square = turtle.textinput("Squares", "Do you want the squares in different colours ?? (yes/no)")
    if square =='yes':
        for i in range(1, n + 1, 1):
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
            turtle.color(next(colours))
    if square == 'no':    
        for i in range(1, n + 1, 1):
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
            turtle.forward(r * i)
            turtle.left(90)
    turtle.listen()

def hexagon():
    turtle.speed(0)
    hex = cycle(['red', 'green', 'yellow', 'purple', 'blue','orange'])
    h = turtle.textinput("Hexagon", "Do you want the hexagon in different colours ?? (yes/no)")
    if h == 'yes':
        for i in range(200):
            turtle.color(next(hex))
            x = i/100 + 1
            turtle.width(x)
            turtle.forward(i)
            turtle.left(59) 
    if h == 'no':
        for i in range(200):
            x = i/100 + 1
            turtle.width(x)
            turtle.forward(i)
            turtle.left(59)
    turtle.speed(0.6)
    turtle.listen()

##############################################################

turtle.listen()

turtle.onkeypress(goup,"w")
turtle.onkeypress(godown,"s")
turtle.onkeypress(goleft,"a")
turtle.onkeypress(goright,"d")
turtle.onkeypress(change,"q")
turtle.onkeypress(clear,".")

turtle.onkeypress(penup,"y")
turtle.onkeypress(pendown,"x")
turtle.onkeypress(pensize,"p")

turtle.onkeypress(back,"b")
turtle.onkeypress(hide,"h")
turtle.onkeypress(show,"j")

turtle.onkeypress(text,"t")

turtle.onkeypress(circle,"c")
turtle.onkeypress(square,"v")
turtle.onkeypress(rectangle,"r")

turtle.onkeypress(begin_fill,"f")
turtle.onkeypress(end_fill,"g")

turtle.onkeypress(loops,"1")
turtle.onkeypress(spyrograph,"2")
turtle.onkeypress(triangles,"3")
turtle.onkeypress(squares,"4")
turtle.onkeypress(hexagon,"6")
10470cookie-checkPython Turtle Drawing Program / Programm zum Zeichnen

Leave a Reply

Your email address will not be published. Required fields are marked *