诶,花了两天的时间终于把这个游戏给写出来了,虽然是看着视频敲着别人的代码,但在Linux环境下也是真不容易。先就这样吧,把原码放这儿,然后我会再写一篇文章对这个原码进行解释!
#include<curses.h>
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#define UP 1
#define DOWN -1
#define LEFT 3
#define RIGHT -3
void initNcurse()
{
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;
struct snake food;
void initfood()
{
int x=rand()%20;
int y=rand()%20;
food.hang=x;
food.lie=y;
}
int hasNode(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;
}
int hasfood(int i,int j)
{
if(food.hang==i && food.lie==j)
{
return 1;
}
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(hasNode(hang,lie)==1)
{
printw("[]");
}
else if(hasfood(hang ,lie)==1)
{
printw("##");
}
else
{
printw(" ");
}
}
printw("\n");
}
if(hang==19)
{
for(lie=0;lie<20;lie++)
{
printw("--");
}
printw("\n");
printw("food.hang=%d,food.lie=%d\n",food.hang,food.lie);
printw("Designed by QYY KEY=%d\n",key);
}
}
}
void addn()
{
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 initsnake()
{
struct snake *p=NULL;
dir =RIGHT;
while(head!=NULL)
{
p=head;
head=head->next;
free(p);
}
initfood();
head=(struct snake*)malloc(sizeof(struct snake));
head->hang=2;
head->lie=1;
head->next=NULL;
tail=head;
addn();
addn();
addn();
}
void deletenode()
{
struct snake* p;
p=head;
head=head->next;
free(p);
}
int ifsnakedie()
{
struct snake *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 movsnake()
{
addn();
if(hasfood(tail->hang,tail->lie))
{
initfood();
}
else
{
deletenode();
}
if(ifsnakedie())
{
initsnake();
}
}
void* refreshJieMian()
{
while(1)
{
movsnake();
gamePic();
refresh();
usleep(100000);
}
}
void turn(int direction)
{
if(abs(dir)!=abs(direction))
{
dir=direction;
}
}
void* changeDir()
{
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,changeDir,NULL);
while(1);
getch();
endwin();
return 0;
}
bandicam 2021-03-18 20-05-49-443