Python实现流星雨效果的代码

绘制一颗流星

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
 
x0,y0 = 1,1     #此为流星位置
ts = np.arange(0,1,0.01)    #参数
xs,ys = x0+ts, y0+ts        #绘图线条
 
points = np.array([xs, ys]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
 
ax = plt.subplot()
lc = LineCollection(segments, cmap='viridis')
 
lc.set_array(ts)
lc.set_linewidth(ts[::-1])
line = ax.add_collection(lc)
 
ax.set_xlim(0, 3)
ax.set_ylim(0, 3)
plt.show()

 很多流星

from numpy.random import rand, randint
from matplotlib.collections import LineCollection

import numpy as np
import matplotlib.pyplot as plt

N, L = 20, 100  # 流星个数和线段数
ts = np.array([
    np.linspace(0, rand(), L) for _ in range(N)]).T
x0, y0 = rand(2 * N).reshape(2, 1, N)
x0 *= 5
xs, ys = x0 + ts, y0 + ts  # 绘图线条1

points = np.array([xs, ys]).T.reshape(N, L, -1, 2)

ax = plt.subplot()
for i in range(N):
    segs = np.concatenate([points[i][:-1], points[i][1:]], axis=1)
    lc = LineCollection(segs, cmap='viridis')
    lc.set_array(ts[:, i])
    lc.set_linewidth(ts[::-1, i])
    ax.add_collection(lc)

ax.set_xlim(0, 6)
ax.set_ylim(-2, 3)
ax.set_axis_off()  # 取消坐标轴
plt.show()

 

这是一个使用Python实现动态流星雨效果的示例代码: ```python import random import time # 设置屏幕的宽度和高度 WIDTH = 80 HEIGHT = 20 # 定义流星的类 class Meteor: def __init__(self): self.x = random.randint(0, WIDTH) # 随机生成初始x坐标 self.y = 0 # 初始y坐标为0 self.speed = random.uniform(0.1, 1) # 随机生成下落速度 # 更新流星的位置 def update(self): self.y += self.speed if self.y >= HEIGHT: # 如果流星超出屏幕范围,则重新生成 self.x = random.randint(0, WIDTH) self.y = 0 self.speed = random.uniform(0.1, 1) # 绘制流星 def draw(self): print("\033[31m*\033[0m", end="", flush=True) # 使用红色打印字符,"\033[31m"表示红色,"\033[0m"表示恢复默认颜色 # 清空屏幕 def clear_screen(): print("\033[2J", end="", flush=True) # 设置光标位置 def set_cursor(x, y): print("\033[{};{}H".format(y, x), end="", flush=True) # 隐藏光标 def hide_cursor(): print("\033[?25l", end="", flush=True) # 显示光标 def show_cursor(): print("\033[?25h", end="", flush=True) # 主程序 def main(): meteors = [] # 存储流星的列表 # 初始化流星 for _ in range(10): meteors.append(Meteor()) hide_cursor() clear_screen() while True: clear_screen() for meteor in meteors: meteor.update() set_cursor(int(meteor.x), int(meteor.y)) meteor.draw() time.sleep(0.1) if __name__ == "__main__": main() ``` 你可以运行以上代码,在终端中会出现一个动态的流星雨效果。希望对你有帮助!
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值