发布时间:2025-12-11 02:37:05 浏览次数:1
此次贪吃蛇小游戏的目的是使得我在Linux底下使用vi进行编写的
心得:
1.自己对linux中如何使用vi更加熟悉
如::wq yy pp dd u 等等
2.对c语言的指针,结构体,链表等更加的牢固
3.借此小项目也运用到多线程作为进入linux的深入学习打下坚实的基础
代码展示
#include<curses.h>#include<stdlib.h>#defineUP1//1与-1的目的是使用abs()函数防止一上一下#defineDOWN-1#defineLEFT2#defineRIGHT-2structSnake{//创建一个结构体inthang;intlie;structSnake*next;};structSnake*head=NULL;//全局定义一个头和尾structSnake*tail=NULL;intkey;//定义一个按键的整形变量intdir;//定义一个方向的整形变量structSnakefood;voidinitFood(){//定义一个食物##可以随机生成intx=rand()%19;inty=rand()%19;food.hang=x;food.lie=y;}voidinitNcurse(){initscr();keypad(stdscr,1);noecho();}inthasSnakeNode(inti,intj){//显示蛇身体structSnake*p;p=head;while(p!=NULL){if(p->hang==i&&p->lie==j){return1;}p=p->next;}return0;}inthasFood(inti,intj){//有食物if(food.hang==i&&food.lie==j){return1;}return0;}voidgamePic(){//游戏图形化展示inthang;intlie;move(0,0);for(hang=0;hang<20;hang++){if(hang==0){for(lie=0;lie<20;lie++){printw("--");}printw("\n");}if(hang>=0&&hang<=19){for(lie=0;lie<=20;lie++){if(lie==0||lie==20){printw("|");}elseif(hasSnakeNode(hang,lie)){printw("[]");}elseif(hasFood(hang,lie)){printw("##");}else{printw("");}}printw("\n");}if(hang==19){for(lie=0;lie<20;lie++){printw("--");}printw("\n");printw("byricko");}}}voidaddNode(){//加头并且方向structSnake*new=(structSnake*)malloc(sizeof(structSnake));new->next=NULL;switch(dir){caseUP:new->hang=tail->hang-1;new->lie=tail->lie;break;caseDOWN:new->hang=tail->hang+1;new->lie=tail->lie;break;caseLEFT:new->hang=tail->hang;new->lie=tail->lie-1;break;caseRIGHT:new->hang=tail->hang;new->lie=tail->lie+1;break;}tail->next=new;tail=new;}voidinitSnake(){//初始化蛇structSnake*p;dir=RIGHT;while(head!=NULL){p=head;head=head->next;free(p);}initFood();head=(structSnake*)malloc(sizeof(structSnake));head->hang=1;head->lie=1;head->next=NULL;tail=head;addNode();addNode();addNode();addNode();}voiddeleNode(){//删除最后节点structSnake*p;p=head;head=head->next;free(p);}intifSnakeDie(){//在撞到边界以及自己迟到自己的时候会输出一个1让自己复活structSnake*p;p=head;if(tail->hang<0||tail->lie==0||tail->hang==20||tail->lie==20){return1;}while(p->next!=NULL){if(p->hang==tail->hang&&p->lie==tail->lie){return1;}p=p->next;}return0;}voidmoveSnake(){//蛇的移动addNode();if(hasFood(tail->hang,tail->lie)){//如果吃到食物就不删除最后的节点initFood();}else{deleNode();}if(ifSnakeDie()){initSnake();}}voidrefreshJieMian(){//刷新界面线程while(1){moveSnake();gamePic();refresh();usleep(150000);//刷新频率}}voidturn(intdirection){//防止方向键按了上又按下if(abs(dir)!=abs(direction)){dir=direction;}}voidchangeDir(){//改变方向while(1){key=getch();switch(key){caseKEY_DOWN:turn(DOWN);break;caseKEY_UP:turn(UP);break;caseKEY_LEFT:turn(LEFT);break;caseKEY_RIGHT:turn(RIGHT);break;}}}intmain(){pthread_tt1;//定义线程1pthread_tt2;initNcurse();//初始化ncurseinitSnake();//初始化蛇gamePic();//初始化界面pthread_create(&t1,NULL,refreshJieMian,NULL);//启动线程里面的函数pthread_create(&t2,NULL,changeDir,NULL);while(1);//线程3getch();endwin();return0;}对代码进行编译
gccsnake.c-lcurses-lpthread
生成a.out运行文件
运行代码
./a.out
图片展示
“Linux下C语言如何实现贪吃蛇小游戏”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!