Python Turtle Library and Game
Python Turtle Library is an extremely useful and simple python library that provides a graphical interface environment. The Turtle library, where you can create nested intricate shapes and at the same time provide input form inputs, is quite fun.

Python Turtle Library is an extremely useful and simple python library that provides a graphical interface environment. The Turtle library, where you can create nested intricate shapes and at the same time provide input form inputs, is quite fun.
The Turtle module comes installed in Python. Therefore, you can start using it by typing -import turtle without any extra installation.
Index
Turtle Library Documentation
You can review all python code related to Python Turtle in the GitHub repo:
https://github.com/omersahintr/pyTurtles
If you do a Google search on Turtle Library, I can recommend a few websites for documentation.
- https://docs.python.org/3/library/turtle.html
- https://realpython.com/beginners-guide-python-turtle/
- https://pythonsandbox.com/turtle
All Python code in this article has been tested and published in Python 3.12.
Sample Turtle Codes
Write and run the following code. Information about the function is given in the comment line with “#” next to the lines.
import turtle
yazi_tahtasi = turtle.Screen() #yazi_tahtası adında turtle object
yazi_tahtasi.bgcolor("yellow") #Sayfa arkaplan rengi "#880033" veya "red" vs.
yazi_tahtasi.title("Yazı Tahtası") #Sayfa Başlığı
turtle_ins = turtle.Turtle() #turtle object oluştur.
turtle_ins.forward(100) #100px ileri git
turtle.done() #turtle kapat
PythonScreen Output:

To Draw Two Lines by Making an Angle
To draw two vectors at an angle to each other:
import turtle
yazi_tahtasi = turtle.Screen()
yazi_tahtasi.bgcolor("yellow") #Sayfa arkaplan rengi
yazi_tahtasi.title("Yazı Tahtası") #Sayfa Başlığı
turtle_ins_1 = turtle.Turtle() #turtle nesnesi oluştur
turtle_ins_1.forward(100) #100px ileri git
turtle_ins_2 = turtle.Turtle() #Ikinci turtle objesi
turtle_ins_2.left(60) #sola 60 derece aci yap
turtle_ins_2.forward(100) #100 pixel ileri git
turtle.done() #turtle kapat
PythonScreen Output:

To Draw a Quadrilateral or Square with Turtle
To draw a triangle, square, rectangle, pentagon or polygon with a single turtle object:
### KARE ÇİZDİREN KODLAR ###
import turtle
yazi_tahtasi = turtle.Screen()
yazi_tahtasi.bgcolor("yellow") #Sayfa arkaplan rengi
yazi_tahtasi.title("Yazı Tahtası") #Sayfa Başlığı
turtle_ins = turtle.Turtle() #turtle çalıştır
turtle_ins.forward(100) #100px ileri git
turtle_ins.left(90) #sola 90 derece aci yap
turtle_ins.forward(100) #100 pixel ileri git
turtle_ins.left(90) #sola 90 derece aci yap
turtle_ins.forward(100) #100 pixel ileri git
turtle_ins.left(90) #sola 90 derece aci yap
turtle_ins.forward(100) #100 pixel ileri git
turtle.done() #turtle kapat
PythonScreen Output:

For the last square shape we wrote, I think we did a bit of “code hammocking”. I mean, is it necessary to write so many lines of code just to draw a square?
Do you think we can draw in one line using Python Loops?
### MATH SHAPES DRAWING ###
import turtle
kose = 0
koseSay = int(input("Köşe Sayısını giriniz: "))
kenarUzunluk = int(input("Kenar Uzunluğu giriniz: "))
yazi_tahtasi = turtle.Screen()
yazi_tahtasi.bgcolor("yellow") #Sayfa arkaplan rengi
yazi_tahtasi.title("Yazı Tahtası") #Sayfa Başlığı
turtle_ins = turtle.Turtle() #turtle çalıştır
while(True):
if kose!=koseSay:
turtle_ins.forward(kenarUzunluk) #100px ileri git
turtle_ins.left(360/koseSay) #sola X derece aci yap
kose+=1
else:
break
turtle.done() #turtle kapat
PythonOur code is now a Python job. I’m sure some of you said:
–“We wrote 2 lines less, is that it?“
Angle = 360/Number of Edges
When we integrate the angle formula above with the Turtle library in Python, it will draw as many polygons as the number of sides the user will enter from the screen.
For Drawing Star Shape
If we want to draw a smooth star shape:
### STAR SHAPING ###
import turtle
kose = 0
koseSay = 5
kenarPx = int(input("Kenar Uzunluğu Giriniz: "))
yazi_tahtasi = turtle.Screen()
yazi_tahtasi.bgcolor("yellow") #Sayfa arkaplan rengi
yazi_tahtasi.title("Yazı Tahtası") #Sayfa Başlığı
turtle_ins = turtle.Turtle() #turtle çalıştır
for i in range(koseSay):
turtle_ins.forward(kenarPx)
turtle_ins.left(144) #yıldızın bir iç açısı 144 derecedir
turtle.done() #turtle kapat
PythonScreen Output:

