c - how to program a terminal matrix effect? -
i have made code produce raining matrix effect in terminal:
#include <stdio.h> #include <stdlib.h> int main(){ char characters [83] = {'a', ' ', 'b', 'c', ' ', 'd', 'e', ' ', 'f', 'g', ' ', 'h', 'i', ' ', 'j', 'k', 'l', ' ', 'm', 'n', 'o', ' ', 'p', 'q', 'r', 's', 't', 'u', 'v', ' ', 'w', 'x', 'y', 'z', 'a', ' ', 'b', 'c', 'd', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 'm', ' ', 'n', 'o', 'p', 'q', 'r', ' ', 's', 't', 'u', ' ', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', ' ', '9', '!', '%', '&', ' ', '?', '#', '*'}; int = 0; int index_array; srand(time(0)); struct timespec tim, tim2; tim.tv_sec = 0; tim.tv_nsec = 10000000l; (i=0; < 20; i++){ index_array = (rand()%83)+1; printf("%c", characters[index_array]); nanosleep(&tim, &tim2); } printf("\n"); main(); }
but have problems:
1.) code prints 20 chars @ once , wait nanosleep()
, not every character single , wait nanosleep()
before printing next character...
hope can me , question not silly... thanks.
the reason see 20 characters @ once program (or c runtime runs under hood) buffers standard output stream. when gets newline, or when buffer full, pass buffer content along stream. call buffer flushing. there's library function can use force flushing: fflush()
. need put behind printf statement: fflush(stdout);
the next issue see code calculate random index between 1 , 83. array hold 83 characters, means proper index should between 0 , 82.
last not least first see calling main() recursively mimic endless loooop. no practice because program start bloating up, , clobbering whole memory, causing computer crash... wait. didn't intend that, did you? ;) however, use loop (not crash of course.)
Comments
Post a Comment