贪吃蛇怎么不对?
#include<stdio.h>#include<string.h>
#include<process.h>
#include<conio.h>
#define SIZEMAX 100 /*长度*/
#define SNAKELEN 10 /*移动距离*/
#define SPEED 100 /*初始速度*/
typedef enum
{
left,right,up,donw
}DIR;
typedef struct
{
int x;
int y;
}COOR;
struct FOOD
{
COOR crd;
int flag;
}food;
struct SNAKE
{
COOR crd[SIZEMAX];
int node;
DIR dir;
}snake;
int speed=SPEED;
/*主函数*/
void main()
{
init();
while(1){
while(!kbhit()) {
if(!food.flag) setfoodcrd();
showfood();
judgerlod();
judgesef();
snakemove();
Sleep(speed);
}
changeskdir();
}
}
void init()
{
initgraph(640,480);
srand(time(NULL));
food.flag=0;
snake.crd[0].x=0+SNAKELEN;
snake.crd[0].y=0;
snake.crd[1].x=0;
snake.crd[1].y=0;
snake.node=2;
snake.dir=right; /*默认向右*/
}
/*随机生成食物*/
void setfoodcrd()
{
food.crd.x=rand()%(600/SNAKELEN)*SNAKELEN;
food.crd.y=rand()%(480/SNAKELEN)*SNAKELEN;
food.flag=1;
}
/*画食物*/
void showfood()
{
rectangle(food.crd.x,food.crd.y,food.crd.x+SNAKELEN,food.crd.y+SNAKELEN);
}
/*蛇*/
void showsnake()
{
int i;
for(i=snake.node-1;i>=0;i--)
rectangle(snake.crd[i].x,snake.crd[i].y,snake.crd[i].x+SNAKELEN,snake.crd[i].y+SNAKELEN);
setcolor(BLACK);
rectangle(snake.crd[snake.node].x,snake.crd[snake.node].y,snake.crd[snake.node].x+SNAKELEN,snake.crd[snake.node].y+SNAKELEN);
setcolor(WHITE);
rectangle(snake.crd[snake.node-1].x,snake.crd[snake.node-1].y,snake.crd[snake.node-1].x+SNAKELEN,snake.crd[snake.node-1].y+SNAKELEN);
}
/*移动*/
void snakemove()
{
int i,for(i=snake.crd;i>0;i--)
{
snake.crd[i].x=snake.crd[i-1].x;
snake.crd[i].y=snake.crd[i-1].y;
}
switch(snake.dir)
{
case up:snake.crd[0].y-=SNAKELEN;break;
case donw:snake.crd[0].y+=SNAKELEN;break;
case left:snake.crd[0].x-=SNAKELEN;break;
case right:snake.crd[0].x+=SNAKELEN;
}showsnake;
}
/*改变方向*/
void changeskdir()
{
char key;
key=getch();
switch(key)
{
case'w': case'W': if(snake.dir!=donw)snake.dir=up;break;
case's': case'S': if(snake.dir!=up)snake.dir=donw;break;
case'a': case'A': if(snake.dir!=right)snake.dir=left;break;
case'd': case'D': if(snake.dir!=left)snake.dir=right;break;
}
}
/*Game Over*/
void judgeslod()
{
int i;
if(snake.crd[0].x<0||snake.crd[0].x>=640||snake.crd[0].y<0||snake.crd[0].y>=480)
gameover();
for(i=snake.node-1;i>0;i--)
if(snake.crd[0].x==snake.crd[i].x&&snake.crd[0].y==snake.crd[i].y)
gameover();
}
/*吃到食物*/
void judgefood()
{
if(snake.crd[0].x==food.crd.x&&snake.crd[0].y==food.crd.y)
{
snake.node++; setcolor(BLACK);
rectangle(food.crd.x,food.crd.y,food.crd.x+SNAKELEN,food.crd.y+SNAKELEN);
setcolor(WHITE); food.flag=0;
}
}