linux终端下详解贪吃蛇

来源:互联网 发布:软件 专利 编辑:程序博客网 时间:2024/05/16 05:00

 大一学习C语言的时候就想要用Turbo C编写一个视频小游戏出来,种种原因后面搁浅了,现在借着学习Linux系统编程的劲头,编写了一个终端下可以运行的贪吃蛇游戏,其中此视频游戏用到的一些知识和操作系统运行时候的一些简单功能有点类似,引用《Unix/Linux 编程实践教程》(Bruce Molay著)里面所介绍的视频游戏一般的编写以及同操作系统的关系的原文如下:

  一、视频游戏如何做

  (1)空间:游戏必须在计算机屏幕的特定位置画影像。程序如何控制视频显示?

  (2)时间:影像以不同的速度在屏幕上移动。以一个特定的时间间隔改变位置。程序是如何获知时间并且在特定的时间安排事情的发生?

  (3)中断:程序再屏幕上平滑移动的物体,用户可以在任何时刻产生输入。程序是如何响应中断的?

  (4)同时做几件事:游戏必须在保持几个物体移动的同时还要响应中断。程序是如何同时做多件事情而不被弄得晕头转向的?

  二、操作系统面临着类似的问题

  操作系统同样要面对这4个问题。内核将程序载入内存空间并维护每个程序在内存中所处的位置。在内核的调度下,程序以时间片间隔的方式运行,同时,内核也在特定的时刻运行特定的内部任务。内核必须在很短的时间内响应用户和外设在任何时刻的输入。同时做几件事需要一些技巧。内核是如何保证数据的有序和规整的?

  上面的都是那本书上说的,个人觉得讲的很好,看完这本后再看那本Linux圣经《Unix环境高级编程》或许更好些。回归正题吧,主要介绍一下设计一个终端下的贪吃蛇游戏所实现的功能以及所需要的几个条件和一些函数。

  本贪吃蛇实现的功能是通过吃食物来增长自己的长度,可以利用按键 'f' 实现加速和 's' 键实现减速, 'q' 键退出,方向键控制方向,蛇要是碰到自己的身体或者碰到墙或者吃到一定数量,那么游戏就结束。功能还是挺简单的吧,下面就介绍下各个步骤的设计:

  1.首先要使用终端图形库curses.h文件,由于不是C标准库,一般电脑不会自带,需要自行下载安装,ubuntu下可以这么下载  sudo apt-get install libncurses5-dev  已经替换成ncurses.h 即 new curses.h的意思,完全兼容curses。介绍下此游戏需要用到的常见的几个curses函数。

基本curse函数initscr()初始化curses库和ttyendwin()关闭curses并重置ttyrefresh()刷新屏幕显示mvaddch(y,x,c)在坐标(y,x)处显示字符cmvaddstr(y,x,str)在坐标(y,x)处显示字符串strcbreak()开启输入立即响应noecho()输入不回显到屏幕curs_set(0)使光标不可见attrset()开启图形显示模式keypad(stdscr, true)开启小键盘方向键输入捕捉支持

更详细的可以  man ncurses   或者参见http://bbs.chinaunix.net/viewthread.php?tid=909369

  2.介绍完ncurses图形库,接下来进行屏幕绘图,我初始化屏幕效果图见下图所示:先是外围边框,然后是蛇“@”和食物“*”。

废话不多说,上代码吧。


首先是头文件 snake.h的代码:由于在纯文本模式下编程以及本人英语水平有限,可能有的注释比较别扭。

view plainprint?
  1. <span style="font-size: 13px; ">/* Game: snake        version: 1.0    date:2011/08/22 
  2.  * Author: Dream Fly 
  3.  * filename: snake.h 
  4.  */  
  5.   
  6. #define SNAKE_SYMBOL    '@'     /* snake body and food symbol */  
  7. #define FOOD_SYMBOL     '*'  
  8. #define MAX_NODE        30      /* maximum snake nodes */  
  9. #define DFL_SPEED       50      /* snake default speed */  
  10. #define TOP_ROW     5           /* top_row */  
  11. #define BOT_ROW     LINES - 1  
  12. #define LEFT_EDGE   0  
  13. #define RIGHT_EDGE  COLS - 1  
  14.   
  15. typedef struct node         /* Snake_node structure */  
  16. {  
  17.     int x_pos;  
  18.     int y_pos;  
  19.     struct node *prev;  
  20.     struct node *next;  
  21. } Snake_Node;  
  22.   
  23. struct position             /* food position structure */  
  24. {  
  25.     int x_pos;  
  26.     int y_pos;  
  27. } ;  
  28. void Init_Disp();           /* init and display the interface */  
  29. void Food_Disp();           /* display the food position */  
  30. void Wrap_Up();             /* turn off the curses */  
  31. void Key_Ctrl();            /* using keyboard to control snake */  
  32. int set_ticker(int n_msecs);/* ticker */  
  33.   
  34. void DLL_Snake_Create();    /* create double linked list*/  
  35. void DLL_Snake_Insert(int x, int y);    /* insert node */  
  36. void DLL_Snake_Delete_Node();   /* delete a node */  
  37. void DLL_Snake_Delete();        /* delete all the linked list */  
  38.   
  39. void Snake_Move();          /* control the snake move and judge */  
  40. void gameover(int n);       /* different n means different state */</span>  
