views:

286

answers:

3

I'm working on a simple pong clone for the terminal and need a way to delay the printing of a 'frame'.

I have a two dimensional array

screen[ROWS][COLUMNS]

and a function that prints the screen

void printScreen() {
    int i = 0;
    int j;

    while(i < ROWS) {
        j = 0;

        while(j < COLUMNS) {
            printf("%c", screen[i][j]);
            j++;
        }
        i++;
    }
}

It seems that when I do

printScreen();
usleep(1000000);
printScreen();

it will sleep the execution during printScreen().

Any tips for doing this type of animation on the terminal would be much appreciated. Maybe I'm doing this completely wrong. How is it done with ASCII movies like this?

EDIT I'm going with ncurses. Thank you both for the suggestion.

On Ubuntu sudo aptitude install libncurses5-dev and compile with -lncurses.

+2  A: 

If I understood you correctly, you need to add fflush(stdout); before returning from printScreen(). But there are much better (easier) ways of doing text animation, and terminal control. Look at ncurses for example.

Alok
+1  A: 

Ascii movies are done with aalib which works like a graphics display driver. Most people developing full fledged console apps and games use the curses framework or a version of it like ncurses. The one real restriction of going that route is you have to want the full ptty (you can't take part of it).

Evan Carroll
+3  A: 

stdout is buffered. It won't actually send the output to the terminal device until it is told to print a newline or is explicitly flushed.

To flush the output, simply add:

fflush(stdout);

Also, since all you're doing is printing a single character, printf is way overkill. You can replace your printf with:

putchar(screen[i][j]);
R Samuel Klatchko
Doh! putchar is much simpler. Thanks.
Tyler