#include<graphics.h>
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<conio.h>
#define leftx 0
#define lefty 0
#define rightx 600
#define righty 400
#define step 20
#define len_win 200
#define _MAXLEN 200
#define speed 200
#define KEY_ESC 0x1b
#define KEY_UP 0x48
#define KEY_DOWN 0x50
#define KEY_LEFT 0x4b
#define KEY_RIGHT 0x4d
int endx;
int endy;
struct snake
{
int x[_MAXLEN];
int y[_MAXLEN];
int nnode;
int direction;
int live;
};
void DrawGrid(void)
{
int i,j;
i=0;
j=0;
setcolor(WHITE);
setlinestyle(PS_SOLID,1);
rectangle(leftx-1,lefty-1,rightx+1,righty+1);
setcolor(BLACK);
setlinestyle(PS_SOLID,1);
for (i=lefty;i<=righty;i=i+step)
{
line(leftx,i,rightx/step*step,i);
}
for (j=leftx;j<=rightx;j=j+step)
{
line(j,lefty,j,righty/step*step);
}
}
void getRANDXY(int *x,int *y)
{
*x=rand()%(rightx-leftx)/step*step;
*y=rand()%(righty-lefty)/step*step;
}
void snakeint(struct snake *p)
{
p->live=1;
p->direction=rand()%4+1;
getRANDXY(&p->x[0],&p->y[0]);
p->x[1]=p->x[0]+step;
p->y[1]=p->y[0];
p->nnode=2;
}
void snakedraw(struct snake *p,int x,int y)
{
int i;
setcolor(BLACK);
rectangle(x,y,x+step,y+step);
setcolor(RED);
for (i=0;i<p->nnode;i++)
{
rectangle(p->x[i],p->y[i],p->x[i]+step,p->y[i]+step);
}
}
void foodint(int *x,int *y)
{
getRANDXY(x,y);
}
void foodDraw(int x,int y)
{
setcolor(GREEN);
rectangle(x,y,x+step,y+step);
}
void snakeMove(struct snake *p)
{
int i;
for (i=p->nnode-1;i>0;i--)
{
p->x[i]=p->x[i-1];
p->y[i]=p->y[i-1];
}
switch(p->direction)
{
case 1:p->x[0]+=step;break;
case 2:p->x[0]-=step;break;
case 3:p->y[0]-=step;break;
case 4:p->y[0]+=step;break;
}
}
void snakeCheck(struct snake *p)
{
int i;
for(i=3;i<p->nnode;i++)
{
if (p->x[i]==p->x[0]&&p->y[i]==p->y[0])
{
p->live=0;
break;
}
}
if (p->x[0]<leftx||p->x[0]>rightx||p->y[0]<lefty||p->y[0]>righty)
{
p->live=0;
}
}
int foodCheck(struct snake *p,int *fx,int *fy)
{
if (p->x[0]==*fx &&p->y[0]==*fy)
{
p->x[p->nnode]=-10;
p->y[p->nnode]=-10;
p->nnode++;
foodint(fx,fy);
foodDraw(*fx,*fy);
return 1;
}
return 0;
}
int readKey()
{
if (_kbhit()==0)
{
return 0;
}
else
{
int ch=getch();
if (ch==0xE0)
{
ch=getch();
return(ch);
}
}
}
int keyread2(int key,int dir)
{
if (key== KEY_UP ==1&&dir!=4)
{
dir=3;
}
if (key== KEY_DOWN ==1&&dir!=3)
{
dir=4;
}
if (key== KEY_RIGHT ==1&&dir!=2)
{
dir=1;
}
if (key== KEY_LEFT ==1&&dir!=1)
{
dir=2;
}
return dir;
}
void main()
{
struct snake p;
int fx,fy,key,sun;
initgraph(rightx+step+1,righty+step+30);
DrawGrid();
srand(time(NULL));
snakeint(&p);
foodint(&fx,&fy);
foodDraw(fx,fy);
while(1)
{
while(!_kbhit())
{
snakeMove(&p);
snakeCheck(&p);
foodCheck(&p,&fx,&fy);
if(p.live==0)
{
break;
}
snakedraw(&p,endx,endy);
sun=p.nnode-1;
endx=p.x[sun];
endy=p.y[sun];
Sleep(speed);
}
if (p.live==0)
{
break;
}
else
{
key=readKey();
if (key==KEY_ESC)
{
break;
}
p.direction=keyread2(key,p.direction);
}
}
outtextxy(250,200,"GAME OVER");
getch();
closegraph();
}