Play with a turtle with turtle graphics (Part 1)

What is Turtle Graphics

There is a turtle with a pen. When you move the turtle using a simple command, the pen that the turtle has will draw a line that traces the movement of the turtle. Since you can move while lifting the pen, you can draw figures that are not drawn with a single stroke. You can also change the color and thickness of the pen.

Turtle graphics first appeared in 1967 with the LOGO language and are also used in programming education for children. It is easy to understand because the operation by the instruction is visible, and it will be quicker to understand programming by combining various instructions. http://en.wikipedia.org/wiki/Turtle_graphics

Turtle graphics in Python

On Windows, you can also use Turtle Graphics by installing Python. Other than Window, you may need to install additional external graphics libraries.

Operation check & operation demo

First, make sure you have python installed. For Windows OS, please refer to the following and check Add python.exe to Path to install python.

Install python on windows environment http://qiita.com/maisuto/items/404e5803372a44419d60

Next, let's check if the turtle moves.

C:\Users\home> python -m turtle

It should work fine on Windows OS. In other environments, you may see an error similar to the following:

$ python -m turtle
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/lib-tk/turtle.py", line 107, in <module>
    import Tkinter as TK
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
    raise ImportError, str(msg) + ', please install the python-tk package'
ImportError: No module named _tkinter, please install the python-tk package

If you get this error, you need to install the python-tk package as described on the last line. For Debian / Ubuntu Linux, install the package as follows.

$ sudo apt-get install python-tk

If it doesn't work at all, try installing the latest version of Python.

Play with a turtle

Preparation

Launch the Python interpreter and import the turtle package.

C:\Users\home> python
>>> from turtle import *

What can i do?

You can see what you can command the turtle with dir () and help ().

>>> dir()
['Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'Terminator', 'Turtle', 'TurtleScreen', 'Vec2D', '__builtins__', '__doc__', '__name__', '__package__', 'acos', 'addshape', 'asin', 'atan', 'atan2', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'ceil', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'cos', 'cosh', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'e', 'end_fill', 'end_poly', 'exitonclick', 'exp', 'fabs', 'fd', 'fill', 'fillcolor', 'floor', 'fmod', 'forward', 'frexp', 'get_poly', 'getcanvas', 'getpen', 'getscreen','getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'hypot', 'isdown', 'isvisible', 'ldexp', 'left', 'listen', 'log', 'log10', 'lt', 'mainloop', 'mode', 'modf', 'onclick', 'ondrag', 'onkey', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pi', 'pos', 'position', 'pow', 'pu', 'radians', 'register_shape', 'reset', 'resetscreen','resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'showturtle', 'sin', 'sinh', 'speed', 'sqrt', 'st', 'stamp', 'tan', 'tanh', 'tilt', 'tiltangle', 'title', 'towards', 'tracer','turtle', 'turtles', 'turtlesize', 'undo', 'undobufferentries', 'up', 'update','width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']
>>> help(Turtle)
>>> help(foward)
>>> help(back)
>>> help(left)
>>> help(right)
>>> help(up)
>>> help(down)
>>> help(color)
>>> help(clear)
>>> help(bye)

For more information, please refer to the online documentation. http://docs.python.jp/2/library/turtle.html

Simple move

As a starting point, let's simply move the turtle.

>>> forward(100)    #Take 100 steps
>>> circle(100)     #Draw a circle with a radius of 100
>>> left(90)        #90 degrees to the left
>>> color('red')    #Hold a red pen
>>> forward(100)    #Take 100 steps

turtle1.png

Draw a pattern

Let's repeat the process and let it draw a pattern.

>>> for i in range(0, 360, 30):  #Every 30 degrees from 0 degrees to 360 degrees
...     circle(50)               #Enter the TAB key at the beginning of the line to indent(Step down)
...     left(30)                 #Enter the TAB key at the beginning of the line to indent(Explanation omitted hereafter)
... #Operation starts by entering a line break at the beginning of the line
>>> color('green'):
>>> for i in range(0, 360, 30):
...     circle(30)
...     left(30)
...     forward(10)
... #Operation starts by entering a line break at the beginning of the line

turtle2.png

Try to define a drawing function

Let's draw a star using the operation of drawing a star as a function.

