EvilZone

Programming and Scripting => C - C++ => : Kulverstukas December 19, 2012, 07:02:52 PM

: [C] matrix effect printing text
: Kulverstukas December 19, 2012, 07:02:52 PM
A function that I made to print given text in a cool style... doesn't have a particular use, but it was fun to write it :)
Does not handle newlines so you have to give it one line at a time.

(http://i.imgur.com/F3J3U.gif)

The code is very simple as well:
: (c)
/*
  Author: Kulverstukas; http://9v.lt/

  text -- text to print;
  loops - times to loop over char
          array before putting the
          right char. Increase the
          count to increase delay.
*/
void printText(char * text, int loops) {
    // char matrix
    const char chars[52] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
                            'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k',
                            'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '1',
                            '2', '3', '4', '5', '6', '7', '8', '9', '-',
                            '=', '[', ']', ';', '/', '?', ':', '}', '{',
                            '+', '*', '0', '!', '@', '#', '\0'};

    int totalChars = strlen(text); // total chars in a given string
    int charCount = 0; // counter that keeps track of scrolling chars
    int loopCount = 0; // counter that counts loops
    char newArr[totalChars]; // new char array to build new string
    int i = 0;  // index counter, keeps track of given text index
    for (i; i <= totalChars; i++) {
        newArr[i] = text[i];
        newArr[i+1] = '\0'; // must be terminated by nullbyte, else garbage will be shown
        while (loopCount <= loops) {
            printf("%s%c\r",newArr,chars[charCount]);
            if (charCount == 51) {
                charCount = 0;
                loopCount++;
            }
            charCount++;
            int c;
            for (c = 0 ; c <= 999999; c++) {} // work emulator to delay execution
        }
        loopCount = 0;
    }
}

Usage:
: (c)
int main() {
    printText("Enter the matrix", 2);
    return 0;
}
: Re: [C] matrix effect printing text
: Polyphony December 20, 2012, 04:56:43 AM
I messed with it and toned down the mega for loop because it was lagging on my laptop, but I also changed the last char to a space, because for some reason it would print everything and then an extra '#' at the end.  Nice work Kulverstukas :) it's a neat function to put in the "c/snippets" directory lol
: Re: [C] matrix effect printing text
: Kulverstukas December 20, 2012, 05:57:06 AM
Might be issues with different compilers... I was using MinGW.
: Re: [C] matrix effect printing text
: Uriah December 20, 2012, 06:53:36 AM
This is pretty cool Kulverstukas! There are some pretty cool graphical ideas you can implement this with.
: Re: [C] matrix effect printing text
: Polyphony December 21, 2012, 06:18:48 AM
yeah, you could make a login and once you enter the right password then it could
: (c)
printText("ACCESS GRANTED");or something like that, especially if it was some software cracking challenge or something lol.
: Re: [C] matrix effect printing text
: Live Wire December 21, 2012, 07:34:16 AM
Matrix Random Character Scrolling effect.
 
:

#include <iostream.h>
 
int main(){
    int input;
    int y = 0;
    char numbers[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-=_+";
    cout << "Please enter a number: ";
    cin >> input;
    system("color 2");
   
    for (int x=0;x<=input; x++){
        system("color 5");
        cout << numbers[rand() % 78] ;
        system("color 28");
        cout << " ";   
        system("color 5");   
        cout << numbers[rand() % 78] ;
        system("color 23");
        cout << "*";
        system("color 59");
        cout << numbers[rand() % 78] ;
        system("color 71");
        if (y%7 == 1){
                 cout << "\t";
                 system("color 18");
                 y = 4;
        }else{
                 y++;
                 system("color 61");
        }
    }
   
    system("color 7");
   
    return 0;
}

this should work, at least. Oh, the colors will rape your mind.  If you want just straight up green, comment all other system("color s") but the first one, it also goes a lot faster if you do this. DO NOT WATCH WHILE HIGH!!!! YOU WILL PROBABLY DIE.
 
 
 
But Kulver, yours is cool too :)
: Re: [C] matrix effect printing text
: Kulverstukas December 21, 2012, 10:22:04 AM
derpaherp
I don't see any random characters, or any matrix, or scrolling for that matter.
Just flashes for a second in few colors and that's it...
: Re: [C] matrix effect printing text
: Live Wire December 21, 2012, 12:45:37 PM
for matrix comment out all color but the first one, and set the value to like 100000000
: Re: [C] matrix effect printing text
: Kulverstukas December 21, 2012, 01:01:27 PM
for matrix comment out all color but the first one, and set the value to like 100000000
It's still garbage because it just print random chars in a line...
: Re: [C] matrix effect printing text
: Live Wire December 21, 2012, 01:13:37 PM
It's still garbage because it just print random chars in a line...

