济南市城乡建设部网站首页,江山市城乡建设局网站,it外包wordpress模板,中文网址上节我们实现了蛇身向右移动的功能#xff0c;原理就是增加一个节点#xff0c;删除一个节点。 本节我们处理蛇撞墙重置的功能
实现原理
在移动函数中检查蛇头#xff08;链表尾节点#xff09;是否达到墙边的坐标#xff0c;这里有四种撞墙的情况#xff1a;
上墙原理就是增加一个节点删除一个节点。 本节我们处理蛇撞墙重置的功能
实现原理
在移动函数中检查蛇头链表尾节点是否达到墙边的坐标这里有四种撞墙的情况
上墙当行为0的时候下墙当行为20的时候左墙当列为0的时候右墙当列为20的时候。注意我设置的是19根据实际修改
#includecurses.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;
}
学习打卡