Ubuntu 下C++数字雨

以前写过一个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

相关推荐
沐怡旸17 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41621 小时前
Javer 学 c++(十三):引用篇
c++·后端
轻松Ai享生活1 天前
5 节课深入学习Linux Cgroups
linux
感哥1 天前
C++ std::set
c++
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
christine-rr1 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神5551 天前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆1 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
博笙困了1 天前
AcWing学习——差分
c++·算法
乌萨奇也要立志学C++1 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器