hmm. on my pc, it scrolls fast enough that i actually get columns. anyway, just found it on my comp, and felt like sharing.
: Re: [C] matrix effect printing text
: Deque December 21, 2012, 01:35:29 PM
Useless, but funny. I have something similar from a good c coder. Just can't find it atm.
: Re: [C] matrix effect printing text
: Xires January 04, 2013, 05:14:05 PM
Nice work, Kulverstukas.  I would suggest that you look at changing the 'execution delay' loop for something that is far less resource-intensive.  Currently, it's what's known as a 'busy loop'.  This keeps the processor going and wastes energy by generating heat for no real purpose.  There are better ways to let the OS handle other process requests during this delay time so that you have a smoother experience overall.

Also, it may be to your benefit to use '++var' rather than 'var++'.  You should be familiar with the difference between the mechanics of the two but know that '++var' should never be slower than 'var++' while it could be, potentially, faster.
: Re: [C] matrix effect printing text
: Kulverstukas January 04, 2013, 05:57:24 PM
Thanks for the tips, Xires.
I tried searching for alternate solutions as I don't like the work emulating loop as well, but only way I could think of was to use Timers, and C doesn't have such stuff and I didn't find any other solutions... I'll take a look again if you say there is a better solution :)
: Re: [C] matrix effect printing text
: Xires January 05, 2013, 06:51:36 AM
C does have timers, actually.  But what you probably want to look for is some form of 'sleep' function.  There are even nanosecond resolution ones, if needed.  Even a nanosecond can provide the CPU some time to do other things.
: Re: [C] matrix effect printing text
: bluechill January 05, 2013, 05:36:26 PM
C does have timers, actually.  But what you probably want to look for is some form of 'sleep' function.  There are even nanosecond resolution ones, if needed.  Even a nanosecond can provide the CPU some time to do other things.

Kulverstukas, look up sleep().  The only timer defined by the standard is clock() but on a multithreaded system it may not be real-time as it's process time not real-time..... But that's probably good enough for what you want.
: Re: [C] matrix effect printing text
: 0poitr January 06, 2013, 03:03:58 PM
Kulverstukas, your idea is cool. I took it as inspiration and came up with another effect - random text effect :P
Here's me code ~ it does both the matrix effect and the random effect.
:
/*
Author: 0pointr
Inspired by : Kulverstukas's matrix effect program (http://evilzone.org/c-c/%28c%29-matrix-effect-printing-text/)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef unsigned int u_int;

void usage(const char *progname)
{
  puts("Usage: %s <option> <text>");
  puts("Available effects:\n\
\t-m : matrix text\n\
\t-r :random text effect");
  puts("<text> must be quoted. Multiple options can be combined.");
}

void matrix_effect(const char *buff, u_int len)
{
  const char matrix[50] = { 'm', 'a', '#', '$', 't',
                      'r', '&', '@', 'i', 'x',
                      '=', '+', '%', '~', 'q',
                      'w', 'e', 'r', 't', 'y',
                      's', 'd', 'f', 'g', 'h',
                      'h', 'j', 'k', 'l', 'z',
                      'c', 'v', 'b', 'n', 'm',
                      '1', '2', '3', '4', '5',
                      '6', '7', ':', '9', '0',
                      '#', '$', '^', '&', ' '};
  u_int i, j, b_indx=0;
  char print_str[len+1];

  for(b_indx=0U; b_indx<len; b_indx++)
  {
    print_str[b_indx] = buff[b_indx];
    print_str[b_indx+1] = '\0';

    for(i=0U; i<50U*5; i++)
    {
      printf("%s%c\r", print_str, matrix[i%50]);

      for(j=0U; j<=909000; j++) {}

    }
  }
  puts("");
}

void random_effect(const char *buff, u_int len)
{
  int rand, rand_tracker[len+1];
  u_int seed_ptr, i, j, b_indx=0, unfit, z;
  seed_ptr = 1U;
 
  char print_str[len+1];
  memset(print_str, ' ', len+1);
  print_str[len] = '\0';
  memset(rand_tracker, -1, len+1);

  for(b_indx=0U; b_indx<len; b_indx++)
  {
    while(1)
    {
  /* find a valid random index. remember, although rand_r returns
random values, the reminders might not be unique          */
      unfit=0;
      rand = rand_r(&seed_ptr) % len;
      for(j=0; j<b_indx; j++)
      {
        if(rand < 0) { unfit=1; break; }
        if(rand == rand_tracker[j]) { unfit=1; break; }
      }
      if(!unfit) { rand_tracker[b_indx] = rand; break; }
      seed_ptr++;
    }

    print_str[rand] = buff[rand];

    for(j=0U; j<50U*5; j++)
    {
      printf("%s\r", print_str);
      for(z=0U; z<=909900U; z++) {}
    }

  }
  printf("%s\n", print_str);
}

