Created
January 27, 2014 01:23
-
-
Save mohd-akram/8641873 to your computer and use it in GitHub Desktop.
Matrix digital rain in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <time.h> | |
#include <windows.h> | |
#define WIDTH 80 | |
#define HEIGHT 40 | |
#define idx(x, y) ((x)+WIDTH*(y)) | |
struct trail { | |
float start; | |
float end; | |
float speed; | |
} trails[WIDTH]; | |
void init_trail(struct trail *trail) | |
{ | |
trail->start = -(float)(rand() % HEIGHT); | |
trail->end = 0; | |
trail->speed = (rand() % 5) / 10.0f + 0.2f; | |
} | |
void update(CHAR_INFO consoleBuffer[]) | |
{ | |
CHAR_INFO space = {.Char.AsciiChar=' ', .Attributes=0}; | |
for (int x = 0; x < WIDTH; x++) { | |
for (int y = 0; y < HEIGHT; y++) | |
consoleBuffer[idx(x, y)] = space; | |
int start = trails[x].start < 0 ? 0 : (int)trails[x].start; | |
int end = trails[x].end > HEIGHT ? HEIGHT : (int)trails[x].end; | |
for (int y = start; y < end; y++) | |
consoleBuffer[idx(x, y)] = (CHAR_INFO) { | |
.Char.AsciiChar = rand() % 256, | |
.Attributes = FOREGROUND_GREEN | | |
(y < (int)trails[x].end-1 ? 0 : | |
FOREGROUND_RED | FOREGROUND_BLUE)}; | |
trails[x].start += trails[x].speed; | |
trails[x].end += trails[x].speed; | |
if (trails[x].start >= HEIGHT) | |
init_trail(&trails[x]); | |
} | |
} | |
int main(void) | |
{ | |
srand((unsigned)time(NULL)); | |
/* Console window */ | |
HANDLE wHnd = GetStdHandle(STD_OUTPUT_HANDLE); | |
SMALL_RECT windowSize = {0, 0, WIDTH-1, HEIGHT-1}; | |
SetConsoleWindowInfo(wHnd, TRUE, &windowSize); | |
COORD bufferSize = {WIDTH, HEIGHT}; | |
SetConsoleScreenBufferSize(wHnd, bufferSize); | |
CHAR_INFO consoleBuffer[WIDTH * HEIGHT]; | |
COORD charBufSize = {WIDTH, HEIGHT}; | |
COORD characterPos = {0, 0}; | |
SMALL_RECT writeArea = {0, 0, WIDTH-1, HEIGHT-1}; | |
SetConsoleTitle(TEXT("Enter the Matrix")); | |
/* Trails */ | |
for (int i = 0; i < WIDTH; i++) | |
init_trail(&trails[i]); | |
/* Matrix */ | |
for (;;) { | |
update(consoleBuffer); | |
WriteConsoleOutputA(wHnd, consoleBuffer, | |
charBufSize, characterPos, &writeArea); | |
Sleep(16); | |
} | |
return 0; | |
} |
Cool! Since ima Vulcan, im gonna try it with vulcan characters!
Live Long and Prosperππππππππππ
I like it.
So good! Going to study the code and replicate it many times!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, I needed something like that to show when somebody divide by 0 in a simple calculator exercise i'm doing. Thanks