接下来是初始化界面图形的子函数:
view plainprint?
  1. <span style="font-size: 13px; ">/* Function: Init_Disp() 
  2.  * Usage: init and display the interface 
  3.  * Return: none 
  4.  */  
  5. void Init_Disp()  
  6. {  
  7.     char wall = ' ';  
  8.     int i, j;  
  9.     initscr();  
  10.     cbreak();               /* put termial to CBREAK mode */  
  11.     noecho();  
  12.     curs_set(0);            /* set cursor invisible */  
  13.   
  14.     /* display some message about title and wall */  
  15.     attrset(A_NORMAL);      /* set NORMAL first */  
  16.     attron(A_REVERSE);      /* turn on REVERSE to display the wall */  
  17.     for(i = 0; i < LINES; i++)  
  18.     {  
  19.         mvaddch(i, LEFT_EDGE, wall);  
  20.         mvaddch(i, RIGHT_EDGE, wall);  
  21.     }  
  22.     for(j = 0; j < COLS; j++)  
  23.     {  
  24.         mvaddch(0, j, '=');  
  25.         mvaddch(TOP_ROW, j, wall);  
  26.         mvaddch(BOT_ROW, j, wall);  
  27.     }  
  28.     attroff(A_REVERSE);     /* turn off REVERSE */  
  29.     mvaddstr(1, 2, "Game: snake    version: 1.0    date: 2011/08/22");  
  30.     mvaddstr(2, 2, "Author: Dream Fly   Blog: blog.csdn.net/jjzhoujun2010");  
  31.     mvaddstr(3, 2, "Usage: Press 'f' to speed up, 's' to speed down,'q' to quit.");  
  32.     mvaddstr(4, 2, "       Nagivation key controls snake moving.");  
  33.     refresh();  
  34. }  
  35.   
  36. /* Function: Food_Disp() 
  37.  * Usage: display food position 
  38.  * Return: none 
  39.  */  
  40. void Food_Disp()  
  41. {  
  42.     srand(time(0));  
  43.     food.x_pos = rand() % (COLS - 2) + 1;  
  44.     food.y_pos = rand() % (LINES - TOP_ROW - 2) + TOP_ROW + 1;  
  45.     mvaddch(food.y_pos, food.x_pos, FOOD_SYMBOL);/* display the food */  
  46.     refresh();  
  47. }  
  48.   
  49. /* Function: DLL_Snake_Create() 
  50.  * Usage: create double linked list, and display the snake first node 
  51.  * Return: none 
  52.  */  
  53. void DLL_Snake_Create()  
  54. {  
  55.     Snake_Node *temp = (Snake_Node *)malloc(sizeof(Snake_Node));  
  56.     head = (Snake_Node *)malloc(sizeof(Snake_Node));  
  57.     tail = (Snake_Node *)malloc(sizeof(Snake_Node));  
  58.     if(temp == NULL || head == NULL || tail == NULL)  
  59.         perror("malloc");  
  60.     temp->x_pos = 5;  
  61.     temp->y_pos = 10;  
  62.     head->prev =NULL;  
  63.     tail->next = NULL;  
  64.     head->next = temp;  
  65.     temp->next = tail;  
  66.     tail->prev = temp;  
  67.     temp->prev = head;  
  68.     mvaddch(temp->y_pos, temp->x_pos, SNAKE_SYMBOL);  
  69.     refresh();  
  70. }  
  71. </span>  

  3.接下来就是蛇的移动问题,这个是核心部分以及最困难的设计部分了,我采用的是蛇用双向链表的结构来构造出来,分别有一个head 和tail指针,用来添加和删除元素。这里若要实现移动的话(未碰到食物前),就是在链表的头部(head的下一个)插入一个新元素,记录下此时的坐标,用mvaddch(y,x,c)函数添加蛇的图形'@',与此同时,在链表尾部(tail的前一个)删除一个节点,同时这里的坐标用mvaddch(y,x, ' ')添加了' '空白字符,实现删除效果,最后加上refresh(). 这样就可以看到蛇在“移动”了。当然,要是碰到食物的话,尾部节点处就不用删除,达到增长长度的效果。

  那么,接下来的问题是:如何触发蛇的移动呢?如何实现均匀移动以及通过按键 ‘f’ 或 's' 改变运动速度呢?这里我采用的是信号计时中断调用的函数  signal(SIGALRM, Snake_Move) 和 间隔计数器 来实现,通过产生相同间隔的时间片段来不断地调用Snake_Move()函数来执行相应的功能。加减速的功能是通过设定其他变量ttm, ttg来实现再此基本计数器上面再次分频的效果来加减速,ttm, ttg 越大,减速越明显,反之则相反效果。  具体的间隔计数器的函数设计见下:(参考了以上所提书本上的函数)

view plainprint?
  1. /* Function: set_ticker(number_of_milliseconds) 
  2.  * Usage: arrange for interval timer to issue SIGALRM's at regular intervals 
  3.  * Return: -1 on error, 0 for ok 
  4.  * arg in milliseconds, converted into whole seconds and microseconds 
  5.  * note: set_ticker(0) turns off ticker 
  6.  */  
  7. int set_ticker(int n_msecs)  
  8. {  
  9.     struct itimerval new_timeset;  
  10.     long n_sec, n_usecs;  
  11.   
  12.     n_sec = n_msecs / 1000;                 /* int second part */  
  13.     n_usecs = (n_msecs % 1000) * 1000L;     /* microsecond part */  
  14.   
  15.     new_timeset.it_interval.tv_sec = n_sec; /* set reload */  
  16.     new_timeset.it_interval.tv_usec = n_usecs;  
  17.   
  18.     new_timeset.it_value.tv_sec = n_sec;    /* set new ticker value */  
  19.     new_timeset.it_value.tv_usec = n_usecs;  
  20.   
  21.     return setitimer(ITIMER_REAL, &new_timeset, NULL);  
  22. }  

  蛇的移动的函数代码如下:

view plainprint?
  1. void Snake_Move()  
  2. {  
  3.     static int length = 1;      /* length of snake */  
  4.     int Length_Flag = 0;        /* default snake's length no change */  
  5.     int moved = 0;  
  6.     signal(SIGALRM, SIG_IGN);  
  7.     /* judge if the snake crash the wall */  
  8.     if((head->next->x_pos == RIGHT_EDGE-1 && x_dir == 1)   
  9.         || (head->next->x_pos == LEFT_EDGE+1 && x_dir == -1)  
  10.         || (head->next->y_pos == TOP_ROW+1 && y_dir == -1)  
  11.         || (head->next->y_pos == BOT_ROW-1 && y_dir == 1))  
  12.     {  
  13.         gameover(1);  
  14.     }  
  15.     /* judge if the snake crash itself */  
  16.     if(mvinch(head->next->y_pos + y_dir, head->next->x_pos + x_dir) == '@')  
  17.         gameover(2);  
  18.   
  19.     if(ttm > 0 && ttg-- == 1)  
  20.     {  
  21.         /* snake moves */  
  22.         DLL_Snake_Insert(head->next->x_pos + x_dir, head->next->y_pos + y_dir);  
  23.         ttg = ttm;      /* reset */  
  24.         moved = 1;      /* snake can move */  
  25.     }  
  26.     if(moved)  
  27.     {  
  28.         /* snake eat the food */  
  29.         if(head->next->x_pos == food.x_pos && head->next->y_pos == food.y_pos)  
  30.         {  
  31.             Length_Flag = 1;  
  32.             length++;  
  33.             /* Mission Complete */  
  34.             if(length >= MAX_NODE)  
  35.                 gameover(0);  
  36.             /* reset display the food randomly */  
  37.             Food_Disp();  
  38.         }  
  39.         if(Length_Flag == 0)  
  40.         {  
  41.             /* delete the tail->prev node */  
  42.             mvaddch(tail->prev->y_pos, tail->prev->x_pos, ' ');  
  43.             DLL_Snake_Delete_Node();  
  44.         }  
  45.         mvaddch(head->next->y_pos, head->next->x_pos, SNAKE_SYMBOL);  
  46.         refresh();  
  47.     }  
  48.     signal(SIGALRM, Snake_Move);  
  49. }  

主要函数的实现就是这些,以下贴上完整的源代码供大家参考,或者去这里下载:http://download.csdn.net/source/3540117
view plainprint?
  1. /* Game: snake      version: 1.0    date:2011/08/22 
  2.  * Author: Dream Fly 
  3.  * filename: snake.h 
  4.  */  
  5.   
  6. #define SNAKE_SYMBOL    '@'     /* snake body and food symbol */  
  7. #define FOOD_SYMBOL     '*'  
  8. #define MAX_NODE        30      /* maximum snake nodes */  
  9. #define DFL_SPEED       50      /* snake default speed */  
  10. #define TOP_ROW     5           /* top_row */  
  11. #define BOT_ROW     LINES - 1  
  12. #define LEFT_EDGE   0  
  13. #define RIGHT_EDGE  COLS - 1  
  14.   
  15. typedef struct node         /* Snake_node structure */  
  16. {  
  17.     int x_pos;  
  18.     int y_pos;  
  19.     struct node *prev;  
  20.     struct node *next;  
  21. } Snake_Node;  
  22.   
  23. struct position             /* food position structure */  
  24. {  
  25.     int x_pos;  
  26.     int y_pos;  
  27. } ;  
  28. void Init_Disp();           /* init and display the interface */  
  29. void Food_Disp();           /* display the food position */  
  30. void Wrap_Up();             /* turn off the curses */  
  31. void Key_Ctrl();            /* using keyboard to control snake */  
  32. int set_ticker(int n_msecs);/* ticker */  
  33.   
  34. void DLL_Snake_Create();    /* create double linked list*/  
  35. void DLL_Snake_Insert(int x, int y);    /* insert node */  
  36. void DLL_Snake_Delete_Node();   /* delete a node */  
  37. void DLL_Snake_Delete();        /* delete all the linked list */  
  38.   
  39. void Snake_Move();          /* control the snake move and judge */  
  40. void gameover(int n);       /* different n means different state */  

