该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
#include
#include
#include
HANDLE hout;
COORD pos={0,0};
int fail[20][2]={1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int map[21][42];
struct snake
{
short headx;
short heady;
}se={1,1};
int flag=0;
int num=0;
int over=0;
void work(void);
void edge(void);
void dysnake(short x,short y);
void operate(char ch);
void food();
int main()
{char ch;
hout=GetStdHandle(STD_OUTPUT_HANDLE);
edge();
work();
food();
while(1)
{ch=getch();
while(!kbhit())
{ operate(ch);
if(map[se.heady ][se.headx *2]==2)
{map[se.heady ][se.headx *2]=0;
num++; //如果遇到食物,节点加1,
food();
}
if(over)
{ printf("game over"); break;}
dysnake(se.headx ,se.heady );
Sleep(200);
}
if(over)
break;
}
return 0;
}
void edge(void)
{int i;
for(i=0;i<20;i++)
{pos.X=i*2;
pos.Y =0;
SetConsoleCursorPosition(hout,pos);
puts("■");
pos.X=i*2;
pos.Y=20; //在第21行
SetConsoleCursorPosition(hout,pos);
puts("■");
}
for(i=1;i<20;i++)
{pos.X =0;
pos.Y =i;
SetConsoleCursorPosition(hout,pos);
puts("■");
pos.X =40;
pos.Y =i;
SetConsoleCursorPosition(hout,pos);
puts("■");
}
}
void work(void)
{ int i,j;
pos.X=1*2 ;
pos.Y=1 ;
SetConsoleCursorPosition(hout,pos);
puts("●");
map[1][1]=1;
for(i=0;i<21;i++)
for(j=0;j<42;j++)
map[21][42]=0;
}
void food()
{int i,j;
do
{srand((int)time(0));
i=rand()%19+1;
j=rand()%19+1;
pos.X=i*2;
pos.Y =j;
SetConsoleCursorPosition(hout,pos);
puts("☆");
}while(map[j][i]==1);
map[j][i*2]=2;
}
void operate(char ch)
{ switch(ch)
{case 'a':
{se.headx--;
if((se.headx<1)||(map[se.heady ][se.headx ]==1))
{se.headx++;
flag=1;
over=1;
}
else
map[se.heady ][se.headx ]=1;
}break;
case 'd':
{se.headx++;
if((se.headx>19)||(map[se.heady ][se.headx ]==1))
{ se.headx--;
flag=1;
over=1;
}
else
map[se.heady ][se.headx ]=1;
}break;
case 'w':
{se.heady--;
if((se.heady <1)||(map[se.heady ][se.headx ]==1))
{se.heady++;
flag=1;
over=1;
}
else
map[se.heady ][se.headx ]=1;
}break;
case 's':
{se.heady++;
if((se.heady >19)||(map[se.heady ][se.headx ]==1))
{ se.heady--;
flag=1;
over=1;
}
else
map[se.heady ][se.headx ]=1;
}break;
default:flag=1;
}
}
void dysnake(short x,short y) //参数为新蛇头坐标
{ int i;
if(flag==1) //如果蛇头坐标没有改变,不执行清除蛇尾
flag=0;
else
{
pos.X=fail[0][0]*2;
pos.Y =fail[0][1];
map[fail[0][1]][fail[0][0]]=0;
SetConsoleCursorPosition(hout,pos);
puts(" "); //清除蛇尾
for(i=0;i
{ fail[i][0]=fail[i+1][0]; //重新定位蛇身
fail[i][1]=fail[i+1][1];
}
fail[num][0]=x;
fail[num][1]=y;
}
pos.X=x*2;
pos.Y =y;
SetConsoleCursorPosition(hout,pos);
puts("●"); //打印蛇头
}