基本思路:蛇每吃一个食物蛇身子就增加一格,用UP,DOWN,LEFT,RIGHT控制蛇头的运动,而蛇身子跟着蛇头走,每后一格蛇身子下一步走到上一格蛇身子的位置,以此类推。#include<stdio.h>#include<conio.h>#include<windows.h>#defineBEG_X2#defineBEG_Y1#defineWID20#defineHEI20HANDLEhout;typedefenum{UP,DOWN,LEFT,RIGHT}DIR;typedefstructSnake_body{COORDpos;//蛇身的位置structSnake_body*next;//下一个蛇身structSnake_body*prev;//前一个蛇身}SNAKE,*PSNAKE;PSNAKEhead=NULL;//蛇头PSNAKEtail=NULL;//蛇尾//画游戏边框的函数voidDrawBorder(){inti,j;COORDpos={BEG_X,BEG_Y};for(i=0;i<HEI;++i){SetConsoleCursorPosition(hout,pos);for(j=0;j<WID;++j){if(i==0)//第一行{if(j==0)printf("┏");elseif(j==WID-1)printf("┓");elseprintf("━");}elseif(i==HEI-1)//最后一行{if(j==0)printf("┗");elseif(j==WID-1)printf("┛");elseprintf("━");}elseif(j==0||j==WID-1)//第一列或最后一列printf("┃");elseprintf("");}++pos.Y;}}//添加蛇身的函数voidAddBody(COORDpos){PSNAKEpnew=(PSNAKE)calloc(1,sizeof(SNAKE));pnew->pos=pos;if(!head){head=tail=pnew;}else{pnew->next=head;//新创建蛇身的next指向原先的蛇头head->prev=pnew;//原先的蛇头的prev指向新创建的蛇身head=pnew;//把新创建的蛇身作为新的蛇头}SetConsoleCursorPosition(hout,head->pos);printf("◎");}//蛇身移动的函数voidMoveBody(DIRdir){PSNAKEptmp;COORDpos=head->pos;switch(dir){caseUP:if(head->pos.Y>BEG_Y+1)--pos.Y;elsereturn;break;caseDOWN:if(head->pos.Y<BEG_Y+HEI-2)++pos.Y;elsereturn;break;caseLEFT:if(head->pos.X>BEG_X+2)pos.X-=2;elsereturn;break;caseRIGHT:if(head->pos.X<BEG_X+(WID-2)*2)pos.X+=2;elsereturn;break;}AddBody(pos);//添加了一个新的蛇头ptmp=tail;//保存当前的蛇尾tail=tail->prev;if(tail)tail->next=NULL;SetConsoleCursorPosition(hout,ptmp->pos);printf("");free(ptmp);}intmain(){intctrl;DIRdir=RIGHT;//初始蛇的方向是向右的COORDpos={BEG_X+2,BEG_Y+HEI/2};system("color0E");system("modeconcols=90lines=30");hout=GetStdHandle(STD_OUTPUT_HANDLE);printf("------------贪吃蛇的移动------------");DrawBorder();//自定义几个蛇的身体AddBody(pos);pos.X+=2;AddBody(pos);pos.X+=2;AddBody(pos);pos.X+=2;AddBody(pos);pos.X+=2;AddBody(pos);pos.X+=2;AddBody(pos);pos.X+=2;AddBody(pos);//控制蛇的移动while(ctrl=getch()){switch(ctrl){case'w':if(dir==DOWN)continue;dir=UP;break;case's':if(dir==UP)continue;dir=DOWN;break;case'a':if(dir==RIGHT)continue;dir=LEFT;break;case'd':if(dir==LEFT)continue;dir=RIGHT;break;case'q':return0;}MoveBody(dir);}return0;}