键盘交互与计时器-容器
模拟一个办事机构(如银行)的叫号程序。
在一个显示区域内从上到下按顺序显示5个号码,最开始是1-5。四个方向键控制显示区域的移动。空格键产生一个新号码,将最前面的号码挤出显示区。ESC键退出系统。
使用键盘交互与计时器实现该程序,使用容器装载号码。
老师不讲容器还布置这种作业,害的我还得看隔壁班老师的网课。
分析:就是双线程+迭代器。然后用隐藏光标和光标函数实现移动效果。
改进 ://用cls清屏效果比较差,会闪屏。但我还没找到替代方法,凑合用吧。有人说用光标函数定位输出空格效果更好,但我还是会闪屏。gotoxy(0,0)会bug…
闪屏是因为当初没把线程闭环…顺便发现用了sleep后就不闪了,就算用cls也不闪了很神奇()。
代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <list>
#include <conio.h>
#include <windows.h>
#include <stdio.h>
using namespace std;
class test
{
private:
int temp;
list<int>a;
list<int>::iterator p;
int x,y;
clock_t t1,t2;
public:
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);
}
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 browse1(){cout<<"======================"<<endl;
}
void browse2(){
p=a.begin();
cout<<*p<<endl;
}
void browse3(){
p++;
cout<<*p<<endl;
}
void browse4(){
p++;
cout<<*p<<endl;
}
void browse5(){
p++;
cout<<*p<<endl;
}
void browse6(){
p++;
cout<<*p<<endl;
}
test(int xx,int yy,int t)
{x=xx;
y=yy;
temp=t;
for(int i=0;i<5;++i)
{temp=temp+1;
a.push_back(temp);}
hide_cursor();}
void draw1(int x,int y){
gotoxy(x,y);
browse1();
}
void draw2(int x,int y){
gotoxy(x,y+1);
browse2();}
void draw3(int x,int y){
gotoxy(x,y+2);
browse3();
}
void draw4(int x,int y){
gotoxy(x,y+3);
browse4();
}
void draw5(int x,int y){
gotoxy(x,y+4);
browse5();
}
void draw6(int x,int y){
gotoxy(x,y+5);
browse6();
}
void draw7(int x,int y){
gotoxy(x,y+6);
browse1();
}
~test(){
show_cursor();
}
void erase(int x,int y){
gotoxy(x,y);
system("cls");//用cls清屏效果比较差,会闪屏。但我还没找到替代方法,凑合用吧。有人说用光标函数定位输出空格效果更好,但我还是会闪屏。gotoxy(0,0)会bug…
}
void move1()//实现显示区域移动
{
erase(x,y);
if(clock()-t1>100){
if(GetAsyncKeyState(VK_LEFT))
{--x;
if(x<=0)x=0;
}
if(GetAsyncKeyState(VK_RIGHT))
{++x;
if(x>=78)x=78;
}
if(GetAsyncKeyState(VK_UP))
{--y;
if(y<=0)y=0;
}
if(GetAsyncKeyState(VK_DOWN))
{++y;
if(y>=78)y=78;
}
draw1(x,y);
draw2(x,y);
draw3(x,y);
draw4(x,y);
draw5(x,y);
draw6(x,y);
draw7(x,y);
t1=clock();
sleep(200);//用了sleep就不闪了。
}
}
void move2()//实现显示区域内数字迭代
{ if(clock()-t2>200)
{
if(GetAsyncKeyState(VK_ESCAPE)) {
cout<<"exit"<<endl;exit(0);
}
if(GetAsyncKeyState(VK_SPACE))
{
if(a.size()!=0)
{
p=a.begin();
a.erase(p);
a.push_back(++temp);
}
}t2=clock();
}
}
void move(){
while(1){
move1();
move2();
}
}
};
int main()
{
test t(10,0,0);
t.move();
return 0;
}