《C语言程序设计-小游戏-贪吃蛇.docx》由会员分享,可在线阅读,更多相关《C语言程序设计-小游戏-贪吃蛇.docx(3页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、C语言程序设计-小游戏-贪吃蛇 #include#include#include#include#include#define N 21void gotoxy(int x,int y)/位置函数COORD pos;pos.X=2*x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);void color(int a)/颜色函数SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);void init(int apple2)/初始化函数(初始化围
2、墙、显示信息、苹果)int i,j;/初始化围墙int wallN+2N+2=0;for(i=1;i=N;i+)for(j=1;j=N;j+)wallij=1;color(11);for(i=0;iN+2;i+)for(j=0;jN+2;j+)if(wallij)cout;else cout ;coutendl;gotoxy(N+3,1);/显示信息color(20);cout按 W S A D 移动方向endl;gotoxy(N+3,2);color(20);cout按任意键暂停endl;gotoxy(N+3,3);color(20);cout得分:endl;apple0=rand()%N+
3、1;/苹果apple1=rand()%N+1;gotoxy(apple0,apple1);color(12);coutendl;int main() for(;)int i,j;int* snake=NULL;int apple2;int score=0;int tail2;int len=3;char ch=p;srand(unsigned)time(NULL);init(apple);snake=(int*)realloc(snake,sizeof(int*)*len);for(i=0;ilen;i+)snakei=(int*)malloc(sizeof(int)*2);for(i=0;i
4、len;i+)snakei0=N/2;snakei1=N/2+i;gotoxy(snakei0,snakei1);color(14);coutendl;while(1)/进入消息循环tail0=snakelen-10;tail1=snakelen-11;gotoxy(tail0,tail1);color(11);cout0;i-)snakei0=snakei-10;snakei1=snakei-11;gotoxy(snakei0,snakei1);color(14);coutendl;if(kbhit()gotoxy(0,N+2);ch=getche();switch(ch)case w:sn
5、ake01-;break;case s:snake01+;break;case a:snake00-;break;case d:snake00+;break;default: break;gotoxy(snake00,snake01);color(14);coutendl;Sleep(abs(200-0.5*score);if(snake00=apple0&snake01=apple1)/吃掉苹果后蛇分数加1,蛇长加1score+;len+;snake=(int*)realloc(snake,sizeof(int*)*len);snakelen-1=(int*)malloc(sizeof(in
6、t)*2);apple0=rand()%N+1;apple1=rand()%N+1;gotoxy(apple0,apple1);color(12);coutendl;gotoxy(N+5,3);color(20);coutscoreendl;if(snake01=0|snake01=N|snake00=0|snake00=N)/撞到围墙后失败gotoxy(N/2,N/2);color(30);cout失败!endl; for(i=0;ilen;i+)free(snakei);Sleep(2500);break;int a1,tttt;system(cls);init(apple);for(;)printf(请按数字并回车选择操作:n);printf(再来一局。n退出游戏。n请输入数字并回车:);scanf(%d,&a1);if(a1=1|a1=2)break; system(cls); init(apple);printf(输入有误!请重新输入!n); if(a1=2)break;system(cls); exit(0);return 0;