Create Colorful Patterns with Python's Turtle Graphics

codepythonic
0

 Create Colorful Patterns with Python's Turtle Graphics


import turtle
import colorsys

# Create a turtle object
t = turtle.Turtle()

# Create a screen object and set the background color to black
s = turtle.Screen()
s.bgcolor('black')

# Set the turtle's speed to the fastest (0)
t.speed(0)

# Set the number of iterations for the color pattern
n = 70

# Initialize the hue value
h = 0

# Iterate through 360 degrees to create the color pattern
for i in range(360):
    # Convert the hue value to an RGB color using the colorsys module
    c = colorsys.hsv_to_rgb(h, 1, 1)

    # Increment the hue value for the next iteration
    h += 1 / n

    # Set the turtle's color to the RGB color
    t.color(c)

    # Rotate the turtle by 1 degree to the left
    t.left(1)

    # Move the turtle forward by 1 unit
    t.forward(1)

    # Draw two circles with a radius of 100 units, creating a pattern
    for j in range(2):
        t.left(2)
        t.circle(100)

    # Rotate the turtle by 1 degree to the left after each complete rotation of the inner loop
    t.left(1)

# Exit the turtle graphics window
turtle.done()



Explanation:

  • The code starts by importing the turtle module for creating turtle graphics and the colorsys module for color manipulation.

The turtle object t is created using turtle.Turtle().
  • The screen object s is created using turtle.Screen(), and the background color of the screen is set to black using s.bgcolor('black').
  • The turtle's speed is set to the fastest speed (0) using t.speed(0).
  • The variable n is set to control the number of iterations for the color pattern. This determines the number of different colors that will be used.
  • The variable h is initialized to 0, representing the hue value for the initial color.
  • The main loop iterates 360 times, representing a full circle.
  • Inside the loop, the hue value h is converted to an RGB color using colorsys.hsv_to_rgb(h, 1, 1). The saturation and value are set to 1, resulting in fully saturated and bright colors.
  • The hue value h is incremented by 1 / n to gradually change the color for each iteration.
  • The turtle's color is set to the RGB color using t.color(c).
  • The turtle is rotated by 1 degree to the left using t.left(1).
  • The turtle is moved forward by 1 unit using t.forward(1).
  • Inside the inner loop, the turtle is rotated by 2 degrees to the left using t.left(2), and a circle with a radius of 100 units is drawn using t.circle(100). This creates a pattern of two overlapping circles.
  • After completing the inner loop, the turtle is rotated by 1 degree to the left using t.left(1). This helps create an intricate pattern by gradually rotating the turtle after each complete rotation of the inner loop.
  • After the main loop finishes, the turtle.done() function is called to keep the turtle graphics window open.






Tags:

Post a Comment

0Comments

Post a Comment (0)