贪吃蛇C++编程.pdf
上传人:qw****27 上传时间:2024-09-12 格式:PDF 页数:7 大小:57KB 金币:15 举报 版权申诉
预览加载中,请您耐心等待几秒...

贪吃蛇C++编程.pdf

贪吃蛇C++编程.pdf

预览

在线预览结束,喜欢就下载吧,查找使用更方便

15 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

1.//这个是背景的单元格数据结构2.constlength=40;3.constwidth=20;4.structsquare{5.boolblocked;//是否有障碍物6.boolfood;//是否有食物7.intx;//单元格在背景中的相对横坐标8.inty;//单元格在背景中的相对纵坐标9.}bg[length][width];//直接创建游戏背景10.11.//设置背景12.voidsetBG(intlength,intwidth){13.HANDLEhOut;14.COORDOutChar;15.OutChar.X=10;16.OutChar.Y=10;17.inti=0;18.intj=0;19.for(i=0;i<width;i++){20.for(j=0;j<length;j++){21.bg[i][j].x=i;22.bg[i][j].y=j;23.bg[i][j].blocked=false;24.bg[i][j].food=false;25.OutChar.X=j+10;26.hOut=GetStdHandle(STD_OUTPUT_HANDLE);27.SetConsoleCursorPosition(hOut,OutChar);28.cout<<col(BG_WHITE,true)<<"";29.}30.cout<<endl;31.OutChar.Y=i+10;32.SetConsoleCursorPosition(hOut,OutChar);33.}34.}35.//构造障碍物36.voidcreateBlock(intx,inty,unsignedshortcolor){37.HANDLEhOut;38.COORDOutChar;39.OutChar.X=x;40.OutChar.Y=y;41.hOut=GetStdHandle(STD_OUTPUT_HANDLE);42.SetConsoleCursorPosition(hOut,OutChar);//定位光标输入43.cout<<col(color,true)<<"";//一个颜色为color的空白字符44.}45.46.//生成单个障碍物47.voidcreateWall(intx,inty){48.createBlock(x+10,y+10,BG_GREEN);49.bg[x][y].blocked=true;50.}51.52.//判断所指坐标是否被占用53.boolcheckExisted(intx,inty){54.if(bg[x][y].blocked==true||bg[x][y].food==true){55.returnfalse;56.}57.returntrue;58.}59.60.//随机生成障碍物61.voidrand_createWall(void){62.srand((unsigned)time(NULL));63.intn=rand()%70+10;64.intpos_x=0;65.intpos_y=0;66.inti=0;67.for(i=0;i<n;i++){68.pos_x=rand()%length;69.pos_y=rand()%(width-1);70.if(checkExisted(pos_x,pos_y)==true){//防止障碍物重叠71.createWall(pos_x,pos_y);72.}else{73.n++;74.}75.//createWall(pos_x,pos_y);76.}77.}78.//创建食物79.voidcreateFood(intx,inty){80.createBlock(x+10,y+10,BG_BLUE);81.bg[x][y].food=true;82.}83.84.//随机创建食物85.voidrand_createFood(void){86.srand((unsigned)time(NULL));87.intn=1;//rand()%20;88.intpos_x=0;89.intpos_y=0;90.inti=0;91.for(i=0;i<n;i++){92.pos_x=rand()%length;93.pos_y=rand()%(width-1);94.if(checkExisted(pos_x,pos_y)==true){//防止在障碍物上生成食物95.createFood(pos_x,pos_y);96.}else{97.n++;98.}99