view plainprint?
  1. /* Filename: snake.c    version:1.0     date: 2011/08/22 
  2.  * Author: Dream Fly    blog: blog.csdn.net/jjzhoujun2010 
  3.  * Usage: 'f' means speed up, 's' means speed down, 'q' means quit; 
  4.  * Navigation key controls the snake moving.  
  5.  * Compile: gcc snake.c -lncurses -o snake 
  6.  */  
  7.   
  8. #include<stdio.h>  
  9. #include<stdlib.h>  
  10. #include<ncurses.h>  
  11. #include<sys/time.h>  
  12. #include<signal.h>  
  13. #include"snake.h"  
  14.   
  15. struct position food;       /* food position */  
  16. Snake_Node *head, *tail;    /* double linked list's head and tail */  
  17. int x_dir = 1, y_dir = 0;   /* init dirction of the snake moving */  
  18. int ttm = 5, ttg = 5;           /* two timers defined to control speed */  
  19.   
  20. void main(void)  
  21. {  
  22.     Init_Disp();            /* init and display the interface */  
  23.     Food_Disp();            /* display food */  
  24.     DLL_Snake_Create();     /* create double linked list and display snake*/  
  25.     signal(SIGALRM, Snake_Move);  
  26.     set_ticker(DFL_SPEED);  
  27.     Key_Ctrl();             /* using keyboard to control snake */  
  28.     Wrap_Up();              /* turn off the curses */  
  29. }  
  30.   
  31. /* Function: Init_Disp() 
  32.  * Usage: init and display the interface 
  33.  * Return: none 
  34.  */  
  35. void Init_Disp()  
  36. {  
  37.     char wall = ' ';  
  38.     int i, j;  
  39.     initscr();  
  40.     cbreak();               /* put termial to CBREAK mode */  
  41.     noecho();  
  42.     curs_set(0);            /* set cursor invisible */  
  43.   
  44.     /* display some message about title and wall */  
  45.     attrset(A_NORMAL);      /* set NORMAL first */  
  46.     attron(A_REVERSE);      /* turn on REVERSE to display the wall */  
  47.     for(i = 0; i < LINES; i++)  
  48.     {  
  49.         mvaddch(i, LEFT_EDGE, wall);  
  50.         mvaddch(i, RIGHT_EDGE, wall);  
  51.     }  
  52.     for(j = 0; j < COLS; j++)  
  53.     {  
  54.         mvaddch(0, j, '=');  
  55.         mvaddch(TOP_ROW, j, wall);  
  56.         mvaddch(BOT_ROW, j, wall);  
  57.     }  
  58.     attroff(A_REVERSE);     /* turn off REVERSE */  
  59.     mvaddstr(1, 2, "Game: snake    version: 1.0    date: 2011/08/22");  
  60.     mvaddstr(2, 2, "Author: Dream Fly   Blog: blog.csdn.net/jjzhoujun2010");  
  61.     mvaddstr(3, 2, "Usage: Press 'f' to speed up, 's' to speed down,'q' to quit.");  
  62.     mvaddstr(4, 2, "       Nagivation key controls snake moving.");  
  63.     refresh();  
  64. }  
  65.   
  66. /* Function: Food_Disp() 
  67.  * Usage: display food position 
  68.  * Return: none 
  69.  */  
  70. void Food_Disp()  
  71. {  
  72.     srand(time(0));  
  73.     food.x_pos = rand() % (COLS - 2) + 1;  
  74.     food.y_pos = rand() % (LINES - TOP_ROW - 2) + TOP_ROW + 1;  
  75.     mvaddch(food.y_pos, food.x_pos, FOOD_SYMBOL);/* display the food */  
  76.     refresh();  
  77. }  
  78.   
  79. /* Function: DLL_Snake_Create() 
  80.  * Usage: create double linked list, and display the snake first node 
  81.  * Return: none 
  82.  */  
  83. void DLL_Snake_Create()  
  84. {  
  85.     Snake_Node *temp = (Snake_Node *)malloc(sizeof(Snake_Node));  
  86.     head = (Snake_Node *)malloc(sizeof(Snake_Node));  
  87.     tail = (Snake_Node *)malloc(sizeof(Snake_Node));  
  88.     if(temp == NULL || head == NULL || tail == NULL)  
  89.         perror("malloc");  
  90.     temp->x_pos = 5;  
  91.     temp->y_pos = 10;  
  92.     head->prev =NULL;  
  93.     tail->next = NULL;  
  94.     head->next = temp;  
  95.     temp->next = tail;  
  96.     tail->prev = temp;  
  97.     temp->prev = head;  
  98.     mvaddch(temp->y_pos, temp->x_pos, SNAKE_SYMBOL);  
  99.     refresh();  
  100. }  
  101.   
  102. /* Function: Snake_Move() 
  103.  * Usage: use Navigation key to control snake moving, and judge 
  104.  * if the snake touch the food. 
  105.  * Return: 
  106.  */  
  107. void Snake_Move()  
  108. {  
  109.     static int length = 1;      /* length of snake */  
  110.     int Length_Flag = 0;        /* default snake's length no change */  
  111.     int moved = 0;  
  112.     signal(SIGALRM, SIG_IGN);  
  113.     /* judge if the snake crash the wall */  
  114.     if((head->next->x_pos == RIGHT_EDGE-1 && x_dir == 1)   
  115.         || (head->next->x_pos == LEFT_EDGE+1 && x_dir == -1)  
  116.         || (head->next->y_pos == TOP_ROW+1 && y_dir == -1)  
  117.         || (head->next->y_pos == BOT_ROW-1 && y_dir == 1))  
  118.     {  
  119.         gameover(1);  
  120.     }  
  121.     /* judge if the snake crash itself */  
  122.     if(mvinch(head->next->y_pos + y_dir, head->next->x_pos + x_dir) == '@')  
  123.         gameover(2);  
  124.   
  125.     if(ttm > 0 && ttg-- == 1)  
  126.     {  
  127.         /* snake moves */  
  128.         DLL_Snake_Insert(head->next->x_pos + x_dir, head->next->y_pos + y_dir);  
  129.         ttg = ttm;      /* reset */  
  130.         moved = 1;      /* snake can move */  
  131.     }  
  132.     if(moved)  
  133.     {  
  134.         /* snake eat the food */  
  135.         if(head->next->x_pos == food.x_pos && head->next->y_pos == food.y_pos)  
  136.         {  
  137.             Length_Flag = 1;  
  138.             length++;  
  139.             /* Mission Complete */  
  140.             if(length >= MAX_NODE)  
  141.                 gameover(0);  
  142.             /* reset display the food randomly */  
  143.             Food_Disp();  
  144.         }  
  145.         if(Length_Flag == 0)  
  146.         {  
  147.             /* delete the tail->prev node */  
  148.             mvaddch(tail->prev->y_pos, tail->prev->x_pos, ' ');  
  149.             DLL_Snake_Delete_Node();  
  150.         }  
  151.         mvaddch(head->next->y_pos, head->next->x_pos, SNAKE_SYMBOL);  
  152.         refresh();  
  153.     }  
  154.     signal(SIGALRM, Snake_Move);  
  155. }  
  156.   
  157. /* Function: set_ticker(number_of_milliseconds) 
  158.  * Usage: arrange for interval timer to issue SIGALRM's at regular intervals 
  159.  * Return: -1 on error, 0 for ok 
  160.  * arg in milliseconds, converted into whole seconds and microseconds 
  161.  * note: set_ticker(0) turns off ticker 
  162.  */  
  163. int set_ticker(int n_msecs)  
  164. {  
  165.     struct itimerval new_timeset;  
  166.     long n_sec, n_usecs;  
  167.   
  168.     n_sec = n_msecs / 1000;                 /* int second part */  
  169.     n_usecs = (n_msecs % 1000) * 1000L;     /* microsecond part */  
  170.   
  171.     new_timeset.it_interval.tv_sec = n_sec; /* set reload */  
  172.     new_timeset.it_interval.tv_usec = n_usecs;  
  173.   
  174.     new_timeset.it_value.tv_sec = n_sec;    /* set new ticker value */  
  175.     new_timeset.it_value.tv_usec = n_usecs;  
  176.   
  177.     return setitimer(ITIMER_REAL, &new_timeset, NULL);  
  178. }  
  179.   
  180. /* Function: Wrap_Up() 
  181.  * Usage: turn off the curses 
  182.  * Return: none 
  183.  */  
  184. void Wrap_Up()  
  185. {  
  186.     set_ticker(0);      /* turn off the timer */  
  187.     getchar();  
  188.     endwin();  
  189.     exit(0);  
  190. }  
  191.   
  192. /* Function: Key_Ctrl() 
  193.  * Usage: using keyboard to control snake action; 'f' means speed up, 
  194.  * 's' means speed down, 'q' means quit, navigation key control direction. 
  195.  * Return: none 
  196.  */  
  197. void Key_Ctrl()  
  198. {  
  199.     int c;  
  200.     keypad(stdscr, true);       /* use little keyboard Navigation Key */  
  201.     while(c = getch(), c != 'q')  
  202.     {  
  203.         if(c == 'f')  
  204.         {  
  205.             if(ttm == 1)  
  206.                 continue;  
  207.             ttm--;  
  208.         }  
  209.         else if(c == 's')  
  210.         {  
  211.             if(ttm == 8)  
  212.                 continue;  
  213.             ttm++;  
  214.         }  
  215.         if(c == KEY_LEFT)  
  216.         {  
  217.             if(tail->prev->prev->prev != NULL && x_dir == 1 && y_dir == 0)  
  218.                 continue/* it can't turn reverse when snake have length */  
  219.             x_dir = -1;  
  220.             y_dir = 0;  
  221.         }  
  222.         else if(c == KEY_RIGHT)  
  223.         {  
  224.             if(tail->prev->prev->prev != NULL && x_dir == -1 && y_dir == 0)  
  225.                 continue;  
  226.             x_dir = 1;  
  227.             y_dir = 0;  
  228.         }  
  229.         else if(c == KEY_UP)  
  230.         {  
  231.             if(tail->prev->prev->prev != NULL && x_dir == 0 && y_dir == 1)  
  232.                 continue;  
  233.             x_dir = 0;  
  234.             y_dir = -1;  
  235.         }  
  236.         else if(c == KEY_DOWN)  
  237.         {  
  238.             if(tail->prev->prev->prev != NULL && x_dir == 0 && y_dir == -1)  
  239.                 continue;  
  240.             x_dir = 0;  
  241.             y_dir = 1;  
  242.         }  
  243.     }  
  244. }  
  245.   
  246. /* Function: DLL_Snake_Insert(int x, int y) 
  247.  * Usage: Insert node in the snake. 
  248.  * Return: none 
  249.  */  
  250. void DLL_Snake_Insert(int x, int y)  
  251. {  
  252.     Snake_Node *temp = (Snake_Node *)malloc(sizeof(Snake_Node));  
  253.     if(temp == NULL)  
  254.         perror("malloc");  
  255.     temp->x_pos = x;  
  256.     temp->y_pos = y;  
  257.     temp->prev = head->next->prev;  
  258.     head->next->prev = temp;  
  259.     temp->next = head->next;  
  260.     head->next = temp;  
  261. }  
  262.   
  263. /* Function: gameover(int n) 
  264.  * Usage: gameover(0) means Mission Completes; gameover(1) means crashing 
  265.  * the wall; gameover(2) means crash itself. 
  266.  * Return: none 
  267.  */  
  268. void gameover(int n)  
  269. {  
  270.     switch(n)  
  271.     {  
  272.         case 0:   
  273.             mvaddstr(LINES / 2, COLS / 3 - 4, "Mission Completes,press any key to exit.\n");  
  274.             break;  
  275.         case 1:  
  276.             mvaddstr(LINES/2, COLS/3 - 4, "Game Over, crash the wall,press any key to exit.\n");  
  277.             break;  
  278.         case 2:  
  279.             mvaddstr(LINES/2, COLS/3 - 4, "Game Over, crash yourself,press any key to exit.\n");  
  280.             break;  
  281.         default:  
  282.             break;  
  283.     }  
  284.     refresh();  
  285.     /* delete the whole double linked list */  
  286.     DLL_Snake_Delete();  
  287.     Wrap_Up();  
  288. }  
  289.   
  290. /* Function: DLL_Snake_Delete_Node() 
  291.  * Usage: delete a tail node, not the whole linked list 
  292.  * Return: none 
  293.  */  
  294. void DLL_Snake_Delete_Node()  
  295. {  
  296.     Snake_Node *temp;  
  297.     temp = tail->prev;  
  298.     tail->prev = tail->prev->prev;  
  299.     temp->prev->next = tail;  
  300.     free(temp);  
  301. }  
  302.   
  303. /* Function: DLL_Snake_Delete() 
  304.  * Usage: delete the whole double linked list 
  305.  * Return: none 
  306.  */  
  307. void DLL_Snake_Delete()  
  308. {  
  309.     while(head->next != tail)  
  310.         DLL_Snake_Delete_Node();  
  311.     head->next = tail->prev = NULL;  
  312.     free(head);  
  313.     free(tail);  
  314. }  

  通过本程序可以加强自己对信号间隔计数器的理解,以及终端图形编程的理解和了解设计的此类游戏的一般思路,也实现了我大一学习C语言所想要实现的想法。本人第一次在CSDN上面把自己的一些编程想法写的比较详细,不足之处还请指出,共同讨论。

  参考资料:《Unix/Linux编程实践教程》    (美)Bruce Molay 著       杨宗源   黄海涛   译               清华大学出版社

