设为首页 加入收藏

TOP

纯C语言写的贪吃蛇源码
2014-11-23 21:27:41 来源: 作者: 【 】 浏览:11
Tags:语言 源码
#include
  
   
#include
   
     #include
    
      #include
     
       #include <
      windows.h> #define N 225 struct Food { int x; int y; int yes;//1表示需要出现新食物,0表示已有食物。 }food; struct Snake { struct Food body[N]; int life;//1表示蛇死啦,0表示蛇活着。 int node;//蛇的节数。 char direction;//蛇自动运动的方向。 }snake; int score=0; int main() { FILE *p; int i,j,k,b; char map[16][16],c; p=fopen("E:\\file.txt","r"); if(p==NULL) { printf("error"); exit(1); } for(i=0;i<16;i++) { for(j=0;j<16;j++) { map[i][j]=fgetc(p); } fgetc(p); } snake.body[0].x=8;//蛇头。 snake.body[0].y=8; snake.body[1].x=8; snake.body[1].y=7; snake.body[2].x=8; snake.body[2].y=6; snake.node=3;//蛇的节数。 food.yes=1; srand(time(NULL)); snake.direction='d';//一开始蛇自动往右跑。 while(1) { if(kbhit()) { c=getch(); if(snake.life==1) break; if(c=='w' && snake.direction!='s') snake.direction='w'; else if(c=='a' && snake.direction!='d') snake.direction='a'; else if(c=='s' && snake.direction!='w') snake.direction='s'; else if(c=='d' && snake.direction!='a') snake.direction='d'; } if(food.yes==1)//需要随机出现新的食物。 { food.x=1+rand()%14; food.y=1+rand()%14; for(i=0;i
      
       0;i--)//蛇往前移动。 { snake.body[i].x=snake.body[i-1].x; snake.body[i].y=snake.body[i-1].y; } switch(snake.direction)//蛇头方向。 { case'a': snake.body[0].y-=1; break; case'w': snake.body[0].x-=1; break; case'd': snake.body[0].y+=1; break; case's': snake.body[0].x+=1; break; } if(food.yes==0)//显示蛇,食物和围墙。 { system("cls"); for(i=0;i<16;i++) { for(j=0;j<16;j++) { b = 1; for(k=0;k
       
        0 && j<15 && j>0)//食物。 printf("★"); else if(map[i][j]=='1') printf("■"); else printf(" "); } } putchar('\n'); } Sleep(250);//休眠函数。 } for(i=3;i
        
         =15 || snake.body[0].x<=0 || snake.body[0].y>=15 || snake.body[0].y<=0) { printf("蛇撞墙死了!\n"); printf("共得分:%d\n",score); snake.life=1; break; } } fclose(p); return 0; }
        
       
      
     
    
   
  
下面是file.txt:
1111111111111111
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1000000000000001
1111111111111111

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇简单的多态实例 下一篇C语言初学者代码中的常见错误与瑕..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: