The Matrix Printing Animation in C++


<The Matrix> is a great movie, and I am sure that you must be a aware of the following screenshot.

the-matrix The Matrix Printing Animation in C++

So Let’s make something similar (of course without any PS or decent coding it may not look so good).

matrix The Matrix Printing Animation in C++

The above Win32 executable (matrix.exe) can be downloaded at here. The Matrix in C++ The Matrix Printing Animation in C++ It was compiled at G++ 4 (codeblocks). The following is the C++ code that you can freely modify to suit your needs.

#include <iostream>
#include <windows.h>
#include <unistd.h>

using namespace std;

#define BLACK 0
#define BLUE 1
#define GREEN 2
#define CYAN 3
#define RED 4
#define MAGENTA 5
#define BROWN 6
#define LIGHTGREY 7
#define DARKGREY 8
#define LIGHTBLUE 9
#define LIGHTGREEN 10
#define LIGHTCYAN 11
#define LIGHTRED 12
#define LIGHTMAGENTA 13
#define YELLOW 14
#define WHITE 15
#define BLINK 128

inline
char getChar() {
    int x = rand() % 4;
    switch (x) {
        case 0: return (char)(48 + rand() % 10);
        case 1: return (char)(97 + rand() % 26);
        case 2: return 32;
        default: return (char)(65 + rand() % 26);
    }
}

int main()
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    int ret;
    /* get the width of the console */
    ret = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&csbi);
    int width = 80;
    if(ret)
    {
        width = csbi.dwSize.X;
    }
    for (;;) {
        for (int i = 0; i < width; i ++) {
            /* set text color */
            if (rand() & 1) {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), GREEN);
            } else {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WHITE);
            }
            cout << getChar(); // print a digit, uppercase or lowercase
        }
        usleep(20000);
    }
    return 0;
}

You may try to change the random character pattern and try to print them in blocks.

The only thing new in the C++ code is the usage of GetConsoleScreenBufferInfo and SetConsoleTextAttribute which gets the size of the console and sets the text color, respectively.

–EOF (The Ultimate Computing & Technology Blog) —

380 words
Last Post: The 8 bit DOS by Famicom Clone - BBGDOS in the 1990s
Next Post: Simple C/C++ Rocket Animation

The Permanent URL is: The Matrix Printing Animation in C++ (AMP Version)

Leave a Reply