通过对windows.h中的光标的使用可以简单实现控制一个物体的移动,以下代码为控制一个小飞机的移动
其中的_getch()函数的作用是从控制台中获取键盘输入的字符。其头文件为conio.h
#include<iostream>
#include<windows.h>
#include<conio.h>
using namespace std;
void gotoxy(HANDLE hOut, int x, int y)
{
COORD pos;
pos.X = x; //横坐标
pos.Y = y; //纵坐标
SetConsoleCursorPosition(hOut, pos);
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//定义显示器句柄变量
class Plane
{
public:
//消除移动前的图像
void before_move(int x,int y)
{
gotoxy(hOut, x, y);
cout << " " << endl;
gotoxy(hOut, x, y + 1);
cout << " " << endl;
}
//显示移动后的图像
void later_move(int x, int y)
{
gotoxy(hOut, x, y);
cout << " #" << endl;
gotoxy(hOut, x, y + 1);
cout << "###" << endl;
}
};
void HideCursor();
int main()
{
HideCursor();//隐藏光标
int x = 0;
int y = 0;
Plane plane;
plane.later_move(x, y);
while (1)
{
char move = _getch();
plane.before_move(x, y);
switch (move)//判断上下移动
{
case 'w':y -= 1; if (y < 0)y = 0; break;
case 's':y += 1; break;
case 'a':x -= 1; if (x < 0)x = 0; break;
case 'd':x += 1; break;
default:break;
}
plane.later_move(x, y);
}
return 0;
}
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
下面一段代码的作用是把光标移动到(x,y)位置处,其中坐标的原点在最左上角
void gotoxy(HANDLE hOut, int x, int y)
{
COORD pos;
pos.X = x; //横坐标
pos.Y = y; //纵坐标
SetConsoleCursorPosition(hOut, pos);
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//定义显示器句柄变量
下面一段代码的作用是隐藏光标使程序运行更加美观
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}