In yesterday’s post, the random rectangles are printed using console only without the help of any graphics. The basic type of each element/pixel in the console (code page 437) is defined in the following C/C++ structure:
typedef struct {
unsigned char elem;
unsigned char color;
} SCREENELEMENT;
Therefore, we can easily change the color and character of each pixel, to illustrate the ultimate color showing, we can use extended ASCII 219 to print out a solid square to the console.
const unsigned char BLACK = 219;
Now, the core statements are just a few lines:
for (;;) {
for (int i = 0; i < height; i ++) {
for (int j = 0; j < width; j ++) {
s[i][j].color = rand() % 16;
}
}
printScreen(width, height, s);
}
It gives the following output, you can use it as a screen saver (to rename the file extension from *.exe to *.scr)
The pre-compiled C++ animation application (g++ compiler/windows) can be downloaded [here
The complete C++ source code is:
/* http://HelloACM.com */
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <unistd.h> // usleep
#include <time.h> // for time
using namespace std;
const unsigned char BLACK = 219;
typedef struct {
unsigned char elem;
unsigned char color;
} SCREENELEMENT;
BOOL gotoxy(const WORD x, const WORD y) {
COORD xy;
xy.X = x;
xy.Y = y;
return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
inline // update the screen
void printScreen(int width, int height, SCREENELEMENT **screen) {
gotoxy(1, 1); // top-left corner
for (int i = 0; i < height; i ++) {
for (int j = 0; j < width; j ++) {
SCREENELEMENT *cur = &screen[i][j];
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), cur->color);
printf("%c", cur->elem); // may be faster than cout
}
}
}
inline // initialize the screen with pixel se
void initScreen(int width, int height, SCREENELEMENT **screen, SCREENELEMENT se) {
for (int i = 0; i < height; i ++) {
for (int j = 0; j < width; j ++) {
screen[i][j] = se;
}
}
}
int main() {
SetConsoleOutputCP(437);
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;
}
int height = csbi.srWindow.Bottom - csbi.srWindow.Top;
SCREENELEMENT **s = new SCREENELEMENT*[height];
for (int i = 0; i < height; i ++) {
s[i] = new SCREENELEMENT[width];
}
SCREENELEMENT se;
se.elem = BLACK;
se.color = 0;
initScreen(width, height, s, se);
srand(time(NULL));
for (;;) {
for (int i = 0; i < height; i ++) {
for (int j = 0; j < width; j ++) {
s[i][j].color = rand() % 16;
}
}
printScreen(width, height, s);
}
/* clean up */
for (int i = 0; i < height; i ++) {
delete[] s[i];
}
delete[] s;
return 0; /* use Ctrl+C, never returns */
}
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Simple C++ Animation on Console Windows - Random Squares on CodePage 437
Next Post: Modern getch() implementation on Windows C/C++