Merry Christmas!一起用C语言绘制一个动态的圣诞树吧
Posted 从善若水
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Merry Christmas!一起用C语言绘制一个动态的圣诞树吧相关的知识,希望对你有一定的参考价值。
一起用C语言绘制一个动态的圣诞树吧
下面就是演示效果
动态圣诞树视频
一、实现步骤
我们利用ANSI Escape Sequences实现文字和背景颜色的绘制,之后使用系统命令定时刷新窗口并重新绘制圣诞树,以实现动态效果。相关函数如下所示:
- clrscr():用于清理窗口;
- printRandLeaf():随机化树叶的形状;
- triangle():绘制圣诞树的每一层;
- printTree():调用triangle()完成整个树冠的绘制;
- printLog():完成整个树杆的绘制;
几个关键宏含义如下:
- RefRate:圣诞树的刷新频率,越小刷新越快;
- randomness:控制树叶中‘ * ’的密度,越大密度越高;
- WIDTH_FACTOR:控制圣诞树在窗口中的位置,最小值为2。值越大越往右边偏移;
二、编码实现
// 此C程序用于生成一棵圣诞树
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define RefRate 40000
#define randomness 5 // 越高树叶越少
#define WIDTH_FACTOR 4
void clrscr()
system("@cls||clear");
void printRandLeaf()
char leaftypes[5] = '.', '*', '+', 'o', 'O' ;
int temp = rand() % randomness;
// Giving preference to *
if (temp == 1)
int other = rand() % 5;
if(other == 3)
printf("\\x1b[38;5;160m%c \\x1b[0m", leaftypes[other]);
else if(other == 2)
printf("\\x1b[38;5;226m%c \\x1b[0m", leaftypes[other]);
else
printf("%c ", leaftypes[other]);
else
printf("\\x1b[32m%c \\x1b[0m", leaftypes[1]);
void triangle(int f, int n, int toth)
int i, j, k = WIDTH_FACTOR * toth - 2;
for (i = 0; i < f - 1; i++)
k--;
// number of rows
for (i = f - 1; i < n; i++)
// space handler
for (j = 0; j < k; j++)
printf(" ");
// decrementing k after each loop
k = k - 1;
// number of columns, printing stars
for (j = 0; j <= i; j++)
printRandLeaf();
printf("\\n");
// Prints multiple triangles
void printTree(int h)
int start = 1, stop = 0, diff = 3;
while (stop < h + 1)
stop = start + diff;
triangle(start, stop, h);
diff++;
start = stop - 2;
// Prints bottom part.
void printLog(int n)
int i, j, k = WIDTH_FACTOR * n - 4;
for (i = 1; i <= 6; i++)
// space handler
for (j = 0; j < k; j++)
printf(" ");
for (j = 1; j <= 6; j++)
printf("\\x1b[38;5;58m#\\x1b[0m");
printf("\\n");
// Driver code
int main()
srand(time(NULL));
int ht = 9;
printf("\\n*********MERRY CHRISTMAS*********\\n\\n");
// refresh loop
while (1)
clrscr();
printf("\\n\\n\\n");
printTree(ht);
printLog(ht);
usleep(RefRate);
return 0;
以上是关于Merry Christmas!一起用C语言绘制一个动态的圣诞树吧的主要内容,如果未能解决你的问题,请参考以下文章
AOJ 2251 Merry Christmas (最小点覆盖)
XMLéè |Wish You A Merry Christmas !