Turtle and Screen Methods in Python

In Python, we can use the `turtle` and `screen` modules to create some sweet graphics. ..

Why do they call it “graphics” anyway? Because you have to draw pictures with your own two hands!

But seriously , here are the methods we need to know:

1. `turtle.forward(x)` Moves the turtle forward by x units in the current direction.
2. `turtle.backward(x)` Moves the turtle backward by x units in the current direction.
3. `turtle.left(angle)` Turns the turtle left by angle degrees.
4. `turtle.right(angle)` Turns the turtle right by angle degrees.
5. `screen.setup(width, height)` Sets up a new window with width and height dimensions.
6. `screen.exitonclick()` Exits the program when the user clicks anywhere on the screen.
7. `turtle.speed(n)` Changes the speed of the turtle’s movements to n (0-10).
8. `turtle.color(r, g, b)` Sets the color of the turtle’s pen to r, g, and b values between 0 and 1.
9. `screen.bgcolor(r, g, b)` Sets the background color of the screen to r, g, and b values between 0 and 1.

Now let’s put them all together in a simple program:

import turtle # Import the turtle module to use its functions
from random import randint # Import the randint function from the random module

screen = turtle.Screen() # Create a screen object to draw on
tess = turtle.Turtle() # Create a turtle object to draw with

# Set up the screen with some dimensions and background color
screen.setup(800, 600) # Set the dimensions of the screen to 800x600 pixels
screen.bgcolor((0, 0, 0)) # Set the background color to black using RGB values between 0-1

# Define a function to draw a random shape
def draw_shape():
    tess.speed(randint(5, 8)) # Set the speed of the turtle's movements randomly between 5 and 8
    num_sides = randint(3, 7) # Generate a random number between 3 and 7 for the number of sides in the polygon
    angle = 360 // num_sides # Calculate the angle per side based on the number of sides
    for i in range(num_sides):
        tess.forward(150) # Move forward by 150 units (length of each side)
        tess.left(angle) # Turn left by the calculated angle

# Call the function to draw a random shape every time we click on the screen
screen.onclick(draw_shape) # Set the function draw_shape to be called every time the screen is clicked
screen.listen() # Listen for events on the screen
screen.exitonclick() # Exit the program when the screen is clicked

And that’s it! You can run this program and watch as turtles create beautiful polygons for you.

SICORPS