贪吃蛇代码:
#include<curses.h>
#include<stdlib.h>
#include<pthread.h>
#define up 1
#define down -1
#define right 2
#define left -2
typedef struct temp
{
int hang;
int lie;
struct temp *next;
}STU,*STCU;
STCU head=NULL;
STCU tail=NULL;
int dir;
STU food;
STU initFood()
{
food.hang=rand()%40+1;
food.lie=rand()%40+1;
food.next=NULL;
}
void initSnake()
{
initscr();
keypad(stdscr,1);
noecho();
}
void addBody();
void initSnakebody()
{
while(head!=NULL)
{
STCU p=head;
head=head->next;
free(p);
}
dir=right;
initFood();
head=(STCU)malloc(sizeof(STU));
tail=(STCU)malloc(sizeof(STU));
head->hang=2;
head->lie=2;
head->next=NULL;
tail=head;
addBody();
addBody();
addBody();
addBody();
}
void addBody()
{
STCU new=(STCU)malloc(sizeof(STU));
new->next=NULL;
switch(dir)
{
case right:
new->hang=tail->hang;
new->lie=tail->lie+1;
break;
case left:
new->hang=tail->hang;
new->lie=tail->lie-1;
break;
case up:
new->hang=tail->hang-1;
new->lie=tail->lie;
break;
case down:
new->hang=tail->hang+1;
new->lie=tail->lie;
break;
}
tail->next=new;
tail=new;
}
int bodyShow(int hang,int lie)
{
STCU p=head;
while(p!=NULL)
{
if(p->hang==hang&&p->lie==lie)
{
return 1;
}
p=p->next;
}
return 0;
}
int foodShow(int hang,int lie)
{
if(food.hang==hang&&food.lie==lie)
{
return 1;
}
else
{
return 0;
}
}
void gamePacture()
{
int hang,lie;
move(0,0);
for(hang=0;hang<=42;hang++)
{
if(hang==0||hang==41)
{
for(lie=0;lie<82;lie++)
{
printw("-");
}
}
else
{
if(hang==42)
{
printw("Made By Liu Xu");
}
else
{
for(lie=0;lie<=41;lie++)
{
if(lie==0||lie==41)
{
printw("|");
}
else if(bodyShow(hang,lie))
{
printw("[]");
}
else if(foodShow(hang,lie))
{
printw("##");
}
else
{
printw(" ");
}
}
}
}
printw("\n");
}
}
void deleteHead()
{
STCU p=head;
head=head->next;
free(p);
}
int ifSnakeDie()
{
STCU p=head;
if(tail->hang==0||tail->hang==41||tail->lie==0||tail->lie==41)
{
return 1;
}
while(p->next!=NULL)
{
if(p->hang==tail->hang&&p->lie==tail->lie)
{
return 1;
}
p=p->next;
}
return 0;
}
void snakeTurn(int dir1)
{
if(abs(dir)!=abs(dir1))
{
dir=dir1;
}
}
void gameMove()
{
if(tail->hang==food.hang&&tail->lie==food.lie)
{
addBody();
initFood();
}
if(ifSnakeDie())
{
initSnakebody();
}
else
{
addBody();
deleteHead();
}
}
void* jianCeShuRu()
{
int key;
while(1)
{
key=getch();
switch(key)
{
case 0402:snakeTurn(down);break;
case 0403:snakeTurn(up);break;
case 0404:snakeTurn(left);break;
case 0405:snakeTurn(right);break;
}
}
}
void* shuaXinPacture()
{
while(1)
{
gameMove();
gamePacture();
refresh();
usleep(100000);
}
}
int main()
{
pthread_t t1;
pthread_t t2;
initSnake();
initSnakebody();
gamePacture();
pthread_create(&t1,NULL,jianCeShuRu,NULL);
pthread_create(&t2,NULL,shuaXinPacture,NULL);
while(1);
getch();
endwin();
return 0;
}