贪食蛇的运行效果图:
c语言源码:
- #include<stdio.h>
- #include<stdlib.h>
- #define U 'w'
- #define D 's'
- #define R 'd'
- #define L 'a'
- #define long 4
- #define U_Link 1
- #define D_Link 20
- #define L_Link 1
- #define R_Link 60
- #define max 20
- struct S{
- char x,y,cur;
- }h[max],target[11]={{4,4,1},{25,15,1},{5,6,1},{38,16,1},{51,4,1},{25,13,1},{5,18,1},{55,12,1},{15,3,1},{40,15,1},{30,10,1}};
- void delay();
- void close();
- void start();
- void pro(int i);
- void main()
- {
-
- int time;
- char head_l,head_c,i,j,length;
- char key,ch=0,t;
- loop:{
- printf("\t\t\t/***********贪吃蛇**********/\n") ;
- printf("\n\n\t 操作技巧:\n\t\t\tW 键: 向上") ;
- printf("\n\n\t\t\tS 键: 向下") ;
- printf("\n\n\t\t\tA 键: 向左") ;
- printf("\n\n\t\t\tD 键: 向右") ;
- printf("\n\n\n\t\t按回车键进入.............") ;
- getchar();
- for(i=0;i<max-1;i++)
- {
- h[i].cur=i+1;
- }
- h[i].cur=0;
-
- char s[30][60]={0};
- head_l=(U_Link+D_Link)/2;
- head_c=(R_Link+L_Link)/2;
- for(i=0;i<long-1;i++)
- {
- h[i].cur=i+1;
- }
- h[i].cur=0;
-
- length=long;
- time=1500;
- key=L;
- t=0;
- for(j=0;j<length;j++)
- {
- h[j].y=head_l;
- h[j].x=head_c+j;
- }
- while(1)
- {
- for(j=0;j<length;j++)
- {
- s[h[j].y][h[j].x]=1;
- }
- s[target[t].y][target[t].x]=2;
- for(i=0;i<=U_Link;i++)
- printf("================================================================================\n");
-
- for(i=0;i<D_Link-U_Link;i++)
- {
- for(j=0;j<L_Link;j++)
- printf(" ");
- printf(" ||");
- for(j=0;j<R_Link;j++)
- {
- if(s[i][j]==1)
- printf("0");
- else if(s[i][j]==2)
- printf("*");
- else printf(" ");
- }
-
- printf("|| \n");
- }
- if((h[0].x==target[t].x)&&(h[0].y==target[t].y))
- {
- t++;
- length++;
- time-=80;
- if(t>9)break;
- }
- s[h[length-1].y][h[length-1].x]=0;
- for(i=length-1;i>0;i--)
- {
- h[i].x=h[i-1].x;
- h[i].y=h[i-1].y;
- }
-
- if(_kbhit())
- {
- ch=getch();
- if((ch==U)||(ch==D)||(ch==R)||(ch==L))
- key=ch;
- }
- if(key==U)
- {
- if(head_l>=0)
- head_l--;
- else head_l=D_Link;
- }
- if(key==D)
- {
- if(head_l<D_Link)
- head_l++;
- else head_l=U_Link;
- }
- if(key==L)
- {
- if(head_c>=0)
- head_c--;
- else head_c=R_Link+1;
- }
- if(key==R)
- {
- if(head_c<R_Link)
- head_c++;
- else head_c=L_Link;
- }
- h[0].x=head_c;
- h[0].y=head_l;
- printf("\n\t得分: %d",t*10);
- // printf("h[0].x=%d h[0].y=%d target[%d].x=%d y=%d\n",h[0].x,h[0].y,t,target[t].x,target[t].y);
- delay(time);
- close();
-
- }
- close();
- printf("恭喜通关\n");
- printf("\n\t得分: %d\n",t*10);
- printf("按空格键退出\n");
-
- if(' '==getch())
- goto loop;
-
- }
- }
- void delay(int i)
- {
- int a,b=i;
- for(a=0;a<50000;a++,i=b)
- while(i--);
- }
- void close()
- {
- system("cls");
- }
复制代码
|