http://note.sdo.com/my#!note/preview/xJ29Q~jAYzOpnM01Y0004K       curses库的使用

http://blog.sina.com.cn/s/blog_4c3b26e10100sd7b.html   贪吃蛇双链表模型


原创文章,欢迎转载,转载请注明:blog.csdn.net/jjzhoujun2010

作者:Dream Fly




总体源代码如下:

snake.c文件

/* Filename: snake.c     version:1.0     date: 2011/08/21

 * Author: Dream Fly     blog: blog.csdn.net/jjzhoujun2010
 * Usage: 'f' means speed up, 's' means speed down, 'q' means quit;
 * Navigation key controls the snake moving.
 * Compile: gcc snake.c -lcurses -o snake
 */

#include<stdio.h>
#include<stdlib.h>
#include<curses.h>
#include<sys/time.h>
#include<signal.h>
#include"snake.h"

struct position food;        /* food position */
Snake_Node *head, *tail;    /* double linked list's head and tail */
int x_dir = 1, y_dir = 0;    /* init dirction of the snake moving */
int ttm = 5, ttg = 5;            /* two timers defined to control speed */

void main(void)
{
    Init_Disp();            /* init and display the interface */
    Food_Disp();            /* display food */
    DLL_Snake_Create();        /* create double linked list and display snake*/
    signal(SIGALRM, Snake_Move);
    set_ticker(DFL_SPEED);
    Key_Ctrl();                /* using keyboard to control snake */
    Wrap_Up();                /* turn off the curses */
}

