#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct Facts{//组成蛇的每一个元素
int x;//表示列,都是从左上角开始
int y;//行
};
void printAll(int lineCount,int columnCount,int len,struct Facts factArr[],char rect[20][20],int fx,int fy,int fxcount){
int i,j,k;
for(i=0;i<lineCount;i++){
for(j=0;j<columnCount;j++){
char ijIsSnake=0;
for(k=0;k<len;k++){
if(i==factArr[k].y&&j==factArr[k].x){
printf(",",'+');
ijIsSnake=1;
break;
}
}
if(ijIsSnake==0){
if(fxcount==1){
if(i==fy&&j==fx){
printf(",",'f');
}else{
printf(",",rect[i][j]);
}
}
}
}
printf("\n");
}
}
//根据是否和蛇身重复的到水果的位置并显示水果
void showFruit(int *fx,int *fy,int *fxcount,struct Facts factArr[],int len){
if(*fxcount==0){//没水果时
while(1){
int tmpfx,tmpfy;
tmpfx=rand() ;
tmpfy=rand() ;
int a;
char belongSnake=0;//和蛇身不重合
for(a=0;a<len;a++){
if(tmpfx==factArr[a].x&&tmpfy==factArr[a].y){
belongSnake=1;
break;
}
}
if(belongSnake==0){
*fx=tmpfx;
*fy=tmpfy;
*fxcount=1;//水果的数量
break;
}else{//=1:重合
continue;
}
}
}
}
void move(int lineCount,int columnCount,int *len,struct Facts factArr[],char rect[20][20],int *fx,int *fy,int *fxcount,char direct){
struct Facts tmpSnake[lineCount*columnCount];
//memcpy(tmpSnake,factArr,sizeof(factArr));
int t;
for(t=0;t<*len;t++){
tmpSnake[t]=factArr[t];
}
/*
//int aaa[4]={1,2,555};
int aaa[4];
aaa[0]=1;
aaa[1]=2;
aaa[2]=555;
//8 0 0 4 8 3200 16
// printf("%d %d %d %d %d %d %d",sizeof(factArr),tmpSnake[1].y,tmpSnake[2].x,sizeof(int),sizeof(struct Facts),sizeof(tmpSnake),sizeof(aaa));
*/
if(direct=='q'){
exit(0);
}else if(direct=='w'){
factArr[0].y--;
}else if(direct=='a'){
factArr[0].x--;
}else if(direct=='d'){
factArr[0].x++;
}else if(direct=='s'){
factArr[0].y++;
}else{
printf("用法:上:w,左:a右:d下:s退出:q\n");
return;
}
int i;
for(i=1;i<*len;i++){
factArr[i].x=tmpSnake[i-1].x;
factArr[i].y=tmpSnake[i-1].y;
}
system("clear");
if(factArr[0].x==(*fx)&& factArr[0].y==(*fy)){
factArr[*len].x=tmpSnake[(*len)-1].x;
factArr[*len].y=tmpSnake[(*len)-1].y;
// printf("%d %d\n",factArr[*len].x,factArr[*len].y);
(*len)++;
*fxcount=0;
showFruit(fx,fy,fxcount,factArr,*len);
}
printAll(lineCount, columnCount, *len,factArr,rect,*fx,*fy,*fxcount);//重绘
}
int main(){
srand(time(NULL));
int lineCount=20,columnCount=20,len=0;
char rect[lineCount][columnCount];//背景方形
struct Facts factArr[lineCount*columnCount];
//初始化蛇
factArr[len].x=9;
factArr[len].y=9;
len++;
factArr[len].x=9;
factArr[len].y=10;
len++;
memset(rect,'*',sizeof(rect));
char init=1;
int fx,fy,fxcount=0;
while(1){
showFruit(&fx,&fy,&fxcount,factArr,len);
if(init){
printAll(lineCount, columnCount, len,factArr,rect,fx,fy,fxcount);//打印初始化
init=0;
}
char direct='0';
printf("上:w,左:a右:d下:s退出:q\n");
direct=getchar();
getchar();
move(lineCount, columnCount, &len,factArr,rect,&fx,&fy,&fxcount,direct);
}
return 0;
}