开发者

linux terminal animation - best way to delay printing of 'frame' (in C)

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 t开发者_如何学编程he 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.


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).


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]);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