linux 下貪喫蛇

大一學習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庫和tty
endwin() 關閉curses並重置tty
refresh() 刷新屏幕顯示
mvaddch(y,x,c) 在座標(y,x)處顯示字符c
mvaddstr(y,x,str) 在座標(y,x)處顯示字符串str
cbreak() 開啓輸入立即響應
noecho() 輸入不回顯到屏幕
curs_set(0) 使光標不可見
attrset() 開啓圖形顯示模式
keypad(stdscr, true) 開啓小鍵盤方向鍵輸入捕捉支持

更詳細的可以  man ncurses   或者參見http://bbs.chinaunix.net/viewthread.php?tid=909369

  2.介紹完ncurses圖形庫,接下來進行屏幕繪圖,我初始化屏幕效果圖見下圖所示:先是外圍邊框,然後是蛇“@”和食物“*”。

廢話不多說,上代碼吧。


首先是頭文件 snake.h的代碼:由於在純文本模式下編程以及本人英語水平有限,可能有的註釋比較彆扭。

[cpp] view plain copy
  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>  
接下來是初始化界面圖形的子函數:
[cpp] view plain copy
  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 越大,減速越明顯,反之則相反效果。  具體的間隔計數器的函數設計見下:(參考了以上所提書本上的函數)

[cpp] view plain copy
  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. }  

  蛇的移動的函數代碼如下:

[cpp] view plain copy
  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

[cpp] view plain copy
  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 */  

[cpp] view plain copy
  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章