貪吃蛇代碼
#include <dos.h>
#include<alloc.h>
#include <stdlib.h>
#include <stdio.h>
#include "graphics.h"
#include<math.h>
typedef struct
{
int x;
int y;
}node;
struct
{
node info[40];
int length;
}snake;
char light[60][48];
void main()
{
int search(int m,int n);
void Light(int m,int n,int color);
int settle(int key);
char met=1;
int i,j,direction,key1,key2=0,rm,rn;
int driver=DETECT,mode=0;
initgraph(&driver,&mode," ");
setcolor(10);
rectangle(0,0,580,450);
snake.length=3;
for(i=0;i<60;i++)
for(j=0;j<48;j++)
light[i][j]=0;
snake.info[0].x=32;
snake.info[1].x=32;
snake.info[2].x=32;
snake.info[0].y=24;
snake.info[1].y=25;
snake.info[2].y=26;
for(i=0;i<3;i++)
Light(snake.info[i].x,snake.info[i].y,8);
do
{
if(met==1)
{
do
{
rm=random(57);
rn=random(44);
met=0;
}while(search(rm,rn));
}
Light(rm,rn,10);
if(!bioskey(1))
{
key1=key2;
}
else
{
key1=bioskey(0);
if((key2==0x4b00&&key1==0x4d00)||(key1==0x4b00&&key2==0x4d00)||(key1==0x4800&&key2==0x5000)||(key1==0x5000&&key2==0x4800)||(key1==0x5000&&key2==0))
key1=key2;
else key2=key1;
}
if(key1) met=settle(key1);
if(met==2) return;
for(i=0;i<snake.length;i++)
Light(snake.info[i].x,snake.info[i].y,8);
for(i=0;i<13-snake.length*0.3;i++) delay(12000);
}while(snake.length<40);
getch();
}
void Light(int m,int n,int color)
{
setfillstyle(1,color);
bar(10*m,10*n,10*m+8,10*n+8);
if(color==8) light[m][n]=2;
if(color==10) light[m][n]=1;
if(color==0) light[m][n]=0;
}
int search(int m,int n)
{
if(light[m][n]==2)
return(1);
return 0;
}
int settle(int key)
{
int i,rx,ry;
rx=snake.info[snake.length-1].x;ry=snake.info[snake.length-1].y;
for(i=snake.length-1;i>0;i--)
{
snake.info[i].x=snake.info[i-1].x;
snake.info[i].y=snake.info[i-1].y;
}
switch(key)
{
case 0x4800:
snake.info[i].y--;
break;
case 0x5000:
snake.info[i].y++;
break;
case 0x4b00:
snake.info[i].x--;
break;
case 0x4d00:
snake.info[i].x++;
break;
}
if(light[snake.info[i].x][snake.info[i].y]==1)
{
snake.length++;
snake.info[snake.length-1].x=rx;
snake.info[snake.length-1].y=ry;
Light(snake.info[i].x,snake.info[i].y,0);
return(1);
}
if(snake.info[i].x>58||snake.info[i].y>44||snake.info[i].x<0||snake.info[i].y<0||light[snake.info[i].x][snake.info[i].y]==2)
{
return(2);
}
Light(rx,ry,0);
return(0);
}