如何使用c语言代码实现贪吃蛇动画
如何使用c语言代码实现贪吃蛇动画?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
c语言代码实现贪吃蛇动画的方法:首先确定基本思路,蛇每吃一个食物蛇身子就增加一格;然后用UP,DOWN,LEFT,RIGHT控制蛇头的运动,而蛇身子跟着蛇头走;最后每后一格蛇身子下一步走到上一格蛇身子的位置。
基本思路:
蛇每吃一个食物蛇身子就增加一格,用UP, DOWN, LEFT, RIGHT控制蛇头的运动,而蛇身子跟着蛇头走,每后一格蛇身子下一步走到上一格蛇身子的位置,以此类推。
#include <stdio.h>#include <conio.h>#include <windows.h>#define BEG_X 2#define BEG_Y 1#define WID 20#define HEI 20HANDLE hout;typedef enum {UP, DOWN, LEFT, RIGHT} DIR;typedef struct Snake_body{COORD pos;//蛇身的位置struct Snake_body *next;//下一个蛇身struct Snake_body *prev;//前一个蛇身}SNAKE, *PSNAKE;PSNAKE head = NULL;//蛇头PSNAKE tail = NULL;//蛇尾//画游戏边框的函数void DrawBorder(){int i, j;COORD pos = {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("┏");else if(j == WID - 1)printf("┓");elseprintf("━");}else if(i == HEI - 1)//最后一行{if(j == 0)printf("┗");else if(j == WID - 1)printf("┛");elseprintf("━");}else if(j == 0 || j == WID - 1)//第一列或最后一列printf("┃");elseprintf(" ");}++pos.Y;}}//添加蛇身的函数void AddBody(COORD pos){PSNAKE pnew = (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("◎");}//蛇身移动的函数void MoveBody(DIR dir){PSNAKE ptmp;COORD pos = head->pos;switch(dir){case UP:if(head->pos.Y > BEG_Y + 1)--pos.Y;elsereturn;break;case DOWN:if(head->pos.Y < BEG_Y + HEI - 2)++pos.Y;elsereturn;break;case LEFT:if(head->pos.X > BEG_X + 2)pos.X -= 2;elsereturn;break;case RIGHT:if(head->pos.X < BEG_X + (WID - 2) * 2)pos.X += 2;else return;break;}AddBody(pos);//添加了一个新的蛇头ptmp = tail;//保存当前的蛇尾tail = tail->prev;if(tail)tail->next = NULL;SetConsoleCursorPosition(hout, ptmp->pos);printf(" ");free(ptmp);}int main(){int ctrl;DIR dir = RIGHT;//初始蛇的方向是向右的COORD pos = {BEG_X + 2, BEG_Y + HEI / 2};system("color 0E");system("mode con cols=90 lines=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':return 0;}MoveBody(dir);}return 0;}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。