/*双向链表的应用
注重算法,游戏界面我并未多加考虑
希望大家多给建议,注释不多,望大家见凉
未经许可,请毋转载*/
/*UP : 'w' DOWN : 's' LEFT : 'a' RIGHT : 'd' EXIT : 'q'
注重:须是小写*/
#include "stdio.h"
#include "stdlib.h"
#define LEN sizeof(struct node)
#define RIGHT 1
#define LEFT 2
#define UP 3
#define DOWN 4
#define SPEED 4
/*next1表示后趋节点,next2为前趋节点*/
struct node {int status,x,y;struct node *next1,*next2;};
struct node *dz=NULL;
struct node *creat() /*创建一个蛇体长度为4的食豆蛇*/
{struct node *head,*p1,*p2; int i=4;
head=p2=(struct node *)malloc(LEN);
p2->status=RIGHT;
p2->x=i;p2->y=1;
while(i>1)
{p1=(struct node *) malloc(LEN);
p1->status=RIGHT;
p1->x=--i;p1->y=1;
p2->next1=p1;p1->next2=p2;
p2=p1;
}
p2->next1=head;
head->next2=p2;
return head;}
void show(struct node *head)
{struct node *p=head;
do{gotoxy(p->x,p->y);
putchar('*');p=p->next1;
}while(p!=head);
}
void eat(struct node* head) /*吃掉一个豆子*/
{struct node *p2=head->next2;
p2->next1=dz;dz->next2=p2;dz->next1=head;head->next2=dz;
switch(p2->status)
{case RIGHT:dz->x=p2->x-1;dz->y=p2->y;break;
case LEFT:dz->x=p2->x+1;dz->y=p2->y;break;
case UP:dz->x=p2->x;dz->y=p2->y-1;break;
case DOWN:dz->x=p2->x;dz->y=p2->y+1;}
dz=NULL;
}
struct node * update(struct node* head,unsigned char c) /*根据按键更新蛇体*/
{struct node* p2,*p1;p1=head->next2;p2=p1->next2;
do{p1->x=p2->x;p1->y=p2->y;p1->status=p2->status;
p2=p2->next2;p1=p1->next2;
}while(p1!=head);
if(c)
switch(c)
{case 'a':if(head->status!=RIGHT) {(head->x)--;head->status=LEFT;}
else c=0;break;
case 's':if(head->status!=UP) {(head->y)++;head->status=DOWN;}
else c=0;break;
case 'd':if(head->status!=LEFT) {(head->x)++;head->status=RIGHT;}
else c=0;break;
case 'w':if(head->status!=DOWN) {(head->y)--;head->status=UP;}
else c=0;break;
default:c=0;
}
if(!c) /*c=0时表示未按键或按的是无效键*/
switch(head->status)
{case UP:head->y--;break;
case DOWN:head->y++;break;
case RIGHT:head->x++;break;
case LEFT:head->x--;break;
}
if(head->x>80) head->x=1;
else if(head->x<1) head->x=80;
if(head->y>25) head->y=1;
else if(head->y<1) head->y=25;
if(head->x==dz->x&&head->y==dz->y) eat(head);
return head; }
void delay_t(int i) /*蛇的移动速度*/
{int j;
for(j=0;j
void rand_dz() /*随机产生豆子*/
{if(dz==NULL) {dz=(struct node*) malloc(LEN);
dz->x=random(79)+1;dz->y=random(24)+1;}
}
show_dz()
{gotoxy(dz->x,dz->y);putchar('*');}
void exitgame(struct node* head) /*退出游戏,销毁蛇体,释放空间*/
{struct node* p1,*p2;p1=p2=head->next2;
while(p2!=head){p2=p1->next2;free(p1);p1=p2;}
free(head);}
main()
{struct node *head;int key;unsigned char c;
head=creat();rand_dz();
clrscr();
show(head);
show_dz();
delay_t(SPEED);
while(1)
{c=0;
gotoxy(head->next2->x,head->next2->y);putchar(' ');
while(bioskey(1)) c=bioskey(0);
update(head,c);
if(c=='q') break;
if(dz==NULL) {rand_dz();show_dz();} /*豆子被吃,就重新产生豆子*/
show(head);
delay_t(SPEED);}
exitgame(head);
}
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |