/* /* 頭尾平移的方法實現 By black4yl 原理: 在大小爲100的數組中,利用head,rear標記的頭,尾座標值,定位當前頭和尾巴。 在行走時,擦去尾巴,按方向標記新頭,擦去舊頭, 實現蛇行走。 當吃到食物時,只變化頭,不變化 */ #include"windows.h" #include"conio.h" #include"iostream" #include<time.h> using namespace std; #define up 72 #define down 80 #define left 75 #define right 77 void GotoXY(int x,int y) { COORD c; c.X=x-1; c.Y=y-1; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); } void Display(char img[][22],int score,int speed) //0爲空 1爲身子 2爲頭 3爲食物 { system("cls"); int i,j; GotoXY(1,1); for(i=0;i<24;i++) cout<<"□"; cout<<endl; for(i=0;i<22;i++) { cout<<"□"; for(j=0;j<22;j++) { if(img[i][j]==0) cout<<" "; if(img[i][j]==1) cout<<"○"; if(img[i][j]==2) cout<<"○"; if(img[i][j]==3) cout<<"○"; } cout<<"□"<<endl; } for(i=0;i<24;i++) cout<<"□"; GotoXY(50,10); printf("Score: %d 分",score); GotoXY(50,11); printf("speed= %d ms",speed); } void Welcome() { long time=clock(); GotoXY(3,8); cout<<"歡迎進入貪吃蛇遊戲"<<endl; while(clock()-time<2000); system("cls"); GotoXY(3,8); time=clock(); cout<<"操作方法: 按 上 下 左 右 鍵控制蛇,以便吃到更多的食物,不要餓死哦~ "<<endl; GotoXY(6,13); int i=4; do { time=clock(); while(clock()-time<1000); GotoXY(6,13); cout<<"遊戲將在--"<<i<<"--秒"<<"後開始"; }while(i--); system("cls"); } int main() { int x, y; int fx,fy; //食物 srand(time(0)); fx=rand()%20+1; fy=rand()%20+1; int len=0; int i,j; int tcspos[2][150]; char img[22][22]={0}; char arr=77; long time;//時間 int timeover; int speed=500,score=0; int head,rear; head=3; rear=0; for(i=0; i<4; i++){ //初始化蛇身 tcspos[0][i] = 1; tcspos[1][i] = i + 1; } img[fy][fx]=3; Welcome(); Display(img,score,speed); while(1) { timeover=1; time=clock(); while((timeover=clock()-time<=speed)&&!kbhit()); if(timeover) //timeover 非0,說明是按鍵中斷循環 { getch(); arr=getch(); } switch(arr) { //完成操作 case up: y=tcspos[1][head]-1; x=tcspos[0][head]; break; //上 case down: y=tcspos[1][head]+1; x=tcspos[0][head]; break; //下 case left: y=tcspos[1][head]; x=tcspos[0][head]-1; break; //左 case right: y=tcspos[1][head]; x=tcspos[0][head]+1; break; //右 } if(img[y][x]!=0&&!((x==fx)&&(y==fy))) //衝突 { break; //結束 } if(x<0||x>21||y<0||y>21) { break; //結束 } if((x==fx)&&(y==fy)) //吃到 { len++; score+=2; //每吃一個加2分 if(len>9) //蛇長大於10, { len%=9; //重新計算 speed-=20; //每次速度增加20ms score+=10; //沒完成一個10,則多加10分 } img[tcspos[1][head]][tcspos[0][head]]=2; //標記行走後的頭 head=(head+1)%150; //head 移到第二位; tcspos[0][head]=x; //設置蛇頭座標 tcspos[1][head]=y; do //生產食物 { fx=rand()%21+1; fy=rand()%21+1; }while(img[fy][fx]!=0); img[fy][fx]=3; Display(img,score,speed); } else //沒吃到 { img[tcspos[1][head]][tcspos[0][head]]=1; //頭變爲身子 head=(head+1)%150; //頭前移 img[tcspos[1][rear]][tcspos[0][rear]]=0; //消去尾巴 rear=(rear+1)%150; //尾巴前移 tcspos[1][head]=y; tcspos[0][head]=x; img[tcspos[1][head]][tcspos[0][head]]=2; //標記新頭 Display(img,score,speed); } } //while() system("cls"); GotoXY(20,12); cout<<"score:"<<score<<endl; GotoXY(20,13); cout<<"---Game Over---"<<endl; GotoXY(20,14); cout<<"請輸入您的姓名:"; getchar(); }
貪吃蛇C語言實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.