您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > C语言写的简单贪吃蛇-vc6.0编译通过
#includeiostreamusingnamespacestd;#includewindows.h#includestdlib.h#includetime.h#definessize20#definevsize40//地图的水平和垂直尺寸#defineSL200intkey=3,count=0,life=0,whefd=0,score=0,level=1;//k是控制键,count是时间延迟计数器,p死亡证明,m地图上是否有食物。score是分数,level等级。structsnake{intbody[100][2],lenght,direction;}snake;structmap{charpla[ssize][vsize];}map;voidinit_map(){//初始化地图for(inti=0;issize;i++)for(intj=0;jvsize;j++){map.pla[i][j]='';}}voidinit_snake(){//初始化蛇,初始长度为3,方向为右。snake.lenght=3;for(inti=0;isnake.lenght;i++){snake.body[0][0]=ssize/2;snake.body[0][1]=snake.lenght-1;map.pla[ssize/2][snake.lenght-1]='@';}snake.direction=3;}voidprint_map(){//打印地图和蛇for(inti=-1;i=ssize;i++){for(intj=-1;j=vsize;j++){if((i==-1&&j==-1)||(i==ssize&&j==-1)||(j==vsize&&i==-1)||(j==vsize&&i==ssize))cout+;elseif(i==-1||i==ssize)cout-;elseif(j==-1||j==vsize)cout|;elsecoutmap.pla[i][j];}coutendl;}}voiddead(){life=1;}voidfood(){//出现食物intx,y,k=1;while(k){x=rand()%ssize;y=rand()%ssize;if(map.pla[x][y]!='@'){map.pla[x][y]=14;k=0;whefd=1;}}}voidmove(){//移动intx,y,n=0;x=snake.body[snake.lenght-1][0];//记录蛇尾y=snake.body[snake.lenght-1][1];for(inti=snake.lenght-1;i0;i--){//将除蛇头外的每一节向前移动一位snake.body[i][0]=snake.body[i-1][0];snake.body[i][1]=snake.body[i-1][1];}if((key+snake.direction)!=5)//按键方向与当前方向相反则无效snake.direction=key;//按键方向有效时,改变蛇的方向。if(snake.direction==1)//1423分别为上下左右。snake.body[0][0]--;elseif(snake.direction==4)snake.body[0][0]++;elseif(snake.direction==2)snake.body[0][1]--;elseif(snake.direction==3)snake.body[0][1]++;if(snake.body[0][0]0||snake.body[0][0]=ssize||snake.body[0][1]0||snake.body[0][1]=vsize)//超界死亡dead();if(map.pla[snake.body[0][0]][snake.body[0][1]]=='@')//撞中自己死亡dead();if(map.pla[snake.body[0][0]][snake.body[0][1]]==14){//吃到食物whefd=0;n=1;score+=level*10;snake.lenght++;if(score=100){//满足升级分数level++;}}if(life==0){map.pla[snake.body[0][0]][snake.body[0][1]]='@';//打印蛇头}if(life==0||n==0)//消去爬行痕迹map.pla[x][y]='';count=0;//延迟计数清零}intcontrol(){//方向控制if(GetKeyState(VK_UP)0)return1;//1表示按下上键if(GetKeyState(VK_DOWN)0)return4;//4表示按下下键if(GetKeyState(VK_LEFT)0)return2;//2表示按下左键if(GetKeyState(VK_RIGHT)0)return3;//3表示按下右键if(GetKeyState(VK_RETURN)0)return5;//暂停returnkey;}voidplay(){//游戏开始while(life==0){key=control();if(key==5){system(pause);}if(count==120000/level){if(whefd==0)//地图上没有食物food();move();//移动if(life==0){system(cls);print_map();}cout关卡:level分数:score方向:keyendl;}count++;}}intmain(){system(colorE2);system(modeconcols=44lines=25);srand(time(NULL));init_map();init_snake();print_map();play();if(life==1){coutsorry,youaredead!endl;coutlevel:levelscore:scoreendl;}system(pause);return0;}
本文标题:C语言写的简单贪吃蛇-vc6.0编译通过
链接地址:https://www.777doc.com/doc-5160517 .html