Turtle Graphics


Graphics is the discipline that underlies the representation and display of geometric shapes in two- and three-dimensional space. Python comes with a large array of resources that support graphics operations. 

A Turtle graphics toolkit provides a simple and enjoyable way to draw pictures in a window and gives you an opportunity to run several methods with an object. 

Overview of Turtle Graphics

Turtle graphics were originally developed as part of the children’s programming language Logo, created by Seymour Papert and his colleagues at MIT in the late 1960s. The name is intended to suggest a way to think about the drawing process. Imagine a turtle crawling on a piece of paper with a pen tied to its tail.Commands direct the turtle as it moves across the paper and tell it to lift or lower its tail, turn some number of degrees left or right, and move a specified distance.Whenever the tail is down, the pen drags along the paper, leaving a trail. In this manner, it is possible to program the turtle to draw pictures ranging from the simple to the complex.

In the context of a computer, of course, the sheet of paper is a window on a display screen and the turtle is an invisible pen point. At any given moment in time, the turtle is located at a specific position in the window. This position is specified with (x, y) coordinates. The coordinate system for turtle graphics is the standard Cartesian system, with the origin (0, 0) at the center of a window. The turtle’s initial position is the origin, which is also called the home. In addition to its position, a turtle also has several other attributes, as shown below.An equally important attribute of a turtle is its heading, or the direction in which it currently faces. The turtle’s initial heading is 0 degrees, or due east on its map. The degrees of the heading increase as it turns to the left, so 90 degrees is due north.

In addition to its position and heading, a turtle also has several other attributes, as described below.

Heading Specified in degrees, the heading or direction increases in value as the turtle turns to the left, or counterclockwise. Conversely, a negative quantity of degrees indicates a right, or clockwise, turn. The turtle is initially facing east, or 0 degrees. North is 90 degrees.
Color Initially black, the color can be changed to any of more than 16 million other colors. 
Width This is the width of the line drawn when the turtle moves. The initial width is 1 pixel. (You’ll learn more about pixels shortly.)
Down This attribute, which can be either true or false, controls whether the turtle’s pen is up or down. When true (that is, when the pen is down), the turtle draws a line when it moves. When false (that is, when the pen is up), the turtle can move without drawing a line.

Together, these attributes make up a turtle’s state. The concept of state is a very important one in object-based programming. Generally, an object’s state is the set of values of its attributes at any given point in time.
The turtle’s state determines how the turtle will behave when any operations are applied to it. For example, a turtle will draw when it is moved if its pen is currently down, but it will simply move without drawing when its pen is currently up. Operations also change a turtle’s state. For instance, moving a turtle changes its position, but not its direction, pen width, or pen color.

Turtle Operations

We can create a Turtle object and call the member functions to do the operations. The following are some important turtle operations.


Setting Up a turtle.cfg File and Running IDLE
Before you run a program or experiment in IDLE with Python’s turtle module, it will help to set up a configuration file. A Turtle graphics configuration file, which has the filename turtle.cfg, is a text file that contains the initial settings of several attributes of Turtle, Screen, and Canvas objects. Python creates default settings for these attributes, which you can find in the Python documentation. For example, the default window size is half of your computer monitor’s width and three-fourths of its height, and the window’s title is “Python Turtle Graphics.” If you want an initial window size of 300 by 200 pixels instead, you can override the default size by including the specific dimensions in a configuration file. The attributes in the file used for most of our examples are as follows:
width = 300
height = 200
using_IDLE = True
colormode = 255
To create a file with these settings, open a text editor, enter the settings as shown, and save the file as turtle.cfg in your current working directory (the one where you are saving your Python script files or from which you launch IDLE). Now you can launch IDLE in the usual way, and you should be able to run the Turtle graphics examples discussed in this section.

Drawing a Square
To illustrate the use of some methods with a Turtle object, let’s define a function named drawSquare. This function expects a Turtle object, a pair of integers that indicate the coordinates of the square’s upper-left corner, and an integer that designates the length of a side. The function begins by lifting the turtle up and moving it to the square’s corner point.It then points the turtle due south—270 degrees—and places the turtle’s pen down on the drawing surface. Finally, it moves the turtle the given length and turns it left by 90 degrees, four times. Here is the code for the drawSquare function:

from turtle import Turtle
def drawSquare(t, x, y, length):
    '''Draws a square with the given turtle t, an upper-left \n
    corner point (x, y), and a side's length.'''
    t.up()
    t.goto(x, y)
    t.setheading(270)
    t.down()
    for count in range(4):
        t.forward(length)
        t.left(90)
t=Turtle()
drawSquare(t,0,0,50)