/* Function: Init_Disp()
 * Usage: init and display the interface
 * Return: none
 */
void Init_Disp()
{
    char wall = ' ';
    int i, j;
    initscr();
    crmode();                /* put termial to CBREAK mode */
    noecho();
    curs_set(0);            /* set cursor invisible */

    /* display some message about title and wall */
    attrset(A_NORMAL);        /* set NORMAL first */
    attron(A_REVERSE);        /* turn on REVERSE to display the wall */
    for(i = 0; i < LINES; i++)
    {
        mvaddch(i, LEFT_EDGE, wall);
        mvaddch(i, RIGHT_EDGE, wall);
    }
    for(j = 0; j < COLS; j++)
    {
        mvaddch(0, j, '=');
        mvaddch(TOP_ROW, j, wall);
        mvaddch(BOT_ROW, j, wall);
    }
    attroff(A_REVERSE);        /* turn off REVERSE */
    mvaddstr(1, 2, "Game: snake    version: 1.0    date: 2011/08/21");
    mvaddstr(2, 2, "Author: Dream Fly    Blog: blog.csdn.net/jjzhoujun2010");
    mvaddstr(3, 2, "Usage: Press 'f' to speed up, 's' to speed down,'q' to quit.");
    mvaddstr(4, 2, "       Nagivation key controls snake moving.");
    refresh();
}

