利用伪双线程实现 包含光标移动 隐藏光标的实现
#include <iostream>
#include <windows.h>
#include <ctime>
#include <conio.h>
#include <list>
using namespace std;
//光标移动
void gotoxy(int x, int y)
{
HANDLE h;
COORD c;
c.X = x;
c.Y = y;
h = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(h, c);
}
//隐藏光标
void hide_cursor()
{
HANDLE h_GAME = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursor_info;
GetConsoleCursorInfo(h_GAME, &cursor_info);
cursor_info.bVisible = false;//不显示光标
SetConsoleCursorInfo(h_GAME, &cursor_info);
}
//显示光标
void show_cursor()
{
HANDLE h_GAME = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursor_info;
GetConsoleCursorInfo(h_GAME, &cursor_info);
cursor_info.bVisible = true;//不显示光标
SetConsoleCursorInfo(h_GAME, &cursor_info);
}
static int x = 10, y = 5;
class test
{
private:
int n = 5;
list<int> l{ 1,2,3,4,5 };
list<int>::iterator li ;
clock_t t,t1,t2;
public:
test() {
t = clock();
t1 = clock();
t2 = clock();
hide_cursor();
}
~test()
{
show_cursor();
}
//模拟多线程
void draw()
{
//y = 5;
for (li = l.begin();li != l.end();++li)
{
gotoxy(x, y);
y++;
cout << *li;
}
y = y - 5;
}
void erase()
{
//y = 5;
for (int i = 0; i < 5; i++)
{
gotoxy(x, y);
y++;
cout << " ";
}
y = y - 5;
}
void move()
{
while (true)
{
move1();
move2();
}
}
void move1()
{
if (clock() - t1 >= 1000)//一秒更新一次
{
erase();
l.pop_front();
l.push_back(n);
++n;
draw();
t1 = clock();
}
}
void move2()
{
if (clock() - t2 > 200)//只有读取到按键之后才更新
{
if (GetAsyncKeyState(VK_LEFT))
{
erase();
--x;
draw();
}
if (GetAsyncKeyState(VK_RIGHT))
{
erase();
++x;
draw();
}
if (GetAsyncKeyState(VK_UP))
{
erase();
--y;
draw();
}
if (GetAsyncKeyState(VK_DOWN))
{
erase();
++y;
draw();
}
if (GetAsyncKeyState(VK_ESCAPE))
{
exit(0);
}
t2 = clock();
}
}
};
int main()
{
test t;
t.move();
return 0;
}