要求:至少有墙、蛇和食物3种对象,用键盘控制蛇头的前进方向,每吃到一个食物蛇身增长一节,食物被吃掉后随机在另外的位置产生新的食物,蛇头碰到蛇身或墙壁后死亡,游戏结束!
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
main()
{
char map[12][12]
={{'|','|','|','|','|','|','|','|','|','|','|','|'},{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},
{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},
{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},
{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},
{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},
{'|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','|'},{'|','|','|','|','|','|','|','|','|','|','|','|'}};
int bodyx[10];
int bodyy[10]; //存储蛇头和蛇身坐标
int speed; //速度
int life; //life为1时死,life为0时活
int longth; //蛇长度
int direction; //运动方向
int x;
int y; //食物坐标
int eat;//eat为0时有食物,eat为1时无食物
int i;
int a, b, m, n, q, p, j, k;
char c;
char head='@';
char body='#';
char food='*';
bodyx[0]=6;
bodyy[0]=6; //蛇头
bodyx[1]=6;
bodyx[1]=5; //蛇身
speed=500;
longth=3;
life=0;
eat=1;
direction='d';
if(bodyx[0]==x&&bodyy[0]==y)
longth++,eat=1; //蛇吃到食物,蛇身加长
for(i=longth-1;i>0;i--)
{
bodyx[i]=bodyx[i-1];
bodyy[i]=bodyy[i-1];
}
switch (direction)
{
case 'a':bodyy[0]-=1;break;
case 'w':bodyx[0]-=1;break;
case 'd':bodyy[0]+=1;break;
case 's':bodyx[0]+=1;break;
}//蛇头方向
begin:
while(1)
{
system("cls"); //清屏
if(kbhit()) //判断是否有按键按下
{
c=getch(); //获取按键ASCII码值
{
if(c=='w'&&direction!='s') direction='w'; //条件判断
else if(c=='a'&&direction!='d') direction='a';
else if(c=='s'&&direction!='w') direction='s';
else if(c=='d'&&direction!='a') direction='d';
else if(c=='q') //暂停功能
{
printf("\n按下回车键继续游戏");
getchar();
}
else if(c=='e') speed=speed-50; //调速功能
}
}
}
if(life==0&&eat==1)
{
x=(rand()%10)+1;
y=(rand()%10)+1;
for(i=1;i<longth;i++)
{
for(;x==bodyx[i]&&y==bodyy[i];)
{
x=(rand()%10)+1;
y=(rand()%10)+1;
}
}
eat=0;
}//刷新食物
a=bodyx[0]; //a,b是蛇头坐标
b=bodyy[0];
for(i=longth-1;i>0;i--)
{
m=bodyx[i]; //m,n是蛇身坐标
n=bodyy[i];
map[m][n]=body; //改写地图数组
}
map[x][y]=food;
map[p][q]=' ';
map[a][b]=head; //改写地图数组
for(j=0;j<12;j++)
{
for(k=0;k<12;k++)
{
printf("%c",map[j][k]);
printf("\n");
}
}
printf("长度: %d\n速度 %d\n按q键暂停\n按e键加速",longth-1,11-(speed/50));
Sleep(speed);
if(longth>3)
{
for(i=3;i<longth-1;i++)
{
if(bodyx[i]==bodyx[0]&&bodyy[i]==bodyy[0])
life=1;
}
}//判断蛇是否咬到自己
if(bodyx[0]>=11||bodyx[0]<=11||bodyy[0]>=11||bodyy[0]<=11)
life=1;//判断蛇是否撞墙
if(life==1)
{
system("cls");
printf("\tGAME OVER");
system("cls");
printf("Click the enter to reply");
getchar();
goto begin;
}//游戏结束
}
以上是大部分代码(老师给的),剩下的不会补了,求大佬指教