Merry Christmas 圣诞树html+css+js,c++,python实现

✍蹭蹭热度,探索csdn平台的流量密码
💡项目均来源于github平台,非个人创作
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

html+css+js

repo:https://github.com/anvaka/atree
在这里插入图片描述

The tree is built of two spirals. These 11 lines of code render one line on spiral. It includes 3d projection and background shadow. Almost the same as this wiki image:
·

在这里插入图片描述

充分诠释数学的简洁之美。

repo:https://github.com/hakimel/DOM-Tree
请添加图片描述
请添加图片描述

C++

请添加图片描述
编译命令

g++-9 -O2 tree.cpp -std=c++17 -pthread && ./a.out xtree.txt
# g++-7已经启用,改为g++-9
sudo apt-get install g++-9
// Copyright (c) 2018 Antony Polukhin.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)


// TODO:
//  * clean up the mess in code
//  * clean up after the cleanup
//  * add falling snow or glowing stars
//  * more modes for lamps

#include <cstdlib>
#include <chrono>
#include <thread>
#include <iostream>
#include <random>
#include <iterator>
#include <fstream>
#include <algorithm>
#include <atomic>

enum class color_t : unsigned char {};
constexpr color_t operator"" _c(unsigned long long int v) { return color_t(v); }

std::ostream& operator<< (std::ostream& os, color_t val) {
  return os << "\033[38;5;" << static_cast<int>(val) << 'm';
}

struct green_state {
  color_t color() const {
    return *(std::min(std::begin(kGreenColors) + dark, std::end(kGreenColors) - 1));
  }

  void increase_darkness() { ++dark; }
  void reset_darkness() { dark = 0; }

private:
  constexpr static color_t kGreenColors[] = { 22_c, 22_c, 28_c, 28_c, 34_c };
  int dark = 0;
};

struct lamps {
  void operator()(char c) {
    if (mode % max_state == 0)
      new_color();
    std::cout << col << c;
  }

  void end_cycle() {
    if (mode % max_state == 1) {
      new_color();
    } else if (mode % max_state == 2) {
      auto i = static_cast<int>(col);
      ++i;

      i %= 226;
      i = std::clamp(i, 154, 226);

      //i %= 202;
      //i = std::clamp(i, 196, 202);
      col = static_cast<color_t>(i);
    }
  }

  void change_mode() {
    ++mode;
  }

  void stop() {
    stopped = true;
  }

  bool was_stopped() {
    return stopped;
  }

private:
  void new_color() {
    std::sample(std::begin(kPrettyColors), std::end(kPrettyColors), &col, 1, rand);
  }

  std::atomic<bool> stopped = false;
  std::atomic<size_t> mode{0};
  static constexpr size_t max_state = 3;
  std::mt19937 rand{std::random_device{}()};
  color_t col = 0_c;

  // https://misc.flogisoft.com/bash/tip_colors_and_formatting
  static constexpr color_t kPrettyColors[] = {
    1_c, 9_c, 11_c, 15_c, 45_c, 87_c, 118_c, 154_c, 155_c, 165_c, 193_c, 196_c, 198_c,208_c, 226_c, 15_c
  };
};

std::string get_tree(int args, const char** argv) {
  std::string filename = "xtree.txt";
  if (args > 1) {
    filename = argv[1];
  }

  std::string tree;
  std::ifstream ifs{filename.c_str()};
  std::getline(ifs, tree, '\0');
  return tree;
}

