需要在ubuntu系统上安装库文件,支持ncurses:
apt-get install libncurses5-dev
initscr()函数:
initscr()用于初始化ncurses数据结构并读取正确的terminfo文件。内存将被分配。
如果发生错误,initscr将返回ERR,否则将返回指针。
此外,屏幕将被删除并初始化。
getyx() 函数:
getyx() 函数可以用来取得当前光标的位置。并把它存储在传递给它的两个变量中。
在指定的坐标输出
更新终端屏幕
endwin()函数:
endwin()将清除ncurses中所有已分配的资源,并将tty模式恢复为调用initscr()之前的状态 。
必须在ncurses库中的任何其他函数之前调用它,并且必须在程序退出之前调用endwin()。
当您想要输出到多个终端时,可以使用 newterm(...)而不是initscr()。
下面的代码可以实现一个模拟的“球”在屏幕上来回反弹。
代码参考:
[https://www.viget.com/articles/game-programming-in-c-with-the-ncurses-library/]
源程序:
#include <ncurses.h>
#include <unistd.h>
#define DELAY 30000
int main(int argc, char *argv[])
{
int x = 0;
int y = 0;
int max_x = 0,max_y = 0;
int next_x = 0;
int direction = 1;
initscr(); /* 初始化屏幕 */
noecho(); /* 屏幕上不返回任何按键 */
curs_set(FALSE); /* 不显示光标 */
/* getmaxyx(stdscr, max_y, max_x);/* 获取屏幕尺寸 */
mvprintw(5, 5, "Hello, world!");
refresh(); /* 更新显示器 */
sleep(1);
while(1)
{
getmaxyx(stdscr, max_y, max_x);/* 获取屏幕尺寸 */
clear(); /* 清屏 */
mvprintw(y, x, "O");
refresh();
usleep(DELAY);
next_x = x + direction;
if(next_x >= max_x || next_x < 0)
{
direction = (-1) * direction;
}
else
{
x = x + direction;
}
}
endwin(); /* 恢复终端 */
}
Makefile:
# Makefile
cc=gcc
LDFLAGS=-lncurses
SRCS := $(wildcard *.c)
TARGET := $(SRCS:%.c=%)
$(TARGET):$(SRCS)
$(cc) $(LDFLAGS) $(SRCS) -o $(TARGET)
clean:
rm $(TARGET)