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

南楼画角 提交于 2019-12-10 17:45:41

问题


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.


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2076380/linux-terminal-animation-best-way-to-delay-printing-of-frame-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!