这几天工作不忙,回答网友问题时,整了一段键盘控制方块在linux终端移动的代码,基于Linux内核的手机与平板也可以运行。这里分享给广大C语言爱好者,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define TTY_PATH "/dev/tty"
#define STTY_US "stty raw -echo -F "
#define STTY_DEF "stty -raw echo -F "
#define EDGE_R 44 //终端右边缘
#define EDGE_B 80 //终端底边缘
int row=10,col=22; //初始化方块位置
int get_char()
{
fd_set rfds;
struct timeval tv;
int ch = 0;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 10;
if (select(1, &rfds, NULL, NULL, &tv) > 0)
{
ch = getchar();
}
return ch;
}
void Control(char input) //键盘控制模块
{
switch(input)
{
case 'w':
row-=1;
if(row<1)row=1;
break;
case 'a':
col-=2;
if(col==0)col=2;
break;
case 's':
row+=1;
if(row>EDGE_B)row=EDGE_B; //超越底边界的处理
break;
case 'd':
col+=2;
if(col>EDGE_R)col=EDGE_R; //超越右边界的处理
break;
}
}
void block(int _col,int _row)
{
printf("\033[?25l");
{
printf("\033[%d;%dH\033[41m \033[0m" , _row,_col);
fflush(stdout);
usleep(500);
printf("\033[%d;%dH \033[0m" , _row,_col);
}
}
int main()
{
system(STTY_US TTY_PATH);//开启非阻塞输入
while(1)
{
block(col,row);
char input = get_char();
Control(input);
if(input == '3') //输入数字键 “3”后,程序结束
{
system(STTY_DEF TTY_PATH);//关闭非阻塞输入
return 0;
}
}
return 0;
}
效果图: