可以生成一个闪缩的圣诞树哦,祝大家圣诞节快乐。
?
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RED FOREGROUND_RED | FOREGROUND_INTENSITY
#define GREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
#define YELLOW (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY)
#define BLUE FOREGROUND_BLUE | FOREGROUND_INTENSITY
#define WHITE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
#define RESET FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
void setColor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void sleepMillis(int millis) {
Sleep(millis);
}
void clearScreen() {
system("cls");
}
int main() {
srand(time(NULL));
int height = 10; // 圣诞树的高度
int blinkRate = 500; // 闪耀频率(毫秒)
while (1) {
clearScreen();
for (int i = 1; i <= height; i++) {
int spaces = height - i;
int stars = 2 * i - 1;
// 打印空格
setColor(RESET);
for (int j = 0; j < spaces; j++) {
printf(" ");
}
// 打印彩色星号
for (int j = 0; j < stars; j++) {
int color = rand() % 4;
if (color == 0) {
setColor(RED);
} else if (color == 1) {
setColor(GREEN);
} else if (color == 2) {
setColor(YELLOW);
} else {
setColor(BLUE);
}
printf("*");
}
printf("\n");
}
// 打印树干
setColor(RESET);
for (int i = 0; i < height - 1; i++) {
printf(" ");
}
printf("|\n");
// 闪耀效果
sleepMillis(blinkRate);
}
return 0;
}