返回

50行Python代码畅游满天星海

前端

在浩瀚的宇宙中,繁星点点的夜空令人神往。今天,我们将使用Python编程语言来绘制满天星斗的美丽景象。这不仅是一个有趣的编程练习,也是展现我们想象力和创造力的绝佳机会。

首先,我们需要导入turtle库。这是一个Python的标准库,可以帮助我们轻松创建图形。

import turtle

接下来,我们需要设置画布的大小和颜色。我们将使用黑色作为背景色,以突出星星的亮度。

screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")

现在,我们可以开始绘制星星了。我们将使用一个循环来创建多个星星。在循环中,我们将使用随机数来确定星星的位置、大小和颜色。

for i in range(500):
    x = random.randint(-400, 400)
    y = random.randint(-300, 300)
    size = random.randint(1, 5)
    color = (random.random(), random.random(), random.random())

    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.dot(size, color)

在循环中,我们首先使用random.randint()函数来生成星星的x和y坐标。然后,我们使用random.randint()函数来生成星星的大小。最后,我们使用random.random()函数来生成星星的颜色。

星星绘制完成后,我们需要让它们闪烁起来。我们将使用一个while循环来实现这个效果。在循环中,我们将改变星星的颜色,并休眠一段时间。

while True:
    for i in range(500):
        color = (random.random(), random.random(), random.random())
        turtle.penup()
        turtle.goto(x, y)
        turtle.pendown()
        turtle.dot(size, color)

    turtle.update()
    time.sleep(0.05)

在循环中,我们首先使用random.random()函数来生成星星的新颜色。然后,我们使用turtle.penup()和turtle.goto()函数将画笔移动到星星的位置。最后,我们使用turtle.pendown()和turtle.dot()函数重新绘制星星。

为了使动画更流畅,我们在每次更新屏幕后使用time.sleep()函数休眠一段时间。

现在,我们的星空动画就完成了。您可以运行程序来欣赏满天繁星的美丽景象。您还可以调整循环中的参数来改变星星的数量、大小、颜色和闪烁频率。

希望您喜欢这个有趣的小项目。如果您有任何问题或建议,请随时与我联系。