As you can see, the turtle’s icon is located at the home position (0, 0) in the center of the window, facing east and ready to draw. The user can resize the window in the usual manner. The dafault size is 400 x 300.You can use screensize() function to modify the width,hight and background color.

Let’s continue with the turtle named t, and tell it to draw the letter T, in black and red. It begins at the home position, accepts a new pen width of 2, turns 90 degrees left, and moves north 30 pixels to draw a black vertical line. Then it turns 90 degrees left again to face west, picks its pen up, and moves 10 pixels. The turtle next turns to face due east, changes its color from black to red, puts its pen down, and moves 20 pixels to draw a horizontal line.Finally, we hide the turtle.

from turtle import Turtle
t=Turtle()
t.width(5) # For bolder lines
t.left(90) # Turn to face north
t.forward(50) # Draw a vertical line in black
t.left(90) # Turn to face west
t.up() # Prepare to move without drawing
t.forward(20) # Move to beginning of horizontal line
t.setheading(0) # Turn to face east
t.pencolor("red")
t.down() # Prepare to draw
t.forward(40) # Draw a horizontal line in red
t.hideturtle() # Make the turtle invisible



Examining an Object’s Attributes
The Turtle methods shown in the examples thus far modify a Turtle object’s attributes, such as its position, heading, and color. These methods are called mutator methods, meaning that they change the internal state of a Turtle object. Other methods, such as position(), simply return the values of a Turtle object’s attributes without altering its state. These methods are called accessor methods. The next code segment shows some accessor methods in action:
>>> from turtle import Turtle
>>> t = Turtle()
>>> t.position()
(0.0, 0.0)
>>> t.heading()
0.0
>>> t.isdown()
True
Manipulating a Turtle’s Screen
As mentioned earlier, a Turtle object is associated with instances of the classes Screen and Canvas, which represent the turtle’s window and the drawing area underneath it. The Screen object’s attributes include its width and height in pixels, and its background color, among other things. You access a turtle’s Screen object using the notation t.screen, and then call a Screen method on this object. The methods window_width() and window_height() can be used to locate the boundaries of a turtle’s window. The following code resets the screen’s background color, which is white by default, to orange, and prints the coordinates of the upper left and lower right corners of the window:
from turtle import Turtle
t = Turtle()
t.screen.bgcolor("orange")
x = t.screen.window_width() // 2
y = t.screen.window_height() // 2
t.forward(50)
print((-x, y), (x, -y))



Drawing Two-Dimensional Shapes
Many graphics applications use vector graphics, which includes the drawing of simple two-dimensional shapes, such as rectangles, triangles, pentagons, and circles. Earlier we defined a drawSquare function that draws a square with a given corner point and length, and we could do the same for other types of shapes as well. However, our design of the drawSquare function has two limitations:

1. The caller must provide the shape’s location, such as a corner point, as an argument, even though the turtle itself could already provide this location
2. The shape is always oriented in the same way, even though the turtle itself could provide the orientation.
A more general method of drawing a square would receive just its length and the turtle as arguments, and begin drawing from the turtle’s current heading and position. The same design strategy works for drawing any regular polygon.Here is the code

from turtle import Turtle
def square(t, length):
    """Draws a square with the given length."""
    for count in range(4):
        t.forward(length)
        t.left(90)

t=Turtle()
square(t,50)

def hexagon(t, length):
    """Draws a hexagon with the given length."""
    for count in range(6):
        t.forward(length)
        t.left(60)
t=Turtle()
hexagon(t,50)



Because these functions allow the shapes to have any orientation, they can be embedded in more complex patterns. For example, the radial pattern shown  includes 10 hexagons

The code for a function to draw this type of pattern, named radialHexagons, expects a turtle, the number of hexagons, and the length of a side as arguments. Here is the code for the function:

def hexagon(t, length):
    """Draws a hexagon with the given length."""
    for count in range(6):
        t.forward(length)
        t.left(60)
def radialHexagons(t, n, length):
    """Draws a radial pattern of n hexagons with the given length."""
    for count in range(n):
        hexagon(t, length)
        t.left(360 / n)

t=Turtle()
radialHexagons(t,10,50)




Taking a Random Walk

Animals often appear to wander about randomly, but they may be searching for food, shelter, a mate, and so forth. Or, they might be truly lost, disoriented, or just out for a stroll. Let’s get a turtle to wander about randomly. A turtle engages in this harmless activity by repeatedly turning in a random direction and moving a given distance. The following script defines a function randomWalk that expects as arguments a Turtle object, the number of turns, and distance to move after each turn. The distance argument is optional and defaults to 20 pixels. When called in this script, the function performs 40 random turns with a distance of 30 pixels.  shows one resulting output.