int main(int argc, char **argv)
{
  const char *buff=NULL;
  const char *progname = argv[0];

  if(argc < 2)
    usage(progname);
 
  buff = argv[argc-1];
 
  argc--;
  argv++;
  /* parse arguments */
  while(argc > 0)
  {
    if(*argv[0] == '-')
    {
      char *temp=argv[0]+1;

      switch(*temp)
      {
        case 'm':
          matrix_effect(buff, (u_int)strlen(buff));
          break;

        case 'r':
          random_effect(buff, (u_int)strlen(buff));
          break;

        default:
          usage(progname);
      }
    }
    --argc;
    ++argv;
  }


  return 0;
}
A very short video of the prog running is attached.
And btw, sleep() isn't fit for the delay needed here. It takes unsigned int as its argument, so minimum duration is 1sec which is too long for this purpose.
: Re: [C] matrix effect printing text
: Kulverstukas January 06, 2013, 05:44:12 PM
awesome! the backwards one looks sweet :)
: Re: [C] matrix effect printing text
: 0poitr January 07, 2013, 02:23:39 PM
Alright.. I wrote another effect -- its called the scrambled text effect :P
It scrambles one word at a time, displays the steps unscrambling it.
And I found a right alternative to those shit busy loops, usleep(). Lets your program wait at microsecond resolution.
Here's my code ::
:
/*
    Author: 0poitr
    Inspired by : Kulverstukas's matrix effect program (http://evilzone.org/c-c/%28c%29-matrix-effect-printing-text/)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define ABS(a) (a) < 0 ? -(a) : (a)

void usage(const char *progname, int e_code)
{
  printf("Usage: %s <option> <text>\n", progname);
  puts("Available options:\n\
\t-m : matrix text effect\n\
\t-r : random text effect\n\
\t-s : scramble text effect\n\
\t-S : speed of the effect transitions. To decrease speed specify any number < 1 as 0.n . To increase, set it to a whole number.\n\
\t     setting the speed to 0 won't have any effect.\n\
\t-h : this help text");
  puts("<text> must be quoted. Multiple options can be specified.");
  exit(e_code);
}

int get_rand_indx(int b_indx, int *rand_tracker, int len)
{
  int rand;
  static unsigned int seed_ptr = 1U;
  int unfit, j;
  if(len < 1) return 0; 
  while(1)
  {
    unfit=0;
    rand = rand_r(&seed_ptr) % len;
    for(j=0; j<b_indx; j++)
    {
      if(rand < 0) { unfit=1; break; }
      if(rand == rand_tracker[j]) { unfit=1; break; }
    }
    if(!unfit) { rand_tracker[b_indx] = rand; return rand; }
    seed_ptr++;
  }
}

void matrix_effect(const char *buff, int len, float spd)
{
  const char matrix[50] = { 'm', 'a', '#', '$', 't',
                      'r', '&', '@', 'i', 'x',
                      '=', '+', '%', '~', 'q',
                      'w', 'e', 'r', 't', 'y',
                      's', 'd', 'f', 'g', 'h',
                      'h', 'j', 'k', 'l', 'z',
                      'c', 'v', 'b', 'n', 'm',
                      '1', '2', '3', '4', '5',
                      '6', '7', ':', '9', '0',
                      '#', '$', '^', '&', ' '};
  int i, j, b_indx=0;
  char print_str[len+1];

  for(b_indx=0U; b_indx<len; b_indx++)
  {
    print_str[b_indx] = buff[b_indx];
    print_str[b_indx+1] = '\0';

    for(i=0U; i<50U*5; i++)
    {
      printf("%s%c\r", print_str, matrix[i%50]);

      usleep((unsigned)(1500/spd));

    }
  }
  puts("");
}

void random_effect(const char *buff, int len, float spd)
{
  int rand, rand_tracker[len+1];
  int i, j, b_indx=0, z;
  char print_str[len+1];

  memset(rand_tracker, -1, len+1);
  memset(print_str, ' ', len+1);
  print_str[len] = '\0';

  for(b_indx=0U; b_indx<len; b_indx++)
  {
    rand = get_rand_indx(b_indx, rand_tracker, len);
    print_str[rand] = buff[rand];
    /*printf("%s\n", print_str);
    printf("%d ", rand);*/
    for(j=0U; j<50U*5; j++)
    {
      printf("%s\r", print_str);
      usleep((unsigned)(1500/spd));
    }
  }
  printf("%s\n", print_str);
}