/* Function: Food_Disp()
 * Usage: display food position
 * Return: none
 */
void Food_Disp()
{
    srand(time(0));
    food.x_pos = rand() % (COLS - 2) + 1;
    food.y_pos = rand() % (LINES - TOP_ROW - 2) + TOP_ROW + 1;
    mvaddch(food.y_pos, food.x_pos, FOOD_SYMBOL);/* display the food */
    refresh();
}

/* Function: DLL_Snake_Create()
 * Usage: create double linked list, and display the snake first node
 * Return: none
 */
void DLL_Snake_Create()
{
    Snake_Node *temp = (Snake_Node *)malloc(sizeof(Snake_Node));
    head = (Snake_Node *)malloc(sizeof(Snake_Node));
    tail = (Snake_Node *)malloc(sizeof(Snake_Node));
    if(temp == NULL || head == NULL || tail == NULL)
        perror("malloc");
    temp->x_pos = 5;
    temp->y_pos = 10;
    head->prev =NULL;
    tail->next = NULL;
    head->next = temp;
    temp->next = tail;
    tail->prev = temp;
    temp->prev = head;
    mvaddch(temp->y_pos, temp->x_pos, SNAKE_SYMBOL);
    refresh();
}

/* Function: Snake_Move()
 * Usage: use Navigation key to control snake moving, and judge
 * if the snake touch the food.
 * Return:
 */
void Snake_Move()
{
    static int length = 1;        /* length of snake */
    int Length_Flag = 0;        /* default snake's length no change */
    int moved = 0;
    signal(SIGALRM, SIG_IGN);
    /* judge if the snake crash the wall */
    if((head->next->x_pos == RIGHT_EDGE-1 && x_dir == 1)
        || (head->next->x_pos == LEFT_EDGE+1 && x_dir == -1)
        || (head->next->y_pos == TOP_ROW+1 && y_dir == -1)
        || (head->next->y_pos == BOT_ROW-1 && y_dir == 1))
    {
        gameover(1);
    }
    /* judge if the snake crash itself */
    if(mvinch(head->next->y_pos + y_dir, head->next->x_pos + x_dir) == '@')
        gameover(2);

    if(ttm > 0 && ttg-- == 1)
    {
        /* snake moves */
        DLL_Snake_Insert(head->next->x_pos + x_dir, head->next->y_pos + y_dir);
        ttg = ttm;        /* reset */
        moved = 1;        /* snake can move */
    }
    if(moved)
    {
        /* snake eat the food */
        if(head->next->x_pos == food.x_pos && head->next->y_pos == food.y_pos)
        {
            Length_Flag = 1;
            length++;
            /* Mission Complete */
            if(length >= 20)
                gameover(0);
            /* reset display the food randomly */
            Food_Disp();
        }
        if(Length_Flag == 0)
        {
            /* delete the tail->prev node */
            mvaddch(tail->prev->y_pos, tail->prev->x_pos, ' ');
            DLL_Snake_Delete_Node();
        }
        mvaddch(head->next->y_pos, head->next->x_pos, SNAKE_SYMBOL);
        refresh();
    }
    signal(SIGALRM, Snake_Move);
}

/* Function: set_ticker(number_of_milliseconds)
 * Usage: arrange for interval timer to issue SIGALRM's at regular intervals
 * Return: -1 on error, 0 for ok
 * arg in milliseconds, converted into whole seconds and microseconds
 * note: set_ticker(0) turns off ticker
 */
int set_ticker(int n_msecs)
{
    struct itimerval new_timeset;
    long n_sec, n_usecs;

    n_sec = n_msecs / 1000;                    /* int second part */
    n_usecs = (n_msecs % 1000) * 1000L;        /* microsecond part */

    new_timeset.it_interval.tv_sec = n_sec;    /* set reload */
    new_timeset.it_interval.tv_usec = n_usecs;

    new_timeset.it_value.tv_sec = n_sec;    /* set new ticker value */
    new_timeset.it_value.tv_usec = n_usecs;

    return setitimer(ITIMER_REAL, &new_timeset, NULL);
}

