A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

编《贪吃蛇》的最简算法我想就是用链表了
用链表的节点表示蛇
增加的减少都有很方便
移动的时候只须增加一个头节点并去掉尾节点就行了
吃食物是只须增加一个头节点
链表和蛇本来就很相似
用链表编《贪吃蛇》最合适不过了
源程序大家自己看吧!
#include<graphics.h>
#include<stdio.h>
#include<stdlib.h>
#include<dos.h>
#include<bios.h>
#define ESC 0x011b
#define UP 0x4800
#define DOWN 0x5000
#define LEFT 0x4b00
#define RIGHT 0x4d00

struct rode
{int x;
int y;
struct rode *next;
};
struct rode *head,food;


void initgra()
{int dr=DETECT,mode=0;
registerbgidriver(EGAVGA_driver);
initgraph(&dr,&mode,"");

}

int message(char *s)
{ char c;
setfillstyle(1,4);
setcolor(1);
settextstyle(0,0,3);
bar(640/2-200,480/2-50,640/2+250,480/2+50);
outtextxy(640/2-200,480/2-20,s);
c=getch();
sleep(2);
if(c=='n'|| c=='N')return(0);else return(1);

}

initgame()
{

int i;
randomize();
cleardevice();
clear();

setbkcolor(15);
setcolor(4);
for(i=0;i<=640;i+=20) line(i,0,i,479);
for(i=0;i<=480;i+=20) line(0,i,639,i);

add(5,5);
add(5,6);
add(5,7);
rndfood();

getch();

}

add(int x,int y)
{
struct rode *newrode;

newrode=(struct rode*)malloc(sizeof(struct rode));
newrode->x=x;
newrode->y=y;

newrode->next=head;
head=newrode;

draw(x,y);
}

delete()
{struct rode *p1,*p2;

p1=p2=head;

while (p1->next !=NULL) {

p2=p1;
p1=p1->next;

}
redraw(p1->x,p1->y);
free(p1);
p2->next=NULL;
}
long getkey(long oldkey)
{long k;
if(bioskey(1)==0) return 0;
k=bioskey(0);
if(oldkey==UP && k==DOWN) return 0;
if(oldkey==DOWN &&k==UP) return 0;
if(oldkey==RIGHT&&k==LEFT) return 0;
if(oldkey==LEFT&&k==RIGHT) return 0;
return k;
}
clear()
{struct rode *p1,*p2;

p1=p2=head;
while(p1){
p2=p1->next;
free(p1);
p1=p2;
}
head=NULL;
}


draw(int x,int y)
{setcolor(1);
setfillstyle(1,1);
bar((x-1)*20+1,(y-1)*20+1,x*20-1,y*20-1);
}
redraw(int x,int y)
{int c;
c=getbkcolor();
setcolor©;
setfillstyle(1,c);
bar((x-1)*20+1,(y-1)*20+1,x*20-1,y*20-1);
}

rndfood()
{
food.x=random(31)+1;
food.y=random(23)+1;
draw(food.x,food.y);
}


gameover()
{clear();
closegraph();
exit(1);
}

main()
{struct time t;
int oldtime;
long key,oldkey;
int nx,ny,x,y;
long getkey(long oldtime);
initgra();
again:
initgame();
x=0;
y=1;
oldkey=DOWN;
key=DOWN;
gettime(&t);
oldtime=t.ti_hund;

while(key!=ESC)
{gettime(&t);
if((t.ti_hund+100-oldtime)%100<40)
{
if((key=getkey(oldkey))!=0)
{
switch(key)
{case UP:x=0;y=-1;break;
case DOWN:x=0;y=1;break;
case LEFT:x=-1;y=0;break;
case RIGHT:x=1;y=0;break;
default:continue;
}
oldkey=key;
}
}
else{
oldtime=t.ti_hund;
nx=head->x+x;
ny=head->y+y;

if(nx==food.x && ny==food.y)
{
add(food.x,food.y);
rndfood();
continue;
}

if(nx>32||nx <1 ||ny >24 ||ny<1)
if (message("Do you want play again?[Y/N]") ) goto again;
else
gameover();


delete();
add(nx,ny);

}

}
gameover();
}32

2 个回复

倒序浏览
顶一个!
回复 使用道具 举报
太长没看...
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马