You can publish the part of the project that we have written up to this point on GitHub if you wish. For help about GitHub, you can take a look at our article titled “Git Commands“.
İç İçe Dönen Kareleri Çizen Turtle Kodları
### SQUARE in SQUARE Drawing ###
import turtle as tur #shortname is tur
shape = tur.Screen()
shape.bgcolor("light blue") #background color
shape.title("Black Board - Square in Square") #titled
shape = tur.Turtle() #new objective defined
shape.color("yellow") #arrow color set
tur.speed(0.22) #animation speed value
def square(dim,angle): #define drawing method
for i in range(4):
tur.forward(dim)
tur.left(angle)
dim-=1
angle+=1
for i in range(60):
square(120,90)
tur.done()
PythonScreen Output:

As seen here, when we change the values of mathematical variables in a loop, interesting drawings emerge.
Two Circles Rotate Around Each Other, Produced in Different Colors Each Time
In this example we will call the PI number in the Math library and generate an animation as a function of it.
If you want to write Python-based applications with form objects, you should use the Tkinter Python library.
### COLORFUL HELIX SPIRAL SHAPE DRAWING ###
import turtle as tur
import secrets as sec
from math import pi
helix = tur.Screen() #define screen
helix.title("Helix Spinner") #title name
helix.bgcolor("black") #background color set
spinner = tur.Turtle() #new turtle object created
spinner.speed(0.22) #object animation speed has changed
spinner.color("red") #default line color set
for i in range(150): #150 times for loop
spinner.circle(pi * i) #pi=3.14 calculate
spinner.circle(-pi * i) #-pi=-3.14
spinner.circle(20 * (i / 100), 10 * (i / 100), (1)) #circle animation formula
scolor = ""
x = 0
while x<6: #this loop generate to color hexcode
scolor += sec.choice("0123456789ABCDEF") #secret code generated for base hexcode
x += 1
spinner.color("#"+scolor)
tur.done() #turtle has closed
#tur.mainloop() #mainloop function, always loop :)
PythonScreen Video Output :
Writing User Interactive Code with Turtle Module
So far, with the Python Turtle Library, we have always drawn with the parameters we have given in the code line. After this stage, you will learn how to draw with user input in the Turtle module. For this, we are looking at the codes that will receive which key the user presses from the keyboard.
Turtle listen() and onkey() Function
With these two functions, keyboard actions are detected and transferred to the program code you write with the python turtle module. I am leaving the document links about keyboard (keypress) operations here:
First, we need to call the listen() function and then get the action from the keyboard with the onkey(function, key) function
### Action Drawing Board Created
import turtle as tur #turtle imported and its names tur
blackBoard = tur.Screen() #blackBoard Screen created
blackBoard.bgcolor("black") #set bg color
blackBoard.title("Action Black Board") #set board title
blackIns = tur.Turtle() # blackIns Turtle object has created
blackIns.color("white") # arrow and line color sets
def drawing(): #a function defined
blackIns.forward(150) #forward XXX px action
blackBoard.listen() #keyboard listen has started
blackBoard.onkey(fun=drawing,key="space") # press to space button on keyboard
tur.mainloop() #loop func.
PythonScreen Output of Python Code:
After running the Python code, every time you press “Space” on the keyboard, it will draw a 150 px line to the right.

Interactive Mini Game Development for Kids with Turtle
Using the Python Turtle library, the following lines of code were written and when executed, we developed a beginner level game for children. The function of the keys in the program, which works interactively with different keys entered from the keyboard, is as follows:
KEYBOARD | ACTION |
---|---|
space | will draw a line 150 px at a time. |
right button | each time at a 30-degree angle to the right. |
left button | each time at an angle of 30 degrees to the left. |
C char | will clear the screen every time. |
H char | each time the cursor (arrow) will move to the starting point. |
N char | will take the pen off the board every time. |
Y char | will touch the pencil to the blackboard every time. |
### Action Drawing Board Created
import turtle as tur #turtle imported and its names tur
blackBoard = tur.Screen() #blackBoard Screen created
blackBoard.bgcolor("black") #set bg color
blackBoard.title("Action Black Board") #set board title
blackIns = tur.Turtle() # blackIns Turtle object has created
blackIns.color("white") # arrow and line color sets
### Drawing Functions ###
def drawing(): #a function defined
blackIns.forward(150) #forward XXX px action
def chanegAngleRight(): #rotate right angle
blackIns.right(30)
def changeAngleLeft(): #Rotate left angle
blackIns.left(30)
def cleanBoard(): #clear black board funvtion
blackIns.clear()
def returnLastPoint(): #REturn home or last point
blackIns.penup() #pen up from board
blackIns.home() #jump to home point
blackIns.pendown() #pen down to board
def noPen(): #pen up function
blackIns.penup()
def onPen(): #pen down function
blackIns.pendown()
### @@@ Drawing Functions @@@ ###
blackBoard.listen() #keyboard listening has started
blackBoard.onkey(fun=drawing,key="space") # press to space button on keyboard
blackBoard.onkey(fun=chanegAngleRight,key="Right") # press to Right button on keyboard
blackBoard.onkey(fun=changeAngleLeft,key="Left") # press to Left button on keyboard
blackBoard.onkey(fun=cleanBoard,key="c") # press to C button on keyboard
blackBoard.onkey(fun=returnLastPoint,key="h") # press to H button on keyboard
blackBoard.onkey(fun=noPen,key="n") # press to N button on keyboard
blackBoard.onkey(fun=onPen,key="o") # press to O button on keyboard
tur.mainloop() #loop func.
PythonScreen Output of the Code Block:

