Creating a starry night sky with 100 stars using Python is a simple yet visually appealing task that allows us to explore the capabilities of graphics programming in the language. In this article, we’ll discuss how to generate and draw 100 stars on a canvas using Python, focusing on the code and techniques involved.
Step 1: Importing the Required Libraries
To create the starry sky, we’ll use the turtle
module, which is a built-in graphics library in Python. We don’t need to install any additional libraries for this task.
pythonimport turtle
import random
Step 2: Setting up the Canvas
Before drawing the stars, we need to set up the canvas by creating a window and defining its background color. We’ll use a dark color to mimic the night sky.
python# Create a new turtle screen
screen = turtle.Screen()
screen.bgcolor("black") # Set the background color to black
# Create a turtle object
star_turtle = turtle.Turtle()
star_turtle.speed(0) # Set the drawing speed to the fastest
Step 3: Drawing the Stars
Now we’ll define a function to draw a single star. We’ll use a filled circle to represent each star. The function will take the turtle object, the size of the star, and its color as parameters.
pythondef draw_star(turtle, size, color):
turtle.penup()
x = random.randint(-300, 300) # Random x-coordinate
y = random.randint(-200, 200) # Random y-coordinate
turtle.goto(x, y)
turtle.pendown()
turtle.color(color)
turtle.begin_fill()
turtle.circle(size) # Draw a filled circle to represent the star
turtle.end_fill()
Step 4: Generating and Drawing 100 Stars
Next, we’ll use a loop to generate and draw 100 stars on the canvas. We’ll vary the size and color of each star randomly to create a more realistic and varied sky.
python# Draw 100 stars
for _ in range(100):
size = random.randint(1, 5) # Random star size
color = random.choice(["white", "yellow", "blue", "red", "orange"]) # Random star color
draw_star(star_turtle, size, color)
# Keep the window open until the user closes it
turtle.done()
Conclusion
Using Python and the turtle
module, we’ve successfully created a starry night sky with 100 stars. By varying the size and color of each star randomly, we’ve created a visually appealing and realistic representation of the night sky. This project not only demonstrates the capabilities of Python’s graphics programming features, but also allows us to explore concepts like loops, functions, and random number generation.