c語(yǔ)言代碼實(shí)現(xiàn)貪吃蛇動(dòng)畫(huà)的方法:首先確定基本思路,蛇每吃一個(gè)食物蛇身子就增加一格;然后用up,down,left,right控制蛇頭的運(yùn)動(dòng),而蛇身子跟著蛇頭走;最后每后一格蛇身子下一步走到上一格蛇身子的位置。
基本思路:
蛇每吃一個(gè)食物蛇身子就增加一格,用up, down, left, right控制蛇頭的運(yùn)動(dòng),而蛇身子跟著蛇頭走,每后一格蛇身子下一步走到上一格蛇身子的位置,以此類推。
#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;//下一個(gè)蛇身struct snake_body *prev;//前一個(gè)蛇身}snake, *psnake;psnake head = null;//蛇頭psnake tail = null;//蛇尾//畫(huà)游戲邊框的函數(shù)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;}}//添加蛇身的函數(shù)void addbody(coord pos){psnake pnew = (psnake)calloc(1, sizeof(snake));pnew->pos = pos;if(!head){head = tail = pnew;}else{pnew->next = head;//新創(chuàng)建蛇身的next指向原先的蛇頭head->prev = pnew;//原先的蛇頭的prev指向新創(chuàng)建的蛇身head = pnew;//把新創(chuàng)建的蛇身作為新的蛇頭}setconsolecursorposition(hout, head->pos);printf("◎");}//蛇身移動(dòng)的函數(shù)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);//添加了一個(gè)新的蛇頭ptmp = tail;//保存當(dāng)前的蛇尾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(" ------------貪吃蛇的移動(dòng)------------");drawborder();//自定義幾個(gè)蛇的身體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);//控制蛇的移動(dòng)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;}