本人小白 想编一个简单的贪吃蛇游戏 但不知道怎么从键盘获取方向键 求教 最好有列子
获得键盘信息的话,需要调用库的。一般做这种东西都话,C++在QT或者VS上都是可以做的。这些都是有自己的关于键盘和鼠标的各种函数库的。要是不知道的话,还是用楼上的方法,通过字符串或者是数字来控制移动
可以用kbhit()和getch()函数来做,举个例子:
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
#define up 'w'
#define down 's'
#define right 'd'
#define left 'a'
int main(){
while(1){
if(kbhit()){
char a=getch();
switch(a){
case up:
cout<<"上"<<endl;
break;
case down:
cout<<"下"<<endl;
break;
case right:
cout<<"右"<<endl;
break;
case left:
cout<<"左"<<endl;
break;
case 27:
exit(0);
}
}
}
}
C++可以使用如下方式输入字符串:
1、使用cin>>操作符:
1 2 3 4 5 6 7 8
#include
using namespace std;
void main(){
char s[50];//字符数组,用于存放字符串的每一个字符
cout<<"Please input a string"<<endl;
cin>>s; //输入字符串
cout<<"The string you input is"<<s<<endl;
}
2、使用cin.get函数:
1 2 3 4 5 6 7 8
#include
using namespace std;
void main(){
char s[50];//字符数组,用于存放字符串的每一个字符
cout<<"Please input a string"<<endl;
cin.get(s,50);//输入字符串,当输入是Enter键时结束输入
cout<<"The string you input is:"<<s<<endl;
}