请高手指教:用c语言写了个贪吃蛇,但每按下方向键就必须按一下回车,不然就停在原地不走;

#include<graphics.h>#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<time... #include<graphics.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
#define N 200
#define LEFT 'a'
#define RIGHT 'd'
#define UP 'w'
#define DOWN 's'
#define ESC 027
struct Snake{
int x[N];
int y[N];
int life;
int d; // 方向
int node; // 节数
}snake;
struct Food{
int x;
int y;
int flag; // flag==1表示需要出现食物
}food;

int i;
char key;
void Init(void) /* 图形初始化 */
{
int gd=9,gm=2;
initgraph(&gd,&gm," ");
cleardevice();
}
void draw() /* 画墙(50,40,610,460) */
{
setcolor(YELLOW);
rectangle(50,40,610,460);
}
void play()
{
srand(time(NULL));
food.flag =1;
snake.life=0;
snake.d=6;
snake.node=2;
snake.x[0]=100;snake.y[0]=100;
snake.x[1]=110;snake.y[1]=100;
while(1){
while(!kbhit()){
if(food.flag==1)
do{
food.x=rand()%400+60;
food.y=rand()%350+60;
food.flag=0;
}while((food.x%10!=0)||(food.y%10!=0));
if(food.flag==0)
{
setcolor(GREEN);
rectangle(food.x,food.y,food.x+10,food.y-10);
}

for(i=snake.node-1;i>0;i--){ //向前移动
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
if(snake.d==6)
snake.x[0]=snake.x[0]+10;
else if(snake.d==4)
snake.x[0]=snake.x[0]-10;
else if(snake.d==8)
snake.y[0]=snake.y[0]-10;
else if(snake.d==2)
snake.y[0]=snake.y[0]+10;
/* 咬自己 */
for(i=3;i<snake.node;i++)
if((snake.x[i]==snake.x[0])&&(snake.y[i]==snake.y[0])){
snake.life=1;
break;
}

/* 穿墙 */
if(snake.x[0]<50)
snake.x[0]+=540;
if(snake.x[0]>590)
snake.x[0]-=550;
if(snake.y[0]>450)
snake.y[0]-=410;
if(snake.y[0]<50)
snake.y[0]+=410;

if(snake.life==1)
break;
/* 吃到食物 */
if((snake.x[0]==food.x)&&(snake.y[0]==food.y)){
setcolor(BLACK); //覆盖食物
rectangle(food.x,food.y,food.x+10,food.y-10);
// snake.x[snake.node]=-20;
// snake.y[snake.node]=-20;
snake.node++;
food.flag=1;
}
/* 画蛇 */
setcolor(RED);
for(i=0;i<snake.node;i++)
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
Sleep(200);
setcolor(BLACK); //覆盖最后一节
rectangle(snake.x[snake.node-1],snake.y[snake.node-1],
snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);
} //while(!kbhit())结束
if(snake.life==1)
break;
if(kbhit()){
key=getchar();
if(key == ESC)
exit(0);
if((key==LEFT)&&(snake.d!=6))
snake.d=4;
else if((key==RIGHT)&&(snake.d!=4))
snake.d=6;
else if((key==UP)&&(snake.d!=2))
snake.d=8;
else if((key==DOWN)&&(snake.d!=8))
snake.d=2;}

} //while(1)结束
}
main()
{
Init();
draw();
play();
closegraph();
}
展开
 我来答
百度网友349d18b
2012-12-20 · TA获得超过444个赞
知道小有建树答主
回答量:571
采纳率:50%
帮助的人:365万
展开全部
把读键函数getchar()换成getch()
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式