Game Development with Python Turtle
Would you like to develop a game with Turtle, a Python library? In the finale of our Turtle article, we will develop a very fun game.
Our game is called, “Escape Turtle: Catch the Turtle“
import turtle as tur
import random
### GLOBAL VARIABLES ####################
table_size = 12 #table size set #
score=0 # scoreboard reset #
xVals = [30,20,10,0,-10,-20] #
yVals = [-30,-20,-10,0,10,20] #
turtleList =[] #
timerVal=600 #
countDown=15 #
gameOver = False #
#########################################
gameBoard = tur.Screen()
gameBoard.bgcolor("light yellow") #screen backcolor set
gameBoard.title("Escape the Turtle") #screenboard title set
countIns = tur.Turtle() #count of click turtle
count_down = tur.Turtle()
def count_turtle():
countIns.color("dark green")
countIns.penup() #pen up on the board
countIns.hideturtle() #turtle arrow is hide
top = gameBoard.window_height()/2 #top on the gameBoard Screen
yAxis = top*0.9 #y-axis value
countIns.setpos(0,yAxis) #set position on the screen
countIns.write(arg="Count:0", move=False, align="center",
font=("Verdana", 25, "bold")) # Write on the Turtle screen object
def create_turtle(x,y): #Turtle show position on screen function
t = tur.Turtle()
def detect_click(x,y):
global score
global gameOver
score+=1
if not gameOver:
countIns.clear()
countIns.write(arg=f"Count:{score}", move=False, align="center",
font=("Verdana", 25, "bold")) # Write on the Turtle screen object
#print(x,y)
t.onclick(detect_click)
t.penup()
t.shape("turtle")
t.shapesize(3,3)
t.color("red")
t.goto(x * table_size, y * table_size) #distance turtles calculate
turtleList.append(t) #List array has added
def show_turtles(): #all turtle show func.
for yy in yVals:
for xx in xVals:
create_turtle(xx,yy)
def hide_turtles(): #all turtles hide func.
for t in turtleList:
t.hideturtle()
def random_show_turtle(): # random choice turtle function
if not gameOver:
hide_turtles()
random.choice(turtleList).showturtle()
gameBoard.ontimer(random_show_turtle,timerVal) #recursive function: running function in self
def count_down_func(countDown):
global gameOver
count_down.color("dark green")
count_down.penup() # pen up on the board
count_down.hideturtle() # turtle arrow is hide
top = gameBoard.window_height() / 2 # top on the gameBoard Screen
yAxis = top * 0.9 # y-axis value
count_down.setpos(0, yAxis-30) # set position on the screen
if countDown>0:
count_down.clear()
count_down.write(arg=f"Timer:{countDown}", move=False, align="center",
font=("Verdana", 25, "bold")) # Write on the Turtle screen object
gameBoard.ontimer(lambda: count_down_func(countDown-1),1000)
else:
gameOver=True
count_down.clear()
hide_turtles()
count_down.write(arg="Game Over", move=False, align="center",
font=("Verdana", 25, "bold")) # Write on the Turtle screen object
def start_the_game():
tur.tracer(0) #turtle shaping is now start (NO ANIMATION)
count_turtle() #write count value on top of the screen
show_turtles() #all turtles show
hide_turtles() #all turtles hide
random_show_turtle() #random a turtle show
count_down_func(countDown)
tur.tracer(1) #turtle shaping is now finish
start_the_game()
tur.mainloop()
PythonScreenshot of the game:
You can copy the game code and run it in your python environment. If you wish, you can play the game in different scenarios by changing the parameters in the GLOBAL VARIABLES section at the beginning of the code line.
Each line is accompanied by an explanation in English. If you have any questions, you can share them with us in the comments section below.
You can even modify the code to develop the next version of the game.