带彩灯与装饰的 Python 圣诞树

152 阅读1分钟

代码:

import random
 def colored(text, color):
# ANSI 颜色码
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 控制装饰密度。