上节我们实现了蛇身向右移动的功能,原理就是增加一个节点,删除一个节点。
本节我们处理蛇撞墙重置的功能
实现原理
在移动函数中检查蛇头(链表尾节点)是否达到墙边的坐标,这里有四种撞墙的情况:
- 上墙(当行为0的时候)
- 下墙(当行为20的时候)
- 左墙(当列为0的时候)
- 右墙(当列为20的时候。注意我设置的是19,根据实际修改)
#include"curses.h"
#include "stdlib.h"
struct SnakeNode
{int row;int col;struct SnakeNode* next;
};struct SnakeNode* head = NULL;
struct SnakeNode* tail = NULL;void addNode();
void mapinit();
void snakeinit()
{// free struct SnakeNode* p;while(head != NULL){p = head;head = head->next;free(p);}head = (struct SnakeNode*)malloc(sizeof(struct SnakeNode));head->row = 2;head->col = 2;head->next = NULL;tail = head;addNode();addNode();
}void addNode()
{ struct SnakeNode* node = (struct SnakeNode*)malloc(sizeof(struct SnakeNode));node->row = tail->row;node->col = tail->col + 1;node->next = NULL;tail->next = node;tail = node;
}void deleteNode()
{struct SnakeNode* p;p = head;head = head->next;free(p);
}void moveSnake()
{addNode();deleteNode();// if snake is over.if(tail->row == 0 || tail->col == 0 || tail->row >= 20 || tail->col >= 19){snakeinit();}
}void cursesinit()
{initscr();keypad(stdscr,1);
}int hasSnake(int row,int col)
{struct SnakeNode* p = head;while(p!=NULL){if(row == p->row && col == p->col)return 1;p = p->next;}return 0;
}void mapinit()
{int row;int col;move(0,0);for(row = 0;row < 20;row++){// oneif(row == 0 || row == 19){for(col = 0;col < 19;col++)printw("--");}// twoelse{for(col = 0;col < 20;col++){if(col == 0 || col == 19 ) printw("|");else if(hasSnake(row,col)){printw("[]");}else{printw(" "); }}}printw("\n");}// game startprintw("By hongzhe\n");
}int main()
{int key;cursesinit();snakeinit();mapinit();while(1){key = getch();if(key == KEY_RIGHT){moveSnake();mapinit(); // fresh map }}getch(); endwin();return 0;
}