Python 3.4, while not the most recent version of Python, is still a capable language for creating graphical representations. In this blog post, we’ll explore how to use Python 3.4 to draw a starry sky filled with twinkling stars. We’ll leverage the turtle
graphics module, which is a built-in library that comes with Python’s standard library.
Step 1: Setting Up the Environment
To begin, ensure that you have Python 3.4 installed on your computer. If you don’t have it installed, you can download it from the official Python website.
Step 2: Importing the Necessary Libraries
For this project, we’ll only need to import the turtle
module.
pythonimport turtle
import random
We’re also importing the random
module, which we’ll use to generate random positions and sizes for the stars.
Step 3: Initializing the Canvas
Next, we’ll create a canvas using the turtle
module and set its background color to black to represent the night sky.
python# Create the canvas
screen = turtle.Screen()
screen.bgcolor("black")
# Create a turtle cursor
star_turtle = turtle.Turtle()
star_turtle.speed(0) # Set the drawing speed to the fastest
Step 4: Drawing a Single Star
Let’s define a function to draw a single star. For simplicity, we’ll use a five-pointed star.
pythondef draw_star(turtle, size):
angle = 144
for _ in range(5):
turtle.forward(size)
turtle.right(angle)
turtle.forward(size)
turtle.right(180 - angle)
Step 5: Generating and Drawing Random Stars
Now, we’ll use a loop to generate and draw a specified number of random stars on the canvas.
python# Define the number of stars to generate
num_stars = 500
# Define the range for random x and y coordinates
x_range = (-300, 300)
y_range = (-200, 200)
# Generate and draw random stars
for _ in range(num_stars):
x = random.randint(x_range[0], x_range[1])
y = random.randint(y_range[0], y_range[1])
size = random.randint(2, 10)
color = random.choice(["white", "yellow", "blue", "purple"])
star_turtle.penup() # Move the turtle cursor without drawing
star_turtle.goto(x, y) # Move the turtle cursor to the random position
star_turtle.color(color) # Set the color of the turtle cursor
star_turtle.pendown() # Start drawing with the turtle cursor
draw_star(star_turtle, size)
# Keep the window open until closed manually
turtle.done()
In the above code, we’re generating 500 random stars within a specified range of x and y coordinates. Each star has a random size between 2 and 10 pixels and a random color from the list of predefined colors.
Conclusion
With the help of Python 3.4 and the turtle
graphics module, we’ve successfully created a starry sky filled with twinkling stars. This simple project demonstrates the power of Python for creating graphical representations and provides a great opportunity for experimentation and exploration.