C++结构体数组实现贪吃蛇
本文实例为大家分享了C++结构体数组实现贪吃蛇的具体代码,供大家参考,具体内容如下
代码:
#include#include #include usingnamespacestd; constinth=50,w=50,MaxLen=400; voidgotoxy(shorty,shortx)//光标移动函数 { COORDpos={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); } structnode { intx,y; }; nodes[MaxLen]; nodefood; intdir,len; intMap[h+5][w+5]; intTime[7]={0},level;//building。。。 voidFoodCreate() { srand((unsigned)time(NULL));//时间作随机数种子,避免伪随机 while(1) { food.x=rand()%h,food.y=rand()%w; if(food.x>0&&food.y>0&&Map[food.x][food.y]==0)break; } gotoxy(food.x,food.y),printf("@"); gotoxy(h+1,0); } voidinit() { system("cls"); for(inti=0;i<=h;i++)//画图 { for(intj=0;j<=w;j++) { if(i==0||j==0||i==h||j==w)Map[i][j]=1,printf("#"); elseMap[i][j]=0,printf(""); } printf("\n"); } len=2;//初始化蛇 dir=0; s[1].x=12,s[1].y=4; s[len].x=12,s[len].y=3; Map[s[1].x][s[1].y]=Map[s[len].x][s[len].y]=1; gotoxy(s[1].x,s[1].y),printf("*"); gotoxy(s[len].x,s[len].y),printf("*"); gotoxy(h+1,0); FoodCreate(); } intmove() { nodenext=s[1]; switch(dir) { case0:next.y++;break; case1:next.x--;break; case2:next.y--;break; case3:next.x++;break; } if(Map[next.x][next.y])return0;//下一步GG if(next.x==food.x&&next.y==food.y)//下一步遇到食物 { len++; FoodCreate(); } else//下一步是空白就将尾部覆盖 { gotoxy(s[len].x,s[len].y),printf(""); Map[s[len].x][s[len].y]=0; } gotoxy(next.x,next.y),printf("*"); gotoxy(h+1,0); Map[next.x][next.y]=1; for(inti=len;i>1;i--)s[i]=s[i-1]; s[1]=next; Sleep(100);//Sleep放在最后比较顺滑//速度在这儿调 return1; } voidGameOver() { for(inti=1;i<=3;i++) { gotoxy(s[1].x,s[1].y); printf(""); Sleep(300); gotoxy(s[1].x,s[1].y); printf("*"); Sleep(300); } gotoxy(h+1,0); printf("GameOver\n"); printf("Pressanykeytocontinue..."); } voidWelcome() { printf("为了您的游戏体验,请先调整控制台字体和布局(记得不要忘了默认设置):\n"); printf("右键白色框->属性->字体选择点阵字体并调整字体大小为8×8\n"); printf("再选择布局设置窗口大小,推荐60×60\n\n"); printf("WASD控制方向\n"); printf("\n任意键进入贪吃蛇皮..."); getch(); } intmain() { Welcome(); init(); while(1) { if(kbhit()) { charch=getch(); inttemp=dir; switch(ch) { case'd':temp=0;break; case'w':temp=1;break; case'a':temp=2;break; case's':temp=3;break; } if((temp+dir)%2)dir=temp;//如果方向不冲突 } if(move()==0) { GameOver(); getch(); init(); } } }
运行效果:
关于C++小游戏的更多精彩内容请点击专题:《C++经典小游戏》学习了解
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。