1.在main函数中分别引入线程t1 和线程 t2
一个线程用来刷新界面,一个线程用来改变方向
2.刷新界面函数,无限次刷新
3. 也是无限循环while(1) 定义key 从键盘获取输入方向,赋值给dir;
4.在初始化函数中确定蛇向有行走为方向
5.从改变方向的函数changeDir()函数中获取dir的方向,在增加节点函数addNode()中,用switch函数实现蛇方向的改变
代码演示:
#include <curses.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
void initNcurses()
{
initscr();
keypad(stdscr,1);
noecho();
}
struct Snake
{
int hang;
int lie;
struct Snake *next;
};
struct Snake *head = NULL;
struct Snake *tail = NULL;
int key;
int dir;
int hasSnakeNode(int i,int j){ // da yin she shen ti
struct Snake *p;
p = head; //ding tou
while(p != NULL){
if(p -> hang == i && p ->lie == j){
return 1;
}
p = p ->next;
}
return 0;
}
void gamePic()
{
int hang;
int lie;
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 <=18)
{
for(lie = 0;lie<=20;lie++){
if(lie == 0 || lie == 20){
printw("|");
}else if(hasSnakeNode(hang,lie))
{
printw("[]");
}else
{
printw(" ");
}
}
printw("\n");
}
if(hang == 19)
{
for(lie=0;lie<20;lie++){
printw("--");
}
printw("\n");
printw("by caoshupei,key= %d\n",key);
}
}
}
void addNode()
{
struct Snake *new = (struct Snake *)malloc(sizeof(struct Snake));
new -> next =NULL;
switch(dir){
case UP:
new -> hang = tail -> hang-1;
new -> lie = tail -> lie;
break;
case DOWN:
new -> hang = tail -> hang+1;
new -> lie = tail ->lie;
break;
case LEFT:
new -> hang = tail -> hang;
new ->lie = tail -> lie-1;
break;
case RIGHT:
new -> hang = tail -> hang;
new -> lie = tail -> lie+1;
break;
}
tail -> next = new;
tail = new;
}
void deleteNode()
{
struct Snake *p;
p = head;
head = head ->next;
free(p); // fang zhi zao cheng hen duo kong yu de jie dian
}
void initSnakebody()
{
struct Snake *p;
dir = RIGHT;
//di yi ci yun xing shi bu hui zou
while(head != NULL) //yi kai shi deng yu kong
{ //zhuang qiao la jiu shi bu wei kong
p = head;
head = head -> next;
free(p); //shi fang nei cun
}
head = (struct Snake*)malloc(sizeof(struct Snake));
head -> hang = 1; // gu ding chu shi weizhi
head -> lie = 1;
head -> next = NULL; // tou de xie yi ge wei kong
tail = head; // wei ba bian cheng tou
addNode(); // zeng jia jie dian
addNode();
addNode();
}
void moveSnake()
{
struct Snake *p;
struct Snake *new;
addNode();
deleteNode();
if(tail -> hang == 0|| tail ->lie == 0|| tail->hang == 20 ||
tail->lie ==20)
{
initSnakebody();
}
}
void *refreshjiemian()
{
while(1){
moveSnake();
gamePic();
refresh();
usleep(100000);
}
}
void *changeDir()
{
while(1){
key = getch();
switch(key){
case KEY_DOWN:
dir = DOWN;
break;
case KEY_UP:
dir = UP;
break;
case KEY_LEFT:
dir = LEFT;
break;
case KEY_RIGHT:
dir = RIGHT;
break;
}
}
}
int main()
{
pthread_t t1;
pthread_t t2;
initNcurses();
initSnakebody();
gamePic();
pthread_create(&t1,NULL,refreshjiemian,NULL);
sleep(1);
pthread_create(&t2,NULL,changeDir,NULL);
while(1);
getch();
endwin();
return 0;
}