C语言实现贪吃蛇游戏
最近整理下电脑,看到了自己在上个学期打的贪吃蛇游戏的c代码,觉得真的是略微有点冗长,但是实现起来应该也算是比较好理解,于是把自己的代码搬上来,网络上写贪吃蛇的c语言的文章很多,我这篇也仅是给大家作为一个参考而已。
我的代码是在Windows下运行的,因为需要用到windows.h这个库。
然后也做了一个简单的ai模式,这在没有障碍物的情况下前期还是蛮不错的,但是到了后期蛇变长了之后就会有bug了。
好了,直接上代码吧:
1)头文件和宏定义
#include#include #include #include #include #defineSNAKE_MAX_LENGTH20 #defineSNAKE_HEAD'H' #defineSNAKE_BODY'X' #defineBLANK_CELL'' #defineSNAKE_FOOD'$' #defineWALL_CELL'*'
2)各种实现函数的声明
/*snakestepping:dy=-1(up)1(dowm)0(nomove);dx=-1(left),1(right),0(nomove)*/ voidsnakemove(int,int); //towritedowmthecurrentlocationofthesnake voidput_money(void); voidoutput(void); //toputthecurrentmaponthescreen voidinitial_the_game(void); voidput_accelerate(void); //@isaspecialfoodwhichcanspeedupyoursnake. intjudge(int,int); /*whenitcomestoai,itisusedtojudgewhetherthenextstepismovable.*/ intdis(int,int); //whenitcoomestoai,itisusedtocalculatethecurrentdistence//betweenthesnakeheadandthefood. voidwelcome(void);//thegameintroduction. voidgameover(void); voidedition_handed(void); //theeditioninwhichyoucanplaybyyourself. voidedition_presentation(void); //theeditioninwhichthesnakecangoautomatically.
3)各种全局变量
//definevarsforsnake,noticenameofvarsinc
intsnakeX[SNAKE_MAX_LENGTH]={1,2,3,4,5};
intsnakeY[SNAKE_MAX_LENGTH]={1,1,1,1,1};
intsnakeLength=5;
intgamestate=1;
intcurrent_speed=600;
intscore=0;
charedition_choose;//forplayertochoosetheedition.
intcon=1;//tojudgetheinitialstateofthegame;
intenergy=0;//writedowntheconditiontoacceleratebyeating$.
//thefollowingpartistorealizethesimpleai.
constcharmovable[4]={'a','d','s','w'};
intdistance[4]={9999,9999,9999,9999};
intfx=6,fy=6;//thecoordinateofthefood$
4)地图
charmap[12][12]=
{"************",
"*XXXXH*",
"**",
"**",
"**",
"**",
"*$*",
"**",
"*@*",
"**",
"**",
"************"};
5)主函数(可选模式)
intmain(){
while(con){
welcome();
intflag=1;
while(flag){
edition_choose=getch();//choosetheedition
if(edition_choose=='h'){
edition_handed();
flag=0;
}
elseif(edition_choose=='p'){
edition_presentation();
flag=0;
}
else{
printf("Pleasepressthecorrectbottom-,-...\n");
}
}
gameover();
}
return0;
}
6)手动模式实现
voidedition_handed(void){
system("cls");
output();
charch='d';
while(gamestate){
switch(ch){
case'a'://goleft
while(1){
snakemove(-1,0);
Sleep(current_speed);
if(gamestate==0)//tobreaktheloopifthesnakehitthewalloritself.
break;
if(kbhit()!=0){//tochangethedirection
ch=getch();
if(ch=='s'||ch=='w')
break;
else
ch='a';
}
}
break;
case'd'://goright
while(1){
snakemove(1,0);
Sleep(current_speed);
if(gamestate==0)
break;
if(kbhit()!=0)
ch=getch();
if(ch=='s'||ch=='w')
break;
else
ch='d';
}
break;
case's'://godown
while(1){
snakemove(0,1);
Sleep(current_speed);
if(gamestate==0)
break;
if(kbhit()!=0)
ch=getch();
if(ch=='a'||ch=='d')
break;
else
ch='s';
}
break;
case'w'://goup
while(1){
snakemove(0,-1);
Sleep(current_speed);
if(gamestate==0)
break;
if(kbhit()!=0)
ch=getch();
if(ch=='a'||ch=='d')
break;
else
ch='w';
}
break;
}
if(gamestate==0)
break;
}
return;
}
7)自动模式实现
voidedition_presentation(void){//forai
system("cls");
inti,min=10000;
output();
charch;
charquit='o';
intk;
while(gamestate){//findtheshortestway;
min=10000;
if(judge(-1,0))distance[0]=dis(-1,0);
if(judge(1,0))distance[1]=dis(1,0);
if(judge(0,1))distance[2]=dis(0,1);
if(judge(0,-1))distance[3]=dis(0,-1);
for(i=0;i<4;i++){
if(min>=distance[i]){
min=distance[i];
k=i;
}
}
Sleep(current_speed);
switch(movable[k]){
case'a'://goleft
snakemove(-1,0);
break;
case'd'://goright
snakemove(1,0);
break;
case's'://godown
snakemove(0,1);
break;
case'w'://goup
snakemove(0,-1);
break;
}
if(gamestate==0)
break;
system("cls");
output();
}
return;
}
8)其他辅助函数
欢迎界面
voidwelcome(void){//justforsomeintroduction
printf("WELCOMETOTHESNAKE'SWORLD!!!!\n");
printf("\n");
printf("\n");
printf("Pleasechoosetheeditionyouwant.\n");
printf("\n");
printf("\n");
printf("The'h'isforthehand-operatedandthe'p'isforthesimplepresentation\n");
printf("\n");
printf("\n");
printf("Attention:thepresentationstillhasaliitlebug,whileitcanbemovingrightforaperiodoftime...\n");
return;
}
游戏结束界面
voidgameover(void){//giveyousomeintroductionwhenyoulosethegame.
system("cls");
printf("Gameover!!!\n");
printf("Doyouwanttocontinue?yorn\n");
charstart;//inordertojudgewhetheryoustillwanttoplaythegame.
while(1){
start=getch();
if(start=='y'){
system("cls");
initial_the_game();
break;
}elseif(start=='n'){
system("cls");
con=0;//inordertoletthegameend.
printf("Seeyounexttime!^-^\n");
break;
}else{
printf("Pleasepressthecorrectbuttom.\n");
}
}
}
图像实现方式
voidoutput(void){//putthecuttentgamemap.
printf("THEINTERESTINGSNAKEGAMECREATEDBYLONGJ=,=\n");
printf("usew~s~a~dtocontrolthesnake'smovement\n");
printf("ATTENTION:the@canspeedupyourlovelysnake~~\n");
inti,j;
for(i=0;i<12;i++){
for(j=0;j<12;j++){
printf("%c",map[i][j]);
if(j==11)
printf("\n");
}
}
printf("Yourcurrent_speedis%d\n",current_speed);
printf("Thenumberofyourfoodundigestedis%d(whenitcomesto5,yourspeedwillbeaccelerated!)\n",energy);
printf("SCORE=%d\n",score);
return;
}
蛇的行走实现
voidsnakemove(intdx,intdy){//alltheconditionsarecomparingtheheadandthenextposition.
inti;
if(snakeY[snakeLength-1]+dy==snakeY[snakeLength-2]&&snakeX[snakeLength-1]+dx==snakeX[snakeLength-2])
return;//topreventitgotoitslef.
if(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='X'){
gamestate=0;
return;
}
if(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='*'){
gamestate=0;
return;
}
if(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]==''
||map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='@'){
map[snakeY[0]][snakeX[0]]='';//cleartheformer_tail
if(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='@'
&¤t_speed>100){//whatwillhappenwhenyoursnakeeatsthe@
current_speed-=100;
put_accelerate();
}
for(i=0;i50){
current_speed-=50;
energy=0;
}
put_money();
}
system("cls");
output();
return;
}
食物放置的实现
voidput_money(void){///aiwillchangethecode
intflag=1;
while(flag){
srand(time(NULL));
fx=rand()%12;
fy=rand()%12;
if(map[fy][fx]==''){
map[fy][fx]='$';
flag=0;
}
if(edition_choose=='p'){
inti;
for(i=0;i<4;i++)
distance[i]=9999;
}
}
return;
}
voidput_accelerate(void){
intx,y,flag=1;
while(flag){
srand(time(NULL));
x=rand()%12;
y=rand()%12;
if(map[x][y]==''){
map[x][y]='@';
flag=0;
}
}
return;
}
ai辅助函数
intdis(intdx,intdy){
returnabs(fx-snakeX[snakeLength-1]-dx)+abs(fy-snakeY[snakeLength-1]-dy);
}
intjudge(intdx,intdy){
if(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='')
return1;
elseif(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='$')
return1;
elseif(map[snakeY[snakeLength-1]+dy][snakeX[snakeLength-1]+dx]=='@')
return1;
else
return0;
}
游戏over后的初始化函数:
voidinitial_the_game(void){
inti,j,count=1;
snakeLength=5;
gamestate=1;
fx=fy=6;
current_speed=600;
for(i=0;i<5;i++)
snakeY[i]=1;
for(i=0;i<5;i++){
snakeX[i]=count++;
}
for(j=0;j<12;j++){
map[0][j]='*';
map[11][j]='*';
}
for(i=1;i<11;i++){
map[i][0]=map[i][11]='*';
for(j=1;j<11;j++)
map[i][j]='';
}
map[fy][fx]='$';
map[8][4]='@';
for(i=0;i<4;i++){
distance[i]=9999;
}
for(i=0;i<4;i++)
map[snakeY[i]][snakeX[i]]='X';
map[snakeY[4]][snakeX[4]]='H';
return;
}
小结:
不难看出,c语言代码比较冗长,而且初始化的函数实现起来十分麻烦,稍有不慎就会全部出错,导致游戏无法持续玩下去,博主当初写的时候就是被坑了很久=_=
因而现在在学c++,希望以后把类的概念之类的东西都弄得更加熟练之后,可以去把这个冗长的c代码改成更加简洁,阅读性更强的c++代码。
(好的,已经更新了,写出了一个比较简单的C++贪吃蛇,的确是思路清晰很多,代码的可读性更高。)
这篇博客给那些想要用c来写贪吃蛇的同学一些参考,运行起来是没有问题的,可以选择性看:)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。