int main(int args, const char** argv) {
  using namespace std::literals::chrono_literals;

  auto tree = get_tree(args, argv);
  lamps lamp;

  std::thread t([&lamp]() {
    char c;
    while (std::cin >> c) {
      if (c == 'q') {
        lamp.stop();
        break;
      }
      lamp.change_mode();
    }
  });

  for (;;) {
    if (lamp.was_stopped()) {
      break;
    }

    std::system("clear");

    green_state g;
    auto it = tree.begin();
    auto end = tree.end();
    auto prev_width = 0;
    for (; it != end; ++it) {
      const auto c = *it;
      switch (c) {
      case '*': [[fall_through]]
      case ' ':
        std::cout << g.color() << c;
        break;

      case 'o': [[fall_through]]
      case 'O':
        lamp(c);
        break;

      case '#':
        std::cout << 94_c << c;
        break;

      case '\n': {
          const auto next_new_line = std::find(it + 1, end, '\n');
          const auto new_width = std::count_if(
              it,
              next_new_line,
              [](char s) { return s == '*' || s == 'o' || s == 'O'; }
          );
          if (prev_width < new_width) {
            g.increase_darkness();
          } else {
            g.reset_darkness();
          }
          prev_width = new_width;
        }
        [[fall_through]]

      default:
        std::cout << 0_c << c;
      }
    }

    std::cout << 0_c << std::endl;
    lamp.end_cycle();
    std::this_thread::sleep_for(400ms);
  }

  t.join();
}

python

请添加图片描述
在终端运行:

python terminal_tree.py
import argparse
import os
import random
import time

BALL = '⏺'
COLOR = {
    'blue': '\033[94m',
    'yellow': '\033[93m',
    'cyan': '\033[96m',
    'green': '\033[92m',
    'magenta': '\033[95m',
    'white': '\033[97m',
    'red': '\033[91m'
}
STAR = '★'


def random_change_char(string, value):
    indexes = random.sample(range(0, len(string)), value)
    string = list(string)
    for idx in indexes:
        if string[idx] != ' ' and string[idx] == '_':
            string[idx] = BALL
    return ''.join(string)


def tree(height=13, screen_width=80):
    star = (STAR, 3*STAR)
    if height % 2 != 0:
        height += 1
    body = ['/_\\', '/_\_\\']
    trunk = '[___]'
    begin = '/'
    end = '\\'
    pattern = '_/'
    j = 5
    for i in range(7, height + 1, 2):
        middle = pattern + (i - j) * pattern
        line = ''.join([begin, middle[:-1], end])
        body.append(line)
        middle = middle.replace('/', '\\')
        line = ''.join([begin, middle[:-1], end])
        body.append(line)
        j += 1

    return [line.center(screen_width) for line in (*star, *body, trunk)]


def balls(tree):
    for idx, _ in enumerate(tree[:-3], 2):
        tree[idx] = random_change_char(tree[idx], len(tree[idx])//8)
    return tree


def colored_stars_balls(tree):
    for idx, _ in enumerate(tree):
        string = list(tree[idx])
        for pos, _ in enumerate(string):
            if string[pos] == STAR:
                string[pos] = ''.join([COLOR['yellow'], STAR, '\033[0m'])
            elif string[pos] == BALL:
                string[pos] = ''.join([random.choice(list(COLOR.values())), BALL, '\033[0m'])
        tree[idx] = ''.join(string)
    return tree


def cli():
    parser = argparse.ArgumentParser(prog="Python Christmas Tree by Chico Lucio from Ciencia Programada",
                                     epilog="Ctrl-C interrupts the Christmas :-(")
    parser.add_argument('-s', '--size', default=13, type=int,
                        help="Tree height. If even it will be subtracted 1. If less than 7, considered 5. Default: 13")
    parser.add_argument('-w', '--width', default=80, type=int,
                        help="Screen width. Used to center the tree. Default: 80")
    parser.add_argument('-t', '--terminal', action='store_true',
                        help="Uses the terminal size to center the tree. -s and -w will be ignored")
    args = parser.parse_args()

    if args.terminal:
        screen_width, height = os.get_terminal_size()
        height -= 2
    else:
        height = args.size
        screen_width = args.width
    while True:
        try:
            time.sleep(random.uniform(.1, 1))
            os.system('cls' if os.name == 'nt' else 'clear')
            print('\n'.join(colored_stars_balls(balls(tree(height, screen_width)))))
        except KeyboardInterrupt:
            os.system('cls' if os.name == 'nt' else 'clear')
            print(f"\n{'Merry Christmas!!':^{screen_width}}", end='\n\n')
            break


if __name__ == '__main__':
    cli()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u小鬼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值