#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
void gotoxy(int x,int y){
COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}
char ch='O',c;
short x=13,y=40,face;
int main()
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut, &cci);
cci.bVisible = FALSE;
SetConsoleCursorInfo(hOut, &cci); //以上5行去除光标显示
gotoxy(y,x);
cout<<ch;
while(1) {
if (c=getch()) {
gotoxy(y,x);cout<<' ';
if (c=='w') {x--;face=1;}
if (c=='s') {x++;face=3;}
if (c=='a') {y--;face=4;}
if (c=='d') {y++;face=2;}
gotoxy(y,x);cout<<ch;
_sleep(200);
}
while (!kbhit()) {
gotoxy(y,x);cout<<' ';
if (face==1) x--;
if (face==2) y++;
if (face==3) x++;
if (face==4) y--;
gotoxy(y,x);cout<<ch;
_sleep(200);
}
}
return 0;
}
kbhit()在执行时,检测是否有按键按下,有按下返回非0值,没有按下则返回0,是非阻塞函数;
不同于getch()的在执行时,检测按下什么键,如果不按键该函数不返回,也就不进行下一步操作,是阻塞函数。