Creating a starry sky using Python is a fun and engaging way to explore the power of the programming language. In this article, we’ll discuss the code required to draw a beautiful starry sky, step by step.
Prerequisites
To follow this tutorial, you’ll need to have Python installed on your computer. Additionally, we’ll be using the turtle
module, which is a built-in Python module that provides basic graphics capabilities.
The Code
Let’s dive into the code that will help us create a starry sky.
pythonimport turtle
import random
# 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
# Function to draw a star
def 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()
# Draw 100 stars
for _ in range(100):
star_size = random.randint(5, 20) # Random star size
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 until the user closes it
turtle.done()
Code Explanation
- Imports: We import the
turtle
module and the random
module, which will help us generate random values for the stars’ positions and sizes.
- Screen Setup: We create a new screen using
turtle.Screen()
and set its background color to black using screen.bgcolor("black")
.
- Turtle Setup: We create a turtle object using
turtle.Turtle()
and set its drawing speed to the fastest using star_turtle.speed(0)
.
- Draw Star Function: We define a function
draw_star()
that takes a turtle object and a size as parameters. Inside the function, we use a loop to draw a star by moving the turtle forward and turning it right by 144 degrees five times.
- Drawing Stars: We use a loop to draw 100 stars. Inside the loop, we generate random values for the star’s size, x-coordinate, and y-coordinate using the
random
module. We then move the turtle to the random position, set its color to white, and call the draw_star()
function to draw the star.
- Keeping the Window Open: Finally, we use
turtle.done()
to keep the window open until the user closes it.
Conclusion
By using the turtle
module in Python, we’ve been able to create a beautiful starry sky with just a few lines of code. This project is a great way to explore graphics programming in Python and have fun while learning.