profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Friday, November 10, 2017

Python 3.6 turtles or drawing stuff


"Turtle" is a module in python which helps us to create some basic drawings. Imagine this as a scrible or whiteboard and you use your code to draw. Why the name turtle? well, Imagine a turtle whose tails is dipped in ink and when it is moving on a whiteboard or paper, the tail leaves the ink on the paper creating thus a diagram or drawing. you control the movement of the turtle and turtle's tail dipped in ink takes care of the drawing. cool..haan..i know. Let us get started with your python shell. I always run 3 commands when i am using a new module to know more and explore it.
help()
dir()
<modulename>.__doc__
make it a habit and it will help you.

import turtle
help(turtle)

also run
>>> dir(turtle)
['Canvas', 'Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'TK', 'TNavigator', 'TPen', 'Tbuffer', 'Terminator', 'Turtle', 'TurtleGraphicsError', 'TurtleScreen', 'TurtleScreenBase', 'Vec2D', '_CFG', '_LANGUAGE', '_Root', '_Screen', '_TurtleImage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__forwardmethods', '__func_body', '__loader__', '__methodDict', '__methods', '__name__', '__package__', '__spec__', '__stringBody', '_alias_list', '_make_global_funcs', '_screen_docrevise', '_tg_classes', '_tg_screen_functions', '_tg_turtle_functions', '_tg_utilities', '_turtle_docrevise', '_ver', 'addshape', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'config_dict', 'deepcopy', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'end_fill', 'end_poly', 'exitonclick', 'fd', 'fillcolor', 'filling', 'forward', 'get_poly', 'get_shapepoly', 'getcanvas', 'getmethparlist', 'getpen', 'getscreen', 'getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'inspect', 'isdown', 'isfile', 'isvisible', 'join', 'left', 'listen', 'lt', 'mainloop', 'math', 'mode', 'numinput', 'onclick', 'ondrag', 'onkey', 'onkeypress', 'onkeyrelease', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'read_docstrings', 'readconfig', 'register_shape', 'reset', 'resetscreen', 'resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'simpledialog', 'speed', 'split', 'st', 'stamp', 'sys', 'textinput', 'tilt', 'tiltangle', 'time', 'title', 'towards', 'tracer', 'turtles', 'turtlesize', 'types', 'undo', 'undobufferentries', 'up', 'update', 'width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']

>>> turtle.__doc__
'\nTurtle graphics is a popular way for introducing programming to\nkids. It was part of the original Logo programming language developed\nby Wally Feurzig and Seymour Papert in 1966.\n\nImagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it\nthe command turtle.forward(15), and it moves (on-screen!) 15 pixels in\nthe direction it is facing, drawing a line as it moves. Give it the\ncommand turtle.right(25), and it rotates in-place 25 degrees clockwise.\n\nBy combining together these and similar commands, intricate shapes and\npictures can easily be drawn.\n\n----- turtle.py\n\nThis module is an extended reimplementation of turtle.py from the\nPython standard distribution up to Python 2.5. (See: http://www.python.org)\n\nIt tries to keep the merits of turtle.py and to be (nearly) 100%\ncompatible with it. This means in the first place to enable the\nlearning programmer to use all the commands, classes and methods\ninteractively when using the module from within IDLE run with\nthe -n switch.\n\nRoughly it has the following features added:\n\n- Better animation of the turtle movements, especially of turning the\n  turtle. So the turtles can more easily be used as a visual feedback\n  instrument by the (beginning) programmer.\n\n- Different turtle shapes, gif-images as turtle shapes, user defined\n  and user controllable turtle shapes, among them compound\n  (multicolored) shapes. Turtle shapes can be stretched and tilted, which\n  makes turtles very versatile geometrical objects.\n\n- Fine control over turtle movement and screen updates via delay(),\n  and enhanced tracer() and speed() methods.\n\n- Aliases for the most commonly used commands, like fd for forward etc.,\n  following the early Logo traditions. This reduces the boring work of\n  typing long sequences of commands, which often occur in a natural way\n  when kids try to program fancy pictures on their first encounter with\n  turtle graphics.\n\n- Turtles now have an undo()-method with configurable undo-buffer.\n\n- Some simple commands/methods for creating event driven programs\n  (mouse-, key-, timer-events). Especially useful for programming games.\n\n- A scrollable Canvas class. The default scrollable Canvas can be\n  extended interactively as needed while playing around with the turtle(s).\n\n- A TurtleScreen class with methods controlling background color or\n  background image, window and canvas size and other properties of the\n  TurtleScreen.\n\n- There is a method, setworldcoordinates(), to install a user defined\n  coordinate-system for the TurtleScreen.\n\n- The implementation uses a 2-vector class named Vec2D, derived from tuple.\n  This class is public, so it can be imported by the application programmer,\n  which makes certain types of computations very natural and compact.\n\n- Appearance of the TurtleScreen and the Turtles at startup/import can be\n  configured by means of a turtle.cfg configuration file.\n  The default configuration mimics the appearance of the old turtle module.\n\n- If configured appropriately the module reads in docstrings from a docstring\n  dictionary in some different language, supplied separately  and replaces\n  the English ones by those read in. There is a utility function\n  write_docstringdict() to write a dictionary with the original (English)\n  docstrings to disc, so it can serve as a template for translations.\n\nBehind the scenes there are some features included with possible\nextensions in mind. These will be commented and documented elsewhere.\n\n'

Once you are done exploring it then let us proceed to some fun stuff. Let us draw a
a line
a triangle
a rectangle
a circle and some fun with all of them.

a turtle always starts from left to right. clear the screen. run the following.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90) # tell amy to move forward for about 90 units

you will see that our amy (turtle) draws a straight line or in other words moves from left to right for about 90 units and leaves a trace of ink on its path.
Let us turn that into a triangle.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)

you will now see that in the new window amy/turtle draws a triangle.
Let us make a rectangle around it. I am sure now you know how it works. So let us try it out.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)

Now our triangle is inside the new rectangle. Why stop there? let us have a circle on these too.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.circle(180) # a circle with 180 units of radius

I want you to explore more since the motto of this post is only to enable you to explore and not explore. Help you to learn cooking so that you cook for yourself and not to cook and steal the fun of cooking from you. FYI I don't much like cooking. I just make oats twice a day with water/salt/spice and thats it.