fork download
  1. import random
  2. import time
  3.  
  4. # ANSI 颜色代码
  5. GREEN = '\033[32m'
  6. RED = '\033[31m'
  7. YELLOW = '\033[33m'
  8. BLUE = '\033[34m'
  9. PURPLE = '\033[35m'
  10. CYAN = '\033[36m'
  11. RESET = '\033[0m'
  12.  
  13. def draw_tree(height=15):
  14. """绘制彩色圣诞树"""
  15. print(GREEN)
  16. # 树冠(三角形)
  17. for i in range(height):
  18. # 计算每行的空格数和星号数
  19. spaces = " " * (height - i - 1)
  20. # 树的主体用绿色星号
  21. stars = GREEN + "*" * (2 * i + 1) + RESET
  22.  
  23. # 随机在树冠上添加彩色装饰球
  24. tree_line = list(stars)
  25. for j in range(len(tree_line)):
  26. # 如果是星号,有一定概率替换为彩色装饰
  27. if tree_line[j] == '*' and random.random() < 0.1:
  28. color = random.choice([RED, YELLOW, BLUE, PURPLE, CYAN])
  29. tree_line[j] = color + 'o' + RESET
  30. print(spaces + ''.join(tree_line))
  31.  
  32. # 树干
  33. trunk_height = 3
  34. trunk_width = 3
  35. for _ in range(trunk_height):
  36. print(" " * (height - trunk_width) + "|" * (trunk_width * 2 - 1))
  37.  
  38. # 树顶星星
  39. print(" " * (height - 1) + YELLOW + "★" + RESET)
  40.  
  41. # 直接运行
  42. draw_tree(15)
Success #stdin #stdout 0.07s 14396KB
stdin
Standard input is empty
stdout

              *
             ***
            ****o
           *******
          *o**o****
         *o*********
        *************
       ***************
      *****o****o**o***
     ********o**********
    *****o*************o*
   ***o*******o**o*oo*****
  ************oo***********
 ****oo*****o**o*o***o******
o**************o***o*********
            |||||
            |||||
            |||||
              ★