使用 Python 的`turtle`库来实现 2025 新年快乐的程序

以下是一个使用 Python 的turtle库来实现 2025 新年快乐的程序,其中包含烟花效果和祝福语:

import turtle
import random

# 设置画布和画笔
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("2025 新年快乐!")

# 定义烟花类
class Firework:
    def __init__(self):
        self.pen = turtle.Turtle()
        self.pen.speed(0)
        self.pen.hideturtle()
        self.pen.penup()
        self.x = random.randint(-350, 350)
        self.y = random.randint(-250, 100)
        self.pen.goto(self.x, self.y)
        self.pen.pendown()
        self.color = random.choice(["red", "orange", "yellow", "green", "blue", "purple", "pink"])
        self.pen.color(self.color)
        self.size = random.randint(20, 100)

    def explode(self):
        self.pen.dot(self.size)

# 显示祝福语
message_pen = turtle.Turtle()
message_pen.speed(0)
message_pen.color("white")
message_pen.penup()
message_pen.goto(0, 200)
message_pen.write("2025 新年快乐!", align="center", font=("Arial", 36, "bold"))
message_pen.hideturtle()

# 发射烟花
for _ in range(20):
    firework = Firework()
    firework.explode()

# 保持窗口打开
turtle.done()

代码说明:

  1. 导入库:导入turtle库用于绘图,random库用于生成随机数。
  2. 设置画布和画笔:创建一个 800x600 的黑色画布,并设置窗口标题为“2025 新年快乐!”。
  3. 定义烟花类Firework类用于创建烟花对象,包含初始化方法__init__和爆炸方法explode。初始化方法随机选择烟花的位置、颜色和大小,爆炸方法使用dot函数绘制烟花。
  4. 显示祝福语:使用turtlewrite方法在画布上方显示“2025 新年快乐!”的祝福语。
  5. 发射烟花:使用for循环创建 20 个烟花对象,并调用explode方法绘制烟花。
  6. 保持窗口打开:使用turtle.done()方法保持窗口打开,直到用户关闭它。

运行这个程序,你将看到一个包含烟花效果和祝福语的 2025 新年快乐界面。

你可能感兴趣的:(算法,python,python,开发语言)