In this article, we will explore how to create a starry sky in Python, where the stars have varying sizes, giving a more realistic and dynamic appearance. We’ll make use of the popular turtle
module for graphics rendering and the random
module for generating random sizes and positions for the stars.
Setting Up the Environment
First, let’s ensure that we have Python installed on our system. The turtle
module is a built-in module in Python, so there’s no need for external installation.
Coding the Starry Sky
We’ll start by importing the necessary modules:
pythonimport turtle
import random
Next, we’ll set up the turtle screen and create a turtle object:
python# Create the 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
Now, let’s define a function to draw a star of a given size:
pythondef draw_star(turtle, size):
turtle.begin_fill()
for _ in range(5):
turtle.forward(size) # Move forward by the size of the star
turtle.right(144) # Turn right by 144 degrees
turtle.end_fill()
With this function in hand, we can proceed to draw the stars with varying sizes. We’ll use a loop to draw a certain number of stars, and within the loop, we’ll generate a random size for each star:
python# Draw stars with varying sizes
num_stars = 100
for _ in range(num_stars):
star_size = random.randint(5, 20) # Random star size between 5 and 20
x = random.randint(-300, 300) # Random x-coordinate
y = random.randint(-200, 200) # Random y-coordinate
star_turtle.penup()
star_turtle.goto(x, y)
star_turtle.pendown()
star_turtle.color("white") # Set the color of the star to white
draw_star(star_turtle, star_size)
# Keep the window open
turtle.done()
Testing and Running the Code
Once you’ve written the code, you can run it in your Python environment. You’ll see a window appear with a black background, and on it, you’ll see 100 white stars of varying sizes scattered randomly.
Customizing the Starry Sky
You can customize the starry sky by changing the number of stars (num_stars
), the range of star sizes (random.randint(5, 20)
), the color of the stars (star_turtle.color("white")
), or even the background color (screen.bgcolor("black")
).
Conclusion
By using the turtle
module in Python, we’ve been able to create a dynamic and visually appealing starry sky with varying star sizes. This project not only demonstrates the power of Python for graphics programming but also allows us to experiment with different parameters and customize the output to our liking.