#include <curses.h>
#include <stdlib.h>
struct snake
{
int hang;
int lie;
struct snake *next;
};
struct snake *head=NULL;
struct snake *tail=NULL;
void initNcurse()
{
initscr();
keypad(stdscr,1);
}
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
{
printw(" ");
}
}
printw("\n");
}
if(hang==19)
{
for(lie=0;lie<20;lie++)
{
printw("--");
}
printw("\n");
printw("by shuai ge");
}
}
}
void addNode()
{
struct snake *new=(struct snake *)malloc(sizeof(struct snake));
new->hang=tail->hang;
new->lie=tail->lie+1;
new->next=NULL;
tail->next=new;
tail=new;
}
void initsnake()
{
struct snake *p;
while(head!=NULL)
{
p=head;
head=head->next;
free(p);
}
head=(struct snake *)malloc(sizeof(struct snake));
head->hang=2;
head->lie=2;
head->next=NULL;
tail=head;
addNode();
addNode();
addNode();
addNode();
}
void deleteNode()
{
struct snake *p;
p=head;
head=head->next;
free(p);
}
void movesnake()
{
addNode();
deleteNode();
if(tail->hang==0 || tail->lie==0 || tail->hang==20 || tail->lie==20)
{
initsnake();
}
}
int main()
{
int con;
initNcurse();
initsnake();
gamePic();
while(1)
{
con=getch();
if(con==KEY_RIGHT)
{
movesnake();
gamePic();
}
}
getch();
endwin();
return 0;
}
运行效果
蛇身撞墙时就重新回到起点
蛇身撞墙
回到起点
——@上官可编程