c语言贪吃蛇食物不能随机,为啥我的贪吃蛇随机性的把食物吃没,帮忙看一下吧...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#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("●"); //打印蛇头

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值