以前写过一个Window下的数字雨,像黑客帝国里那样的01数字,现在补充一版Linux下的。使用了curses库,安装方法与使用方法参照
Linux下curses函数库的详细介绍_libcurses库-CSDN博客
5-linux学习笔记之-----curses-CSDN博客
效果如下:
代码如下:
#include <time.h>
#include <curses.h>
#include <stdio.h>
#include <chrono>
#include <thread>
typedef struct //记录雨滴的结构体
{
int x;
int y;
char ch;
}RAINDROP;
const int BUFFER_SIZE = 50; //雨线数量
int WIDTH = 80;
int HEIGHT = 30;
const int RAIN_LENGTH = 18; //雨线长度
RAINDROP raindropLine[BUFFER_SIZE];
WINDOW *HOUT = initscr();//获得标准输出的句柄
int main()
{
if (has_colors() == TRUE)
{
start_color(); //初始化颜色显示
init_pair(1, COLOR_RED, COLOR_WHITE); //只能是颜色库里面8中颜色的组合
init_pair(2, COLOR_BLUE, COLOR_GREEN);
init_pair(3, COLOR_BLACK, COLOR_GREEN);
init_pair(4, COLOR_GREEN, COLOR_BLACK);
}
HEIGHT = LINES; //根据控制台的宽高设置显示的宽高
WIDTH = COLS;
noecho();
srand((unsigned int)time(NULL));
for (int i=0; i<BUFFER_SIZE; i++) //随机设置雨滴下落的位置
{
raindropLine[i].x = rand()%WIDTH;
raindropLine[i].y = rand()%HEIGHT;
raindropLine[i].ch = rand() %2 + 48; //设置雨滴内容0或1
}
while(true)
{
curs_set(0);
//GetConsoleScreenBufferInfo(HOUT, &info); //当窗体大小变化时,重新设置宽高信息
HEIGHT = LINES;
WIDTH = COLS;
for (int i=0; i<BUFFER_SIZE; ++i)
{
if (raindropLine[i].y <= HEIGHT)
{
mvaddch(raindropLine[i].y, raindropLine[i].x, raindropLine[i].ch | COLOR_PAIR(4)); //设置雨滴颜色
}
mvaddch(raindropLine[i].y - RAIN_LENGTH, raindropLine[i].x, ' ');
raindropLine[i].y++;
raindropLine[i].ch = rand() % 2 + 48;
if (raindropLine[i].y > HEIGHT + RAIN_LENGTH)
{
raindropLine[i].x = rand() % WIDTH;
raindropLine[i].y = rand() % HEIGHT;
}
if ( raindropLine[i].y <= HEIGHT)
{
mvaddch( raindropLine[i].y, raindropLine[i].x, raindropLine[i].ch | COLOR_PAIR(4) | A_BOLD); //高亮最下方的雨滴
}
}
refresh();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
getchar();
return 0;
}
编译命令
gcc main.cpp -o rain -lpthread -lcurses