代码:
import random
def colored(text, color):
colors = {
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"blue": "\033[94m",
"purple": "\033[95m",
"cyan": "\033[96m",
"reset": "\033[0m"
}
return colors[color] + text + colors["reset"]
def print_tree(height=8,彩灯_density=0.15):
print(" " * (height - 1) + colored("★", "yellow"))
for i in range(height):
spaces = " " * (height - i - 1)
stars = "*" * (2 * i + 1)
chars = list(stars)
for j in range(len(chars)):
if random.random() < 彩灯_density:
color = random.choice(["red", "yellow", "blue", "purple", "cyan"])
chars[j] = colored("●", color)
print(spaces + "".join(chars))
trunk_width = 3
trunk_height = 2
for _ in range(trunk_height):
print(" " * (height - trunk_width // 2 - 1) + colored("|" * trunk_width, "green"))
if name == "main":
print_tree(height=8, 彩灯_density=0.15)
运行结果(示例,彩灯位置随机):
★
●
★
●●
●
*★●★
●●*****
★●●**
| |
| |
说明:
- 终端支持
ANSI 颜色时,星星与彩灯会显示彩色;若不支持,仍可正常显示为文本。
- 调整
height 可改变树的大小,彩灯_density 控制装饰密度。