用python写代码雨
时间: 2023-12-17 21:50:50 浏览: 85
以下是Python代码雨的示例代码:
```python
import random
import time
# 定义屏幕宽高和字符集
WIDTH = 80
HEIGHT = 25
CHARS = [' ', '.', ':', '+', '*', '?', '%', 'S', '#', '@']
# 定义雨滴类
class Drop:
def __init__(self, x, y):
self.x = x
self.y = y
self.char = random.choice(CHARS)
self.speed = random.randint(1, 5)
def fall(self):
self.y += self.speed
if self.y >= HEIGHT:
self.y = 0
self.x = random.randint(0, WIDTH)
self.char = random.choice(CHARS)
# 初始化雨滴列表
drops = []
for i in range(100):
x = random.randint(0, WIDTH)
y = random.randint(0, HEIGHT)
drop = Drop(x, y)
drops.append(drop)
# 循环打印雨滴
while True:
# 清空屏幕
print('\033[2J')
# 移动光标到左上角
print('\033[H')
# 打印雨滴
for drop in drops:
print('\033[{};{}H{}'.format(drop.y, drop.x, drop.char))
drop.fall()
# 休眠一段时间
time.sleep(0.1)
```
运行代码后,会在终端中打印出一个代码雨的效果。可以根据需要调整屏幕宽高、字符集和雨滴数量等参数。
阅读全文