键盘交互:程序运行后,通过键盘,输入数据,控制对象变化,控制程序流程
还有鼠标(触屏)交互,菜单(按钮)交互,对话框交互
程序结构
While(true)
{
绘制图形
延时
清除图形
坐标变换
}
1.小球字符的打印,小球字符是Windows里的一个特殊字符,可以在word文档里选择插入-符号,然后拷贝到程序里
2.延时:_sleep(time)是window里的系统函数,可以直接调用,time的单位是毫秒,在延时的时间里程序是没有运行的(独占系统资源),影响程序的执行效率
3.边界控制:
x++;if(x>77)x=0;等价于x++;x=x%77;
**按键动作判断所用到的函数kbhit();(需要头文件“conio.h")**c
#include <iostream>
#include <windows.h>
#include <conio.h>
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 move(int x0,int y0)
{
int x=x0,y=y0;
while(!kbhit())
{
gotoxy(x,y);
cout<<"●";
_sleep(10);//运行时sleep独占系统,其余程序是无法进行的
gotoxy(x,y);
cout<<" ";
++x;
x=x%77;
}
}
int main()
{
move(0,10);
}
****接收键盘码getch()需要头文件“conio.h”****
#include <windows.h>
#include <conio.h>
using namespace std;
int main()
{
char c;
c=getch();
cout<<(int)c<<endl;//输出键盘码
return 0;
}
注意:字母键,数字键只有一个键盘码。而有些常用的控制键有两个键盘码如四个方向键
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main()
{
char c1,c2;
c1=getch();
c2=getch();
cout<<(int)c1<<endl;
cout<<(int)c2<<endl;
return 0;
}
如果按下任意一个方向键就可以显示出两个键盘码了
所以在用控制键进行交互的时候一定要弄清键盘码
键盘控制小动画:用方向键控制小球在屏幕上移动,ESC键退出
动画的基础逻辑
While(true)
{
绘制图形
接收键盘码(ESC键退出)
清除图形
坐标变换
}
#include <iostream>
#include <windows.h>
#include <conio.h>
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 move(int x0,int y0)
{
char c1,c2;
int x=x0,y=y0;
while(true)
{
gotoxy(x,y);//绘制图形
cout<<"●";
c1=getch();//接收键盘码
if(c1==27)break;//如果是esc键的话,跳出循环
if(c1==-32)//如果是方向键的键盘码
{
gotoxy(x,y);
cout<<" ";//清除图形
c2=getch();
switch(c2)
{
case 72:--y;break;//向上
case 80:++y;break;//向下
case 75:--x;break;//向左
case 77:++x;break;//向右 坐标原点在左上角
}
}
}
}
int main()
{
move(10,10);
}
后来用函数改写
#include <iostream>
#include<ctime>
#include<cstdlib>
#include<conio.h>
#include<windows.h>
using namespace std;
class Move
{
private:
int x,y;
public:
Move()
{
x=30;
y=40;
}
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 draw()
{
gotoxy(x,y);
cout<<"●";//注意●在使用时要用“”括起来
}
void clear()
{
gotoxy(x,y);
cout<<" ";
}//注意函数的()一定要写完整那个,否则在在此后的函数都无法使用
void move()
{
char c1,c2;
draw();//初始化
while(true)
{
c1=getch();
if(c1==27) break;
if(c1==-32)
{
clear();
c2=getch();
switch(c2)
{
case 75:x=x-1;break;
case 77:x=x+1;break;
}
draw();
}
}
}
};
int main()
{
Move m;//擦除小球要用到两个空格
m.move();
return 0;
}