自己写的贪食蛇游戏,问题有很多
由于反复刷屏和打印,导致硬盘读写严重(硬盘灯闪个不停)和屏幕闪烁,而且速度不好.各位有什么好点的方法吗?
学得不好,献丑了
#include <windows.h>#include <stdlib.h> #include <stdio.h> #include <time.h> int end=1; //全局变量main(){ for(;;) { int x=1,y=1,ditu[21][21]={0},shch=2,c; int *xz=&x,*yz=&y,*chang=&shch; //定义并初始化指针c=caidan('w',1);if(c==0) return 0;if(c==2) sett(chang);srand((unsigned)time(NULL)); //给随机函数种子kudamono(ditu); //初始化食物坐标start('d',ditu,xz,yz,chang); //开始游戏printf("\n\n\n\n\n Game Over");Sleep(3000);getch();} }start(char fx,int ditu[21][21],int *xz,int *yz,int *chang) //游戏主函数{ yidong(fx,xz,yz); end=over(ditu,xz,yz); if(end==0) return; if(ditu[*yz][*xz]<0) //是否为食物 eat(ditu,xz,yz,chang); ditu[*yz][*xz]=*chang; dayin(ditu); fx=gbfx(fx); system("cls"); //清屏 start(fx,ditu,xz,yz,chang); //重复游戏主函数 } yidong(char fx,int *xz, int *yz) //移动算法函数{ if(fx=='w') --*yz; if(fx=='s') ++*yz; if(fx=='a') --*xz; if(fx=='d') ++*xz;}eat(int ditu[21][21],int *xz,int *yz,int *chang) //吃食物函数(加长蛇身){ int x,y; ++*chang; for(y=1;y<=20;y++) for(x=1;x<=20;x++) if(ditu[y][x]>0) ++ditu[y][x]; kudamono(ditu); }kudamono(int ditu[21][21]) //产生食物函数{ int x,y; x=(rand()%19)+1; y=(rand()%19)+1; if(ditu[y][x]==0) ditu[y][x]=-1; //判断是否在蛇身上 else kudamono(ditu); }dayin(int ditu[21][21]) //打印画面函数 { int x,y;for(x=0;x<22;x++) printf("■"); //打印上边框printf("\n"); for(y=1;y<=20;y++) { printf("■"); //打印左边框 for(x=1;x<=20;x++) { if(ditu[y][x]!=0) { printf("■"); ditu[y][x]--; } else printf(" "); } printf("■\n"); //打印右边框 }for(x=0;x<22;x++) printf("■"); //打印下边框printf("\n"); }gbfx(char fx) //改变方向函数{ char nfx; if (!kbhit()) return (fx); //如果没有按键便返回原方向 else { nfx=getch(); if(nfx=='W'||nfx=='S'||nfx=='A'||nfx=='D') nfx=nfx+32; //大写改小写 if(nfx=='w'&&fx!='s'||nfx=='s'&&fx!='w'||nfx=='a'&&fx!='d'||nfx=='d'&&fx!='a') return (nfx); if(nfx=='\r') pau('a'); return (fx); }}over(int ditu[21][21],int *xz,int *yz) //是否死亡{ if(ditu[*yz][*xz]>0||*yz<1||*yz>20||*xz<1||*xz>20) return 0; else return 1; } caidan(char c,int w) //主菜单函数{ system("cls"); printf("WSAD上下左右,Enter确定,游戏中Enter暂停、继续\n"); printf(" "); if(w==1) printf("\b\b→"); printf(" 开始游戏\n"); printf(" "); if(w==2) printf("\b\b→"); printf(" 游戏设置\n"); printf(" "); if(w==3) printf("\b\b→"); printf(" 退出游戏\n"); c=getch(); if(c=='W'||c=='S') c=c+32; if(c=='w') --w; if(c=='s') ++w; if(w<1) w=1; if(w>3) w=3; if(c=='\r') {if(w==3) { w=exi(); if(w==0) return w; else caidan(c,w); } return w; } caidan(c,w); }exi() //退出游戏函数{ char x; printf("是否退出游戏?Y确定,任意键继续..."); x=getch(); if(x=='Y'||x=='y') return 0; else return 1; } sett(int *chang) //游戏设置函数{ int sh; printf("输入蛇身的长度\n"); scanf("%d",&sh); if(sh>=100) { printf("搞得这么长干什么 重新设置^_^\n"); //随手恶搞 sett(chang); } *chang=sh; caidan('w',1);}pau(char p) //暂停函数{ if(p=='\r') return 0; if (!kbhit()) { system("cls"); Sleep(500); printf("\n\n\n\n\n\n pause"); Sleep(1500); } else { p=getch(); if(p=='\r') return 0; } pau('a'); }