/* Function: Wrap_Up()
 * Usage: turn off the curses
 * Return: none
 */
void Wrap_Up()
{
    set_ticker(0);        /* turn off the timer */
    getchar();
    endwin();
    exit(0);
}

/* Function: Key_Ctrl()
 * Usage: using keyboard to control snake action; 'f' means speed up,
 * 's' means speed down, 'q' means quit, navigation key control direction.
 * Return: none
 */
void Key_Ctrl()
{
    int c;
    keypad(stdscr, true);        /* use little keyboard Navigation Key */
    while(c = getch(), c != 'q')
    {
        if(c == 'f')
        {
            if(ttm == 1)
                continue;
            ttm--;
        }
        else if(c == 's')
        {
            if(ttm == 8)
                continue;
            ttm++;
        }
        if(c == KEY_LEFT)
        {
            if(tail->prev->prev->prev != NULL && x_dir == 1 && y_dir == 0)
                continue; /* it can't turn reverse when snake have length */
            x_dir = -1;
            y_dir = 0;
        }
        else if(c == KEY_RIGHT)
        {
            if(tail->prev->prev->prev != NULL && x_dir == -1 && y_dir == 0)
                continue;
            x_dir = 1;
            y_dir = 0;
        }
        else if(c == KEY_UP)
        {
            if(tail->prev->prev->prev != NULL && x_dir == 0 && y_dir == 1)
                continue;
            x_dir = 0;
            y_dir = -1;
        }
        else if(c == KEY_DOWN)
        {
            if(tail->prev->prev->prev != NULL && x_dir == 0 && y_dir == -1)
                continue;
            x_dir = 0;
            y_dir = 1;
        }
    }
}

/* Function: DLL_Snake_Insert(int x, int y)
 * Usage: Insert node in the snake.
 * Return: none
 */
void DLL_Snake_Insert(int x, int y)
{
    Snake_Node *temp = (Snake_Node *)malloc(sizeof(Snake_Node));
    if(temp == NULL)
        perror("malloc");
    temp->x_pos = x;
    temp->y_pos = y;
    temp->prev = head->next->prev;
    head->next->prev = temp;
    temp->next = head->next;
    head->next = temp;
}

/* Function: gameover(int n)
 * Usage: gameover(0) means Mission Completes; gameover(1) means crashing
 * the wall; gameover(2) means crash itself.
 * Return: none
 */
void gameover(int n)
{
    switch(n)
    {
        case 0:
            mvaddstr(LINES / 2, COLS / 3 - 4, "Mission Completes,press any key to exit.\n");
            break;
        case 1:
            mvaddstr(LINES/2, COLS/3 - 4, "Game Over, crash the wall,press any key to exit.\n");
            break;
        case 2:
            mvaddstr(LINES/2, COLS/3 - 4, "Game Over, crash yourself,press any key to exit.\n");
            break;
        default:
            break;
    }
    refresh();
    /* delete the whole double linked list */
    DLL_Snake_Delete();
    Wrap_Up();
}

/* Function: DLL_Snake_Delete_Node()
 * Usage: delete a tail node, not the whole linked list
 * Return: none
 */
void DLL_Snake_Delete_Node()
{
    Snake_Node *temp;
    temp = tail->prev;
    tail->prev = tail->prev->prev;
    temp->prev->next = tail;
    free(temp);
}

/* Function: DLL_Snake_Delete()
 * Usage: delete the whole double linked list
 * Return: none
 */
void DLL_Snake_Delete()
{
    while(head->next != tail)
        DLL_Snake_Delete_Node();
    head->next = tail->prev = NULL;
    free(head);
    free(tail);

}




snake.h文件

/* Game: snake        version: 1.0    date:2011/08/21    
 * Author: Dream Fly
 * filename: snake.h
 */

#define SNAKE_SYMBOL    '@'        /* snake body and food symbol */
#define FOOD_SYMBOL        '*'
#define DFL_SPEED        50        /* snake default speed */
#define TOP_ROW        5            /* top_row */
#define BOT_ROW        LINES - 1
#define LEFT_EDGE    0
#define RIGHT_EDGE    COLS - 1

typedef struct node            /* Snake_node structure */
{
    int x_pos;
    int y_pos;
    struct node *prev;
    struct node *next;
} Snake_Node;

struct position                /* food position structure */
{
    int x_pos;
    int y_pos;
} ;
void Init_Disp();            /* init and display the interface */
void Food_Disp();            /* display the food position */
void Wrap_Up();                /* turn off the curses */
void Key_Ctrl();            /* using keyboard to control snake */
int set_ticker(int n_msecs);/* ticker */

void DLL_Snake_Create();    /* create double linked list*/
void DLL_Snake_Insert(int x, int y);    /* insert node */
void DLL_Snake_Delete_Node();    /* delete a node */
void DLL_Snake_Delete();        /* delete all the linked list */

void Snake_Move();            /* control the snake move and judge */

void gameover(int n);        /* different n means different state */


编译:

         首先要使用终端图形库curses.h文件,由于不是C标准库,一般电脑不会自带,需要自行下载安装,ubuntu下可以这么下载 

         sudo apt-get install libncurses5-dev

            gcc snake.c -o snake -lcurses