void scramble_effect(const char *buff, int len, float spd)
{
  int offset, offset_tracker[len+1];
  int i, j, b_indx, z;
 
  char print_str[len+1];
  memset(print_str, '\0', len+1);
  srand( time(NULL) );

  for(b_indx=0; b_indx<len; b_indx++)
  {
    memset(offset_tracker, -1, len+1);
    offset=0;
    int print_len=0U;
    while(buff[b_indx] && buff[b_indx] != ' ')
      { print_str[b_indx] = buff[b_indx++]; print_len++; }

    print_str[b_indx] = (b_indx == len) ? '\0' : ' ';
    /* Fixme: get_offset_indx() doent always get uniq val from this
       call and gets stuck in an infinite internal loop. Why?? */
    /*offset = get_offset_indx(b_indx, offset_tracker, print_len-1);*/
    offset = rand() % print_len;
    if(!offset) offset = print_len/2;

    z = b_indx-print_len;
    int init_z = z;
    while(z < b_indx)
    {
      char ch = print_str[z];
      int replace_indx = ((z+offset) % print_len) + init_z;
      print_str[z] = print_str[replace_indx];
      print_str[replace_indx] = ch;
      ++z;
    }
    z=b_indx-1;
    while(z >= init_z)
    {
      char ch = print_str[z];
      int replace_indx = (((int)z+offset) % print_len) + init_z;
     
      print_str[z] = print_str[replace_indx];
      print_str[replace_indx] = ch;
      for(j=0; j<50*3; j++)
      {
        printf("%s\r", print_str);
        usleep((unsigned)(1500/spd));
      }
      --z;
    }
  }
  printf("%s\n", print_str);
}

int main(int argc, char **argv)
{
  const char *buff=NULL;
  const char *progname = argv[0];
  const char *lastarg = argv[argc-1];
  char comm_stack[10];
  unsigned short i=0;
  float spd=1.0;

  if(argc < 3)
    usage(progname, 1);
 
  buff = argv[argc-1];
 
  argc--;
  argv++;

  while(argc > 0 && i<10)
  {
    if(*argv[0] == '-')
    {
      char *temp=argv[0]+1;

      switch(*temp)
      {
        case 'm':
          comm_stack[i++] = 'm';
          break;

        case 'r':
          comm_stack[i++] = 'r';
          break;

        case 's':
          comm_stack[i++] = 's';
          break;
       
        case 'S':
          if(*argv != lastarg)
            if(isdigit(*argv[1]))
              spd = ABS(strtof(argv[1], NULL));
            else
              usage(progname, 1);
          else
            usage(progname, 1);
          break;

        case 'h':
        default:
          usage(progname, 0);
      }
    }
    --argc;
    ++argv;
  }
  if(!spd) spd=1;
  unsigned short j=0;
  while(j < i)
  {
    switch(comm_stack[j++])
    {
      case 'm':
      matrix_effect(buff, (int)strlen(buff), spd);
      break;

      case 'r':
      random_effect(buff, (int)strlen(buff), spd);
      break;

      case 's':
      scramble_effect(buff, (int)strlen(buff), spd);
      break;
    }
  }
  return 0;
}
A short video and the c src file attached.  8)
: Re: [C] matrix effect printing text
: 0poitr January 08, 2013, 09:18:52 PM
Fuck am obsessed with this thing. Wrote three new effects:: marquee effect and two decryption effects like those they show in the movies :D