from turtle import Turtle
import random
def randomWalk(t, turns, distance = 20):
    """Turns a random number of degrees and moves a given
    distance for a fixed number of turns."""
    for x in range(turns):
        if x % 2 == 0:
            t.left(random.randint(0, 270))
        else:
            t.right(random.randint(0, 270))
        t.forward(distance)

t = Turtle()
t.shape("turtle")
randomWalk(t, 40, 30)



Colors and the RGB System

The rectangular display area on a computer screen is made up of colored dots called picture elements or pixels. The smaller the pixel, the smoother the lines drawn with them will be. The size of a pixel is determined by the size and resolution of the display. For example, one common screen resolution is 1680 pixels by 1050 pixels, which, on a 20-inch monitor, produces a rectangular display area that is 17 inches by 10.5 inches. Setting the resolution to smaller values increases the size of the pixels, making the lines on the screen appear more ragged.

Each pixel represents a color. While the turtle’s default color is black, you can easily change it to one of several other basic colors, such as red, yellow, or orange, by running the pencolor method with the corresponding string as an argument. To provide the full range of several million colors available on today’s computers, we need a more powerful representation scheme.

Among the various schemes for representing colors, the RGB system is a common one. The letters stand for the color components of red, green, and blue, to which the human retina is sensitive. These components are mixed together to form a unique color value. Naturally, the computer represents these values as integers, and the display hardware translates this information to the colors you see. Each color component can range from 0 through 255. The value 255 represents the maximum saturation of a given color component, whereas the value 0 represents the total absence of that component. Table below lists some example colors and their RGB values.


You might be wondering how many total RGB color values are at your disposal. That number would be equal to all the possible combinations of three values, each of which has 256 possible values, or 256 * 256 * 256, or 16,777,216 distinct color values. Although the human eye cannot discriminate between adjacent color values in this set, the RGB system is called a true color system.

Another way to consider color is from the perspective of the computer memory required to represent a pixel’s color. In general, N bits of memory can represent 2^N distinct data values. Conversely, N distinct data values require at least log2N bits of memory. In the old days, when memory was expensive and displays came in black and white, only a single bit of memory was required to represent the two color values (a bit of 0 turned off the light source at a given pixel position, leaving the pixel black, while a bit of 1 turned the light source on, leaving the pixel white). When displays capable of showing 8 shades of gray came along, 3 bits of memory were required to represent each color value. Early color monitors might have supported the display of 256 colors, so 8 bits were needed to represent each color value. Each color component of an RGB color requires 8 bits, so the total number of bits needed to represent a distinct color value is 24. The total number of RGB colors, 224, happens to be 16,777,216.

The Turtle class includes the pencolor and fillcolor methods for changing the turtle’s drawing and fill colors, respectively. These methods can accept integers for the three RGB components as arguments.
The following program will draw a filled square.

from turtle import Turtle
import random
t = Turtle()
t.pencolor('red')
t.fillcolor('yellow')
t.begin_fill()
for i in range(4):
    t.forward(100)
    t.right(90)
t.end_fill()
t.hideturtle()



Write a Python program to draw a hexagon and to fill it with red colour. Explain the turtle methods used in it. ( university question)
from turtle import Turtle
t=Turtle()
t.fillcolor('red')
t.begin_fill()
for count in range(6):
      t.forward(50)
      t.left(60)
t.end_fill()
t.hideturtle()



Programming With turtle

The turtle library in Python 3.x is advanced a lot.Lets explore the turtle library with different functions

turtle library
turtle is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas. The onscreen pen that you use for drawing is called the turtle and this is what gives the library its name. In short, the Python turtle library helps new programmers get a feel for what programming with Python is like in a fun and interactive way.

You can import the turtle library and  open the turtle screen using the following command
>>> import turtle
>>> s = turtle.getscreen()


Next, you initialize the variable t, which you’ll then use throughout the program to refer to the turtle:
>>> t = turtle.Turtle()

The screen acts as a canvas, while the turtle acts like a pen. You can program the turtle to move around the screen. The turtle has certain changeable characteristics, like size, color, and speed. It always points in a specific direction, and will move in that direction unless you tell it otherwise:When it’s up, it means that no line will be drawn when it moves.When it’s down, it means that a line will be drawn when it moves.

The first thing you’ll learn when it comes to programming with the Python turtle library is how to make the turtle move in the direction you want it to go. Next, you’ll learn how to customize your turtle and its environment. Finally, you’ll learn a couple of extra commands with which you can perform some special tasks

