アドベントカレンダーの最終日にふさわしいプログラムを作成することにした。
オーナメントのついたクリスマスツリーが出力される。
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
// ANSI color codes
const string GREEN = "\033[32m";
const string RED = "\033[31m";
const string YELLOW = "\033[33m";
const string CYAN = "\033[36m";
const string RESET = "\033[0m";
const string BOLD = "\033[1m";
// Random ornament
string ornament() {
static vector<string> o = {RED + "o" + RESET, YELLOW + "*" + RESET,
CYAN + "@" + RESET};
return o[rand() % o.size()];
}
int main() {
srand(static_cast<unsigned>(time(nullptr)));
const int height = 14;
const int width = height * 2;
// Star
cout << string(width / 2 - 1, ' ') << BOLD << YELLOW << "★" << RESET << "\n";
// Tree body
for (int i = 0; i < height; i++) {
int leaves = i * 2 + 1;
int padding = (width - leaves) / 2;
cout << string(padding, ' ');
for (int j = 0; j < leaves; j++) {
if (i > 2 && rand() % 7 == 0) {
cout << ornament();
} else {
cout << GREEN << "^" << RESET;
}
}
cout << "\n";
}
// Trunk
for (int i = 0; i < 3; i++) {
cout << string(width / 2 - 1, ' ') << BOLD << "\033[38;5;94m" << "|||"
<< RESET << "\n";
}
// Message
cout << "\n"
<< BOLD << RED << "Merry " << GREEN << "Christmas" << RED << " & "
<< CYAN << "Happy Coding!" << RESET << "\n";
return 0;
}