#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<windows.h> int printgamemop(char gr[20][20],int len,int x[],int y[],int fcount,int fx,int fy); int movesnake(char s[],char gr[20][20],int *len,int x[],int y[],int *fcount,int *fx,int *fy,int *score); int addfruit(int *fcount,int *fx,int *fy,int *len,int x[],int y[]); int gameOver(int len,int x[],int y[],int score); int gameOver(int len,int x[],int y[],int score) { int gameOver=0; for(int i=1; i<len; i++) { if(x[0]==x[i]&&y[0]==y[i]) { gameOver=1; printf("当前分数%d\nGame Over!\n",score); break; } } return gameOver; } int addfruit(int *fcount,int *fx,int *fy,int len,int x[],int y[]) { if((*fcount)==0) { while(1) { int tfx=rand()%20; int tfy=rand()%20; int have=0;//判断fy是否生成果子 for(int i=0; i<len; i++) { if(tfx==x[i]&&tfy==y[i]) { have=1; break; } } if(have==1) continue; else { (*fcount)++; (*fx)=tfx; (*fy)=tfy; break; } } } } int printgamemop(char gr[20][20],int len,int x[],int y[],int fcount,int fx,int fy) { for(int i=0; i<20; i++) { for(int j=0; j<20; j++) { gr[i][j]='.'; //是否是蛇的一部分 int snake=0; for(int k=0; k<len ; k++) { if(i==x[k]&&j==y[k]) { if(k==0) { snake=1;//蛇头 } else snake=2;//蛇身 break; } } if(snake==1) { printf("*"); } else if(snake==2) printf("o"); else { if(fcount&&fx==i&&fy==j) printf("@"); else printf(". "); } } printf("\n"); } } //蛇的移动 int movesnake(char s[],char gr[20][20],int *len,int x[],int y[],int *fcount,int *fx,int *fy,int *score) { int cx[400];//20*20==400; int cy[400]; memcpy(cx,x,sizeof(int)*(*len));//复制函数,将x中的sizeof(int)*(*len)字节从头开始复制到cx中 memcpy(cy,y,sizeof(int)*(*len));//做备份 int move=0; if(strcmp(s,"w")==0) { x[0]=x[0]-1; move=1; } else if(strcmp(s,"s")==0) { x[0]=x[0]+1; move=1; } else if(strcmp(s,"a")==0) { y[0]=y[0]-1; move=1; } else if(strcmp(s,"d")==0) { y[0]=y[0]+1; move=1; } //头部 //身体 if(move==1) { if((*fcount)&&x[0]==(*fx)&&y[0]==(*fy)) { memcpy(x+1,cx,sizeof(int)*(*len)); memcpy(y+1,cy,sizeof(int)*(*len));//将蛇的上一个节点复制到下一个节点上 (*len)++; (*fcount)--; (*fx)=0; (*fy)=0;//初始化 (*score)++; addfruit(fcount,fx,fy,(*len),x,y);//增加下一个水果 } else { for(int i=1; i<(*len); i++) { x[i]=cx[i-1]; y[i]=cy[i-1]; } } system("cls");//是一个系统命令,作用是清除刷屏上的所有显示并将光标置于屏幕左上角 printgamemop(gr,(*len),x,y,*fcount,*fx,*fy);//棋盘初始化 } } int main() { srand(time(NULL)); char gr[20][20]; int x[400]= {0}; //代表蛇的行 int y[400]= {0}; //代表蛇的列 int len =0; x[len]=9; y[len]=9; len++;//蛇头 x[len]=9; y[len]=8; len++;//蛇的第一个蛇身 int fx=0;//水果的坐标x int fy=0;//水果的坐标y int fcount=0;//水果数量 int score=0;//得分数 //随机生成水果 addfruit(&fcount,&fx,&fy,len,x,y); printgamemop(gr,len,x,y,fcount,fx,fy); while(1) { printf("当前分数%d,请输入w向下,s向上,a向左,d向右\n",score); char s[2]; scanf("%s",s); //move movesnake(s,gr,&len,x,y,&fcount,&fx,&fy,&score); if(gameOver(len,x,y,score)==1)break; } return 0; }
贪吃蛇
猜你喜欢
转载自taoyongpan.iteye.com/blog/2258475
今日推荐
周排行