簡易多執行緒實現貪吃蛇C語言
阿新 • • 發佈:2021-02-02
技術標籤:筆記
20210201
#include <stdlib.h>
#include <curses.h>
struct snake
{
int hang;
int lie;
struct snake *next;
};
struct snake food;
#define UP 1
#define DOWN -1
#define LEFT 2
#define RIGHT -2
struct snake *head=NULL;
struct snake *tail=NULL;
int key;
int fangxiang;
int makesnake(int j,int k)
{
struct snake *p;
p = head;
while(p != NULL)
{
if(p->hang == j && p->lie == k)
{
return 1;
}
p = p->next;
}
return 0;
}
int die()
{
struct snake *p;
p = head;
if(tail->hang<0 || tail->lie==0 || tail->hang==30 || tail->lie==30)
{return 1;}
while(p->next!=NULL)
{
if(p->hang == tail->hang && p->lie == tail->lie)
{
return 1;
}
p = p->next;
}
return 0;
}
int makefood(int j,int k)
{
if(food.hang == j && food.lie == k)
{return 1;}
return 0;
}
void initsnake( )
{
struct snake *p;
fangxiang = RIGHT;
while(head!=NULL)
{
p = head;
head = head->next;
free(p);
}
createfood();
head = (struct snake *)malloc(sizeof(struct snake));
head->hang = 1;
head->lie = 1;
head->next = NULL;
tail = head;
addnode();
}
void addnode()
{
struct snake *new = (struct snake *)malloc(sizeof(struct snake));
//new->hang = tail->hang;
//new->lie = tail->lie+1;
new->next = NULL;
switch(fangxiang)
{
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 delnode()
{
struct snake *p;
p = head;
head = head->next;
free(p);
}
void createfood()
{
int x = rand()%30;
int y = rand()%30;
food.hang = x;
food.lie = y;
}
void movesnake()
{
addnode();
if(makefood(tail->hang,tail->lie))
{
createfood();
}
else{
delnode();}
if(die())
{
initsnake();
}
}
void initNcurse()
{
initscr();
keypad(stdscr,1);
noecho();
}
void judge(int a)
{
if(abs(fangxiang) != abs(a))//JUEDUIZHI
{
fangxiang = a;
}
}
void gamemap()
{
int hang;
int lie;
move(0,0);// chongzai
for(hang=0;hang<30;hang++)
{
if(hang==0){
for(lie=0;lie<30;lie++)
{
printw("--");
}
printw("\n");
}
if(hang>=0 && hang<=29)
{
for(lie=0;lie<=30;lie++)
{
if(lie==0||lie==30)
{printw("|");}
else if(makesnake(hang,lie))
{
printw("[]");
}
else if(makefood(hang,lie))
{
printw("##");
}
else{
printw(" ");}
}
printw("\n");
}
if(hang==29)
{
for(lie=0;lie<30;lie++)
{
printw("--");
}
printw("\n");
printw("liZHE %d\n",key);
printw("food is in %d,%d\n",food.hang,food.lie);
}
}
}
void refreshmap()
{
while(1)
{
movesnake();
gamemap();
refresh();
usleep(100000);
}
}
void FX()
{
while(1)
{
key = getch();
switch(key)
{
case KEY_DOWN:
judge(DOWN);
break;
case KEY_UP:
judge(UP);
break;
case KEY_LEFT:
judge(LEFT);
break;
case KEY_RIGHT:
judge(RIGHT);
break;
}
}
}
int main()
{
pthread_t t1;
pthread_t t2;//xiancheng
initNcurse();
initsnake();
gamemap();
pthread_create(&t1,NULL,refreshmap,NULL);
pthread_create(&t2,NULL,FX,NULL);
while(1);
getch();
endwin();
return 0;
}