Moving the Turtle

There are four directions that a turtle can move in:
Forward
Backward
Left
Right

The turtle moves .forward() or .backward() in the direction that it’s facing. You can change this direction by turning it .left() or .right() by a certain degree. You can try each of these commands like so:

example

import turtle
s=turtle.getscreen()
t=turtle.Turtle()
t.forward(100) 
t.left(90) 
t.forward(100)

The screen is divided into four quadrants. The point where the turtle is initially positioned at the beginning of your program is (0,0). This is called Home. To move the turtle to any other area on the screen, you use .goto() and enter the coordinates like this:
t.goto(100,100)

To bring the turtle back to its home position, you type the following:
t.home()

This is like a shortcut command that sends the turtle back to the point (0,0). It’s quicker than typing t.goto(0,0).

Drawing a Shape
Drawing a rectangle ( University question)
import turtle
s=turtle.getscreen()
t=turtle.Turtle()
t.forward(100) 
t.right(90) 
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)

or
import turtle
s=turtle.getscreen()
t=turtle.Turtle()
for _ in range(4):
    t.forward(100) 
    t.right(90) 


drawing a triangle
import turtle
s=turtle.getscreen()
t=turtle.Turtle()
t.forward(100) 
t.left(120) 
t.forward(100)
t.left(120)
t.forward(100)


drawing a star ( university question)
import turtle
s=turtle.getscreen()
t=turtle.Turtle()
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)

or

import turtle
s=turtle.getscreen()
t=turtle.Turtle()
for _ in range(5):
    t.forward(100)
    t.right(144)


drawing a circle
import turtle
t=turtle.Turtle()
t.circle(100) # 100 is radius
t.dot(100) # 100 is the diameter


Draw a polygon ( university question)
Note that a function is used here and the coordinates are stored in a list. The goto function is used instead of move with the pen down option to draw
import turtle
def polygon(t,poly):
    x,y=poly[-1]
    t.goto(x,y)
    t.down()
    for x,y in poly:
        t.goto(x,y)
t=turtle.Turtle()
poly=[(0,0),(100,200),(50,150),(-110,150),(0,0)]
polygon(t,poly)



Draw a filled polygon 
import turtle
def polygon(t,poly):
    x,y=poly[-1]
    t.goto(x,y)
    t.down()
    t.fillcolor('green')
    t.pencolor('red')
    t.begin_fill()
    for x,y in poly:
        t.goto(x,y)
    t.end_fill()
t=turtle.Turtle()
poly=[(0,0),(100,200),(50,150),(-110,150),(0,0)]
polygon(t,poly)


Drawing Text
import turtle
# Create a turtle object
t = turtle.Turtle()
# Move the turtle to the desired location
t.penup()
t.goto(0, 0)
t.pendown()
# Write the text
t.write("Hello, world!")
# Keep the window open until the user clicks
turtle.done()

You can also use the turtle.write() function to write text in a different font. To do this, you need to pass the font name, font size, and font style to the turtle.write() function. For example, the following code will write the text "Hello, world!" in the Arial font, size 12, and bold:


Random Circles
# import package
import turtle
# set turtle
turtle.width(2)
turtle.speed(10)
# loop for pattern
for i in range(10):
turtle.circle(40)
turtle.right(36)
# set screen and drawing remain as it is.
turtle.screensize(canvwidth=400, canvheight=300,
bg="blue")




# Python program to draw
# Spiral Square Outside In and Inside Out
# using Turtle Programming
import turtle 
wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
skk = turtle.Turtle()
skk.color("blue")

def sqrfunc(size):
for i in range(4):
skk.fd(size)
skk.left(90)
size = size-5

sqrfunc(146)
sqrfunc(126)
sqrfunc(106)
sqrfunc(86)
sqrfunc(66)
sqrfunc(46)
sqrfunc(26)




# Python program to draw
# Spiral Helix Pattern
# using Turtle Programming

import turtle
loadWindow = turtle.Screen()
turtle.speed(2)

for i in range(100):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)

turtle.exitonclick()


# Python program to draw
# Rainbow Benzene
# using Turtle Programming
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%6])
t.width(x//100 + 1)
t.forward(x)
t.left(59)




Filled star

from turtle import Turtle
t=Turtle()
t.pencolor('red')
t.fillcolor('yellow')
t.begin_fill()
while True:
    t.forward(200)
    t.left(170)
    if abs(t.pos()) < 1:
        break
t.end_fill()
#t.done()




Comments

Popular posts from this blog

Programming in Python CST 362 KTU CS Sixth Semester Elective Notes

Image Processing