用python写一个漂浮雪花
时间: 2024-05-06 18:17:17 浏览: 6
好的,以下是用Python实现漂浮雪花的代码:
```python
import random
import time
# 雪花的字符集合
snow_chars = ["*", ".", "+", "o", "O", "x", "X", "@"]
# 雪花的数量
snow_count = 20
# 屏幕的宽度
screen_width = 80
# 生成一个随机的雪花
def generate_snow():
return {"char": random.choice(snow_chars), "x": random.randint(0, screen_width), "y": 0}
# 初始化雪花列表
snow_list = [generate_snow() for i in range(snow_count)]
# 不断循环,更新雪花的位置,并打印出来
while True:
# 清空屏幕
print("\033[2J\033[1;1H")
# 更新每个雪花的位置
for snow in snow_list:
snow["y"] += 1
if snow["y"] >= 25:
snow["y"] = 0
snow["x"] = random.randint(0, screen_width)
print("\033[%d;%dH%s" % (snow["y"], snow["x"], snow["char"]))
# 休眠一段时间
time.sleep(0.1)
```
以上代码运行后会在命令行中显示出漂浮的雪花效果。注意在Windows下需要将`\033`替换成`\x1b`。