可交互彩色圣诞树🎄c++代码

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// 颜色控制宏(Windows用SetConsoleTextAttribute,Linux用ANSI转义)
#ifdef _WIN32
#include <windows.h>
#define SET_COLOR(c) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c)
#else
#define SET_COLOR(c) cout << "\033[" << c << "m"
#endif

int main() {
    srand((unsigned int)time(0)); // 随机种子(雪花位置随机)
    int height;

    // 交互输入高度
    cout << "请输入圣诞树高度(建议5-20):";
    cin >> height;
    while (height < 5 || height > 20) {
        cout << "高度需在5-20之间,请重新输入:";
        cin >> height;
    }

    // 绘制顶部星星
    SET_COLOR(14); // 亮黄色
    for (int i = 0; i < height - 1; i++) cout << " ";
    cout << "★" << endl;

    // 绘制彩色树冠+随机雪花
    for (int i = 0; i < height; i++) {
        // 前置空格(居中)
        for (int j = 0; j < height - i - 1; j++) {
            // 随机雪花(白色,10%概率)
            if (rand() % 10 == 0) {
                SET_COLOR(7);
                cout << "❄";
            } else cout << " ";
        }
        // 彩色树冠(红/绿/黄交替)
        for (int k = 0; k < 2 * i + 1; k++) {
            int color = 2 + rand() % 3; // 2=绿色,3=蓝色,4=红色
            SET_COLOR(color);
            cout << (rand() % 5 == 0 ? "●" : "*"); // 随机点缀小圆点
        }
        cout << endl;
    }

    // 绘制棕色树干
    SET_COLOR(6); // 棕色
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < height - 2; j++) cout << " ";
        cout << "███" << endl;
    }

    // 恢复默认颜色
    SET_COLOR(7);
    cout << endl;
    return 0;
}

 

请登录后发表评论

    没有回复内容