attached.

btw, Kulverstukas, you deserve a thank. You got me into this effects thing :D So, thank you.
: Re: [C] matrix effect printing text
: Kulverstukas January 08, 2013, 10:13:22 PM
haha you got some cool ones in there :D you're welcome for the inspiration...
: Re: [C] matrix effect printing text
: Deque January 10, 2013, 09:10:20 AM
Finally found it. It is written by ryoh and called eyecandy:
: (C)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#undef  LINE_MAX
#define LINE_MAX 256

char *randstring(int length);
void mutate(char *src, const char *dest);


int main(int argc, char *argv[]) {
        if(argc != 2) {
                fprintf(stderr, "Specify a file\n");
                exit(1);
        }

        FILE *fin;
        if((fin = fopen(argv[1], "r")) == NULL) {
                perror("in fopen");
                exit(1);
        }

        char *buffer;
        buffer = (char *) malloc(LINE_MAX);
        bzero(buffer, LINE_MAX);

        char temp[LINE_MAX];
        bzero(temp, LINE_MAX);
        unsigned int size = LINE_MAX-1;
        while(getline(&buffer, &size, fin) != EOF) {
                int count;
                for(count = 0; buffer[count] != '\0'; count++) {
                        if(buffer[count] == '\n')
                                continue;
                        else
                                temp[count] = buffer[count];
                }
                bzero(buffer, strlen(buffer));
                strncpy(buffer, temp, strlen(temp));
                mutate(randstring(strlen(buffer)), buffer);
                bzero(temp, strlen(temp));
                puts("");
        }
        free(buffer);
        fclose(fin);

        return 0;
}

char *randstring(int length) {
        if(length >= LINE_MAX)
                length = LINE_MAX-1;
        static char keys[] = {
                "abcdefghijklmnopqrstuvwxyz"
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                "1234567890"
        };
        static char buffer[LINE_MAX];
        bzero(buffer, LINE_MAX);
        srand(time(0));
        for(;length != 0; length--)
                strncat(buffer, &keys[rand()%strlen(keys)], 1);
        return buffer;
}

void mutate(char *src, const char *dest) {
    struct timespec slp = {0, 62500000};
    int go = 1;
    while(go) {
        if (strcmp(src, dest) == 0)
            go=0;
        printf("\r%s",src);
        int count;
        for(count = 0; src[count] != '\0'; count++) {
            if (src[count] == dest[count])
                continue;
            else if (src[count] < dest[count])
                src[count]++;
            else
                src[count]--;
        }
        fflush(stdout);
        nanosleep(&slp, NULL);
    }
}

Try it out. The effect looks a bit better, since not only the last character is switching.
: Re: [C] matrix effect printing text
: Kulverstukas January 10, 2013, 12:15:49 PM
Try it out. The effect looks a bit better, since not only the last character is switching.
Doesn't even compile with CodeBlocks+MinGW. Error on line 70:
:
variable 'slp' has initializer but incomplete type
: Re: [C] matrix effect printing text
: 0poitr January 10, 2013, 01:33:18 PM
@Deque, On line 33 you need to typecast the second param to (size_t *).
Also I'd recommend allocating memory the size of the file instead of a hard coded 256 bytes.
You can get the file size fseek -ing to SEEK_END and then ftell().

And btw, the last one of my effects is actually the same as yours - effectwise. ;)
: Re: [C] matrix effect printing text
: Deque January 11, 2013, 10:19:14 AM
@Deque, On line 33 you need to typecast the second param to (size_t *).
Also I'd recommend allocating memory the size of the file instead of a hard coded 256 bytes.
You can get the file size fseek -ing to SEEK_END and then ftell().

And btw, the last one of my effects is actually the same as yours - effectwise. ;)

It's not my code, I said that in the post.
The effect looks different to me on your video, but I might be mistaken.
: Re: [C] matrix effect printing text
: 0poitr January 11, 2013, 04:08:21 PM
@Deque err, I dint notice.