>>> def star(size):
...     for i in 1,2,3,4,5:
...         forward(size)
...         right(180 - 180/5)
... #Function definition ends by entering a line break at the beginning of the line
>>> reset()
>>> star(100)
>>> color('green')
>>> begin_fill()
>>> star(50)
>>> end_fill()

turtle3.png

Draw fractal shapes

>>> def fractal(size, depth=0):
...    if depth <= 0:
...       forward(size)                          #Straight line
...    else:
...       fractal(size/3, depth-1); left(60)     #1/Fractal drawing with a length of 3, facing 60 degrees to the left
...       fractal(size/3, depth-1); left(-120)   #1/Fractal drawing with a length of 3, facing 120 degrees to the right
...       fractal(size/3, depth-1); left(60)     #1/Fractal drawing with a length of 3, facing 60 degrees to the left
...       fractal(size/3, depth-1)               #1/Fractal drawing with length of 3
... (Blank line input) #Function definition ends by entering a line break at the beginning of the line
... reset(); fractal(200)
... reset(); fractal(200, 1)
... reset(); fractal(200, 2)
... reset(); fractal(200, 3)

turtle4.png

>>> reset(); goto(-100,-100); clear()
>>> for i in "12345":
...     fractal(200, 3)
...     left(360/5)
... (Blank line input)

turtle5.png

That is all for the first part. In the second part, I will play with multiple turtles and add new movements to the turtles.

Recommended Posts

Play with a turtle with turtle graphics (Part 1)
Play with Turtle on Google Colab
[Python] Chapter 03-01 turtle graphics (creating a turtle)
Play handwritten numbers with python Part 2 (identify)
Play like a web app with ipywidgets
[Python] Drawing a swirl pattern with turtle
Draw a graph with PyQtGraph Part 1-Drawing
Play with Prophet
Play with PyTorch
Play with 2016-Python
Play with CentOS 8
Play with Pyramid
Play with Fathom
Tweet the weather forecast with a bot Part 2
[Piyopiyokai # 1] Let's play with Lambda: Creating a Lambda function
Draw a graph with PyQtGraph Part 3-PlotWidget settings
[Python] Draw a Mickey Mouse with Turtle [Beginner]
Draw a graph with PyQtGraph Part 4-PlotItem settings
Draw a graph with PyQtGraph Part 6-Displaying a legend
Draw a graph with PyQtGraph Part 5-Increase the Y-axis
A4 size with python-pptx
I made a ready-to-use syslog server with Play with Docker
[AWS] Play with Step Functions (SAM + Lambda) Part.3 (Branch)
Play with Othello (Reversi)
[Let's play with Python] Make a household account book
How to make a shooting game with toio (Part 1)
sandbox with neo4j part 10
[AWS] Play with Step Functions (SAM + Lambda) Part.1 (Basic)
[Piyopiyokai # 1] Let's play with Lambda: Get a Twitter account
Draw a graph with PyQtGraph Part 2--Detailed plot settings
Decorate with a decorator
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
[Python] Road to a snake charmer (5) Play with Matplotlib
[AWS] Play with Step Functions (SAM + Lambda) Part.2 (Parameter)
Play with the Raspberry Pi Zero WH camera module Part 1
Make a tky2jgd plugin with no practicality in QGIS Part 2
Make a tky2jgd plugin with no practicality in QGIS Part 1
Build a bulletin board app from scratch with Django. (Part 2)
Build a bulletin board app from scratch with Django. (Part 3)
Image processing with Python (Part 2)
Let's play with 4D 4th
Studying Python with freeCodeCamp part1
Make a Blueqat backend ~ Part 1
Let's play with Amedas data-Part 1
Bordering images with python Part 1
Learn librosa with a tutorial 1
Play with reinforcement learning with MuZero
Draw a graph with NetworkX
Scraping with Selenium + Python Part 1
Play with push notifications with imap4lib
Make a Blueqat backend ~ Part 2
Try programming with a shell!
Play around with Linux partitions
Create a homepage with django
Let's play with Amedas data-Part 4
Studying Python with freeCodeCamp part2
Image processing with Python (Part 1)
Play with Jupyter Notebook (IPython Notebook)
[Python] Play with Discord's Webhook.
Solving Sudoku with Python (Part 2)
Using a printer with Debian 10