请教一个C语言贪吃蛇问题:为什么运行结果是蛇的长度在增加啊?
我第一步只是编写一个简单的,没有食物,蛇也不增长,只是用上下左右四个键控制蛇的运动,蛇碰壁就退出。程序的算法就是蛇头的坐标根据方向而加减10,而蛇段的坐标则依次等于前面一节蛇段的坐标,然后把蛇尾黑掉(setcolor(0)),这样就实现了蛇的运动,但是问题是程序运行后,结果是蛇在不断地增长,这是怎么回事啊?我的程序错在什么地方,该怎么该啊?谢谢指点!程序如下:#include "stdlib.h"
#include "graphics.h"
#include "dos.h"
#define N 200
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b
int key;
int speed=99000;
struct Snake
{
int x[N];
int y[N];
int node;
int direction;
int life;
}snake;
void init();
void close();
void drawk();
void play();
void over();
void main()
{
init();
drawk();
play();
over();
close();
}
void init()
{
int gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode,"");
cleardevice();
}
void close()
{
cleardevice();
closegraph();
}
void drawk()
{
int i;
setcolor(11);
setlinestyle(SOLID_LINE,0,THICK_WIDTH);
for(i=0;i<=55;i++)
{
rectangle(50+10*i,40,60+10*i,49);
rectangle(50+10*i,451,60+10*i,460);
}
for(i=0;i<=41;i++)
{
rectangle(50,40+10*i,59,50+10*i);
rectangle(601,40+10*i,610,50+10*i);
}
}
void play()
{
int i;
snake.life=0;
snake.direction=1;
snake.x[0]=110;
snake.y[0]=100;
snake.x[1]=100;
snake.y[1]=100;
snake.node=2;
while(1)
{
while(!kbhit())
{
for(i=snake.node-1;i>0;i--)
{
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
switch(snake.direction)
{
case 1:snake.x[0]+=10;break;
case 2:snake.x[0]-=10;break;
case 3:snake.y[0]-=10;break;
case 4:snake.y[0]+=10;break;
}
if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455)
{
over();
snake.life=1;
}
setcolor(4);
for(i=0;i<snake.node;i++)
{
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]+10);
}
delay(speed);
setcolor(0);
rectangle(snake.x[snake.node-1],snake.y[snake.node],snake.x[snake.node-1]+10,snake.y[snake.node]+10);
}
if(snake.life==1)
break;
key=bioskey(0);
if(key==ESC)
break;
else if(key==UP&&snake.direction!=4)
snake.direction=3;
else if(key==RIGHT&&snake.direction!=2)
snake.direction=1;
else if(key==LEFT&&snake.direction!=1)
snake.direction=2;
else if(key==DOWN&&snake.direction!=3)
snake.direction=4;
}
}
void over()
{
cleardevice();
setcolor(RED);
settextstyle(0,0,4);
outtextxy(200,200,"game over!");
getch();
}