#include
#include
#include
#include
#include
#define N 225
struct Food
{
int x;
int y;
int yes;//1表示需要出現新食物,0表示已有食物。
}food;
struct Snake
{
struct Food body[N];
int life;//1表示蛇死啦,0表示蛇活著。
int node;//蛇的節數。
char direction;//蛇自動運動的方向。
}snake;
int score=0;
int main()
{
FILE *p;
int i,j,k,b;
char map[16][16],c;
p=fopen("E:\\file.txt","r");
if(p==NULL)
{
printf("error");
exit(1);
}
for(i=0;i<16;i++)
{
for(j=0;j<16;j++)
{
map[i][j]=fgetc(p);
}
fgetc(p);
}
snake.body[0].x=8;//蛇頭。
snake.body[0].y=8;
snake.body[1].x=8;
snake.body[1].y=7;
snake.body[2].x=8;
snake.body[2].y=6;
snake.node=3;//蛇的節數。
food.yes=1;
srand(time(NULL));
snake.direction='d';//一開始蛇自動往右跑。
while(1)
{
if(kbhit())
{
c=getch();
if(snake.life==1)
break;
if(c=='w' && snake.direction!='s')
snake.direction='w';
else if(c=='a' && snake.direction!='d')
snake.direction='a';
else if(c=='s' && snake.direction!='w')
snake.direction='s';
else if(c=='d' && snake.direction!='a')
snake.direction='d';
}
if(food.yes==1)//需要隨機出現新的食物。
{
food.x=1+rand()%14;
food.y=1+rand()%14;
for(i=0;i0;i--)//蛇往前移動。
{
snake.body[i].x=snake.body[i-1].x;
snake.body[i].y=snake.body[i-1].y;
}
switch(snake.direction)//蛇頭方向。
{
case'a':
snake.body[0].y-=1;
break;
case'w':
snake.body[0].x-=1;
break;
case'd':
snake.body[0].y+=1;
break;
case's':
snake.body[0].x+=1;
break;
}
if(food.yes==0)//顯示蛇,食物和圍牆。
{
system("cls");
for(i=0;i<16;i++)
{
for(j=0;j<16;j++)
{
b = 1;
for(k=0;k0 && j<15 && j>0)//食物。
printf("★");
else if(map[i][j]=='1')
printf("■");
else
printf(" ");
}
}
putchar('\n');
}
Sleep(250);//休眠函數。
}
for(i=3;i=15 || snake.body[0].x<=0 || snake.body[0].y>=15 || snake.body[0].y<=0)
{
printf("蛇撞牆死了!\n");
printf("共得分:%d\n",score);
snake.life=1;
break;
}
}
fclose(p);
return 0;
}
下面是file.txt:
1111111111111111
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1111111111111111