#include <curses.h>
#include <stdlib.h>
#include <pthread.h>
#define UP -1
#define DOWN 1
#define LEFT 2
#define RIGHT -2
typedef struct snake
{
int hang;
int lie;
struct snake *next;
}Snake,*pSnake;
Snake food;
void initFood()
{
int x=rand()%20;
int y=rand()%20;
food.hang=x;
food.lie=y;
}
int hasFood(int i,int j)
{
if(food.hang==i && food.lie==j)
{
return 1;
}
return 0;
}
pSnake head=NULL;
pSnake tail=NULL;
int key;
int dir;
void initNcurse()
{
initscr();
keypad(stdscr,1);
noecho();
}
int hassnakenode(int i,int j)
{
struct snake *p;
p=head;
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<=19)
{
for(lie=0;lie<=20;lie++)
{
if(lie==0||lie==20)
{
printw("|");
}
else if(hassnakenode(hang,lie))
{
printw("[]");
}else if(hasFood(hang,lie)){
printw("##");
}
else
{
printw(" ");
}
}
printw("\n");
}
if(hang==19)
{
for(lie=0;lie<20;lie++)
{
printw("--");
}
printw("\n");
printw("by 110 key=%d\n",key);
}
}
}
void addNode()
{
pSnake new=(pSnake)malloc(sizeof(Snake));
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;
}
new->next=NULL;
tail->next=new;
tail=new;
}
void initsnake()
{
pSnake p;
dir=RIGHT;
while(head!=NULL)
{
p=head;
head=head->next;
free(p);
}
initFood();
head=(pSnake )malloc(sizeof(Snake));
head->hang=2;
head->lie=2;
head->next=NULL;
tail=head;
addNode();
addNode();
addNode();
addNode();
}
void deleteNode()
{
pSnake p;
p=head;
head=head->next;
free(p);
}
int ifFoodDir()
{
pSnake p;
p=head;
if(tail->hang<0 || tail->lie==0 || tail->hang==20 || tail->lie==20){
return 1;
}
while(p->next!=NULL){
if(p->hang==tail->hang&&p->lie==tail->lie){
return 1;
}
p=p->next;
}
return 0;
}
void movesnake()
{
addNode();
if(hasFood(tail->hang,tail->lie)){
initFood();
}else{
deleteNode();
}
if(ifFoodDir()){
initsnake();
}
}
void *RefreshJiemian()
{
while(1)
{
movesnake();
refresh();
gamePic();
usleep(150000);
// sleep(1);
}
}
void turn (int dires)
{
if(abs(dir)!=abs(dires)){
dir=dires;
}
}
void *ChangeDire()
{
while(1){
key=getch();
switch(key){
case KEY_DOWN:
turn(DOWN);
break;
case KEY_UP:
turn(UP);
break;
case KEY_LEFT:
turn(LEFT);
break;
case KEY_RIGHT:
turn(RIGHT);
break;
}
}
}
int main()
{
pthread_t t1;
pthread_t t2;
initNcurse();
initsnake();
gamePic();
pthread_create(&t1, NULL, RefreshJiemian, NULL);
pthread_create(&t2, NULL, ChangeDire, NULL);
while(1);
getch();
endwin();
return 0;
}
贪吃蛇小项目
最新推荐文章于 2024-05-11 11:17:28 发布