C语言—贪吃蛇双人对战
生活随笔
收集整理的這篇文章主要介紹了
C语言—贪吃蛇双人对战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?貪吃蛇雙人對戰源代碼及詳解
規則 :玩家一(左側)通過按鍵W、S、A、D(大小寫)四個鍵分別控制snake1上移、下移、左移和右移。玩家二(右側)通過按鍵8、5、4、6 四個鍵分別控制snake2上移、下移、左移和右移。
每局游戲三分鐘,死亡則直接失敗,若時間結束,則分高者獲勝。????
每次游戲數據自動疊加保存并進行排名,若賬號第一次使用,則創建新成績。
?
?源代碼及詳細解析:
#include <stdio.h> #include <stdlib.h> #include <Windows.h> #include <time.h> #include<stdbool.h> #include <conio.h> #define SNAKESIZE 100 #define MAPWIDTH 118 #define MAPHEIGHT 29 #define M 200 void gotoxy (); void MAP (); void OPERATION (); void createFood0 (); void createFood (); void createFood1 (); bool check (); bool check1 (); void READ (); void RANK (); void OVER0 (); void OVER (); void fun (); void fun1 (); void START (); void RULE (); void MENU (); void WRITE (char s[20],int score,char s1[20],int score1); void PPX (); struct game {char name[20];int win , lost , score;double prob;double jf; }card[M+1];struct { //保存食物坐標int x;int y; }food;struct {int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake;struct {int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake1; char key = '8' , key1 = 'w' , name[20] , name1[20]; //初始方向向上 int changeFlag = 0 , changeFlag1 = 0 , jf =0 , jf1 =0; int speed=150 , sorce = 0 , sorce1 = 0 , sec=0 , min=3;void gotoxy(int x, int y)//移動光標到指定位置 {COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } void MAP()//打印邊框和兩條蛇的起始位置 {for (int i = 0; i <= MAPWIDTH; i += 2)//打印最上面和最下面兩橫邊框{gotoxy(i, 0);printf("■");gotoxy(i, MAPHEIGHT);printf("■");}for (int i = 1; i < MAPHEIGHT; i++)//打印最左面和最右面{gotoxy(0, i);printf("■");gotoxy(MAPWIDTH, i);printf("■");}while (1)//打印一個食物{srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;if (food.x % 2 == 0)break;}gotoxy(food.x, food.y);printf("★");snake.len = snake1.len = 4;//給兩條蛇的長度賦初值snake.x[0] = MAPWIDTH / 2 + 31;//然后分別打印兩條蛇身部分snake.y[0] = MAPHEIGHT / 2;snake1.x[0] = MAPWIDTH / 2 - 31;snake1.y[0] = MAPHEIGHT / 2;gotoxy(snake.x[0] , snake.y[0] );printf("■");gotoxy(snake1.x[0], snake1.y[0]);printf("●");for (int i = 1; i < snake.len; i++){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1]+1;gotoxy(snake.x[i] , snake.y[i] );printf("■");snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1]+1;gotoxy(snake1.x[i], snake1.y[i]);printf("●");}gotoxy(MAPWIDTH , 0);//把光標移走return; } void OPERATION()//操作函數 {char pre_key = key , pre_key1 = key1 , s;//保存兩條蛇上一次的方向if (_kbhit()){s = getch();if(s=='w'||s=='s'||s=='a'||s=='d'||s=='W'||s=='S'||s=='A'||s=='D')key1=s;else if(s == '8' || s == '5' || s == '4' || s == '6')key=s;}if (changeFlag == 0)//沒吃到食物{gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾處輸出空格即擦去蛇尾}if (changeFlag1 == 0){gotoxy(snake1.x[snake1.len - 1], snake1.y[snake1.len - 1]);printf(" ");//在蛇尾處輸出空格即擦去蛇尾}//將蛇的每一節依次向前移動一節(蛇頭除外)for (int i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}for (int i = snake1.len - 1; i > 0; i--){snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1];}//蛇當前移動的方向不能和前一次的方向相反,比如蛇往左走的時候不能直接按右鍵往右走//如果當前移動方向和前一次方向相反的話,把當前移動的方向改為前一次的方向if (pre_key == '8' && key == '5')key = '8';if (pre_key == '5' && key == '8')key = '5';if (pre_key == '4' && key == '6')key = '4';if (pre_key == '6' && key == '4')key = '6';if (pre_key1 == 'w' && key1 == 's')key1 = 'w';if (pre_key1 == 's' && key1 == 'w')key1 = 's';if (pre_key1 == 'a' && key1 == 'd')key1 = 'a';if (pre_key1 == 'd' && key1 == 'a')key1 = 'd';//判斷蛇頭應該往哪個方向移動switch (key){case '4':snake.x[0] -= 2;//往左break;case '6':snake.x[0] += 2;//往右break;case '8':snake.y[0]--;//往上break;case '5':snake.y[0]++;//往下break;}gotoxy(snake.x[0], snake.y[0]);printf("■");changeFlag = 0;switch (key1){case 'a':case 'A':snake1.x[0] -= 2;//往左break;case 'd':case 'D':snake1.x[0] += 2;//往右break;case 'w':case 'W':snake1.y[0]--;//往上break;case 's':case 'S':snake1.y[0]++;//往下break;}gotoxy(snake1.x[0], snake1.y[0]);printf("●");changeFlag1 = 0;gotoxy(MAPWIDTH,MAPHEIGHT);return; } void createFood() {if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇頭碰到食物{//蛇頭碰到食物即為要吃掉這個食物了,因此需要再次生成一個食物createFood0();createFood0();snake.len++;//吃到食物,蛇身長度加1sorce += 10;speed -= 5;//隨著吃的食物越來越多,速度會越來越快changeFlag = 1;//很重要,因為吃到了食物,就不用再擦除蛇尾的那一節,以此來造成蛇身體增長的效果}return; } void createFood1() {if (snake1.x[0] == food.x && snake1.y[0] == food.y)//蛇頭碰到食物{//蛇頭碰到食物即為要吃掉這個食物了,因此需要再次生成一個食物createFood0();createFood0();snake1.len++;//吃到食物,蛇身長度加1sorce1 += 10;speed -= 5;//隨著吃的食物越來越多,速度會越來越快changeFlag1 = 1;//很重要,因為吃到了食物,就不用再擦除蛇尾的那一節,以此來造成蛇身體增長的效果}return; } void createFood0() {while (1){int a = 1 , b=1;srand( (unsigned int)time(NULL) );food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//隨機生成的食物不能在蛇的身體上for (int i = 0; i < snake.len ; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){a = 0;break;}}for (int i = 0; i < snake1.len; i++){if (snake1.x[i] == food.x && snake1.y[i] == food.y){b = 0;break;}}//隨機生成的食物不能橫坐標為奇數,也不能在蛇身,否則重新生成if (a==1&&b==1&& food.x % 2 == 0)break;}//繪制食物gotoxy(food.x, food.y);printf("★"); } bool check() {//蛇頭碰到上下邊界,游戲結束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return true;//蛇頭碰到左右邊界,游戲結束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return true;//蛇頭碰到蛇身,游戲結束for (int i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return true;}for (int i = 0; i < snake1.len; i++){if(snake1.x[i] == snake.x[0]&&snake1.y[i] == snake.y[0])return true;}return false; } bool check1() {//蛇頭碰到上下邊界,游戲結束if (snake1.y[0] == 0 || snake1.y[0] == MAPHEIGHT)return true;//蛇頭碰到左右邊界,游戲結束if (snake1.x[0] == 0 || snake1.x[0] == MAPWIDTH)return true;//蛇頭碰到蛇身,游戲結束for (int i = 1; i < snake1.len; i++){if (snake1.x[i] == snake1.x[0] && snake1.y[i] == snake1.y[0])return true;}for (int i = 0; i < snake.len; i++){if (snake.x[i] == snake1.x[0] && snake.y[i] == snake1.y[0])return true;}return false; } void MENU ()//打印菜單界面 {printf("\n\n\n\n\t\t\t\t ╔═══════════════════════════════════════════╗\n");printf("\t\t\t\t ║ ║\n");printf("\t\t\t\t ║ 歡迎來到貪吃蛇 ║\n");printf("\t\t\t\t ║ ║\n");printf("\t\t\t\t ║ ║\n");printf("\t\t\t\t ║ ┏━━┓ ┏━━┓ ┏━━┓ ┏━━┓ ║\n");printf("\t\t\t\t ║ 開始:┃ 1┃ 規則:┃ 2┃ 排行:┃ 3┃ 退出:┃ 4┃ ║\n");printf("\t\t\t\t ║ ┗━━┛ ┗━━┛ ┗━━┛ ┗━━┛ ║\n");printf("\t\t\t\t ║ ║\n");printf("\t\t\t\t ║ ║\n");printf("\t\t\t\t ╚═══════════════════════════════════════════╝\n");switch(getch()){case '1':system("cls");START();break;case '2':system("cls");fun(5);RULE();MENU();break;case '3':system("cls");fun(10);RANK();MENU();break;case '4':exit(0);break;default:system("cls");printf("error");MENU();} } void RULE () {system("cls");//清屏printf("\t╔══════════════════════════════════════════════════════════════════════════════════════════════════╗\n");printf("\t║本游戲玩家一(左側)通過按鍵W、S、A、D(不區分大小寫)四個鍵分別控制snake1上移、下移、左移和右移。║\n");printf("\t║玩家二(右側)通過按鍵8、5、4、6 四個鍵分別控制snake2上移、下移、左移和右移。 ║\n");printf("\t║每局游戲三分鐘,死亡則直接失敗,若時間結束,則分高者獲勝,獲勝積分加十,失敗積分加五。 ║\n");printf("\t║每次游戲數據自動疊加保存并按照積分乘勝率進行排名,若賬號第一次使用,則創建新賬號保存新成績。 ║\n");printf("\t╚══════════════════════════════════════════════════════════════════════════════════════════════════╝\n");system("pause");//暫停system( "cls" );//清屏 } void fun(int time)//進度條函數 {int i = 0;char bar[102] = { 0 };gotoxy( 33 , 9 );printf ( "數據載入中,請稍后\n" );while (i <= 50){gotoxy(33 , 10);printf("[%-50s][%3d%%]\r", bar, i * 2);Sleep ( time );bar[i++] = '*';bar[i] = '\0';}system("cls"); } void fun1(int time)//進度條函數 {int i = 0;char bar[102] = { 0 };gotoxy( 33 , 9 );printf ( "游戲啟動中,請做好準備\n" );while (i <= 50){gotoxy(33 , 10);printf("[%-50s][%3d%%]\r", bar, i * 2);Sleep ( time );bar[i++] = '*';bar[i] = '\0';}system("cls"); } void START() {time_t time_sec = 0;time_t old_sec = 0;printf("\n\n\t\t\t\t請左側玩家輸入賬號:");scanf("%s",&name1);printf("\n\n\t\t\t\t請右側玩家輸入賬號:");scanf("%s",&name);while(strcmp(name1,name)==0){printf("\n\n\t\t\t\t請輸入不同的賬號:");scanf("%s",&name);}//進度條進度條system("pause");system( "cls" );fun1 (19);MAP ();time(&time_sec); //獲取時間old_sec = time_sec; //保存時間while (!check()&&!check1()){OPERATION ();createFood ();createFood1 ();Sleep( speed );time(&time_sec); //獲取秒數保存到time_t變量if(time_sec != old_sec) //如果秒數改變(計時達到1秒){old_sec = time_sec; //更新舊的秒數if(sec > 0)sec --; //計時秒數減1else{sec=59; //如果原秒數為0,則變為59min --; //計時分鐘減1}}if(min==0 && sec==0)break;if(min==0 && sec<=8)printf("\a");gotoxy(0 ,0);printf("倒計時——%02d:%02d\r",min, sec);}system( "cls" );printf("\n\n\t\t\tGame Over!\n");system( "pause" );OVER (); }void OVER () {system("cls");printf("\n\n\n\n\t\t\t\t╔═══════════════════════════════════════════╗\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ 游戲結束 ║\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ║\n");if(check()&&!check1()){WRITE(name1,sorce1,name,sorce);printf("\t\t\t\t║ %10s獲勝 %10s失敗 ║\n",name1,name);}else if(!check()&&check1()){WRITE(name,sorce,name1,sorce1);printf("\t\t\t\t║ %10s獲勝 %10s失敗 ║\n",name,name1);}else{printf("\t\t\t\t║ %10s本次游戲得分為:%4d ║\n", name1,sorce1);printf("\t\t\t\t║ %10s本次游戲得分為:%4d ║\n", name , sorce);if(sorce>sorce1){WRITE(name,sorce,name1,sorce1);printf("\t\t\t\t║ %10s獲勝 %10s失敗 ║\n",name,name1);}else if(sorce1>sorce){WRITE(name1,sorce1,name,sorce);printf("\t\t\t\t║ %10s獲勝 %10s失敗 ║\n",name1,name);}elseprintf("\t\t\t\t║ 恭喜你們平局了! ║\n");}printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ┏━━┓ ┏━━┓ ┏━━┓ ║\n");printf("\t\t\t\t║ 再來:┃ 1┃ 排名:┃ 2┃ 退出:┃ 3┃ ║\n");printf("\t\t\t\t║ ┗━━┛ ┗━━┛ ┗━━┛ ║\n");printf("\t\t\t\t╚═══════════════════════════════════════════╝\n");switch(getch()){case '1':for(int i=0;i<M+1;i++){key ='8';key1 ='w';speed=150;snake.x[i] =MAPWIDTH+ 10;snake1.x[i] =MAPWIDTH+ 10;snake.y[i] =MAPHEIGHT+10;snake1.y[i] =MAPHEIGHT+10;}system("cls");MENU ();break;case '2':system("cls");fun(10);RANK ();OVER0();break;case '3':exit(0);break;default:system( "cls" );printf("error");OVER ();}} void OVER0 () {system("cls");printf("\n\n\n\n\t\t\t\t╔═══════════════════════════════════════════╗\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ║\n");printf("\t\t\t\t║ ┏━━┓ ┏━━┓ ┏━━┓ ║\n");printf("\t\t\t\t║ 再來:┃ 1┃ 排名:┃ 2┃ 退出:┃ 3┃ ║\n");printf("\t\t\t\t║ ┗━━┛ ┗━━┛ ┗━━┛ ║\n");printf("\t\t\t\t╚═══════════════════════════════════════════╝\n");switch(getch()){case '1':for(int i=0;i<SNAKESIZE;i++){key1 ='w';key ='8';speed=150;snake.x[i] =MAPWIDTH+ 10;snake1.x[i] =MAPWIDTH+ 10;snake.y[i] =MAPHEIGHT+10;snake1.y[i] =MAPHEIGHT+10;}system("cls");MENU();break;case '2':system("cls");RANK ();OVER0();break;case '3':exit(0);break;default:system( "cls" );printf("error");OVER0();} } void RANK () {int v=1;printf("\t\t\t排名 玩家 積分 勝場 敗場 得分 勝率\n");for(int w=0;w<M+1;w++){if( card[w].jf!=0 ){printf("\t\t\tNO:%3d %10s %5.0lf %5d %5d %11d %3.2lf\n",v,card[w].name,card[w].jf,card[w].win,card[w].lost,card[w].score,card[w].prob*100);v++;}}system("pause");system( "cls" );} void READ () {FILE *w;w = fopen( "d:\\snake.txt","rb" );fread(card,sizeof(struct game),M+1,w);fclose(w); } void WRITE (char s[20],int score,char s1[20],int score1) {FILE *w;int p=0;for(int i=0;i<M+1;i++){if(strcmp(card[i].name,s)==0){p++;card[i].jf+=10;card[i].win += 1;card[i].score+=score;card[i].prob=((double)card[i].win)/((double)(card[i].win+card[i].lost))+0.00001;}}if(p==0){strcpy(card[M/2].name,s);card[M/2].win =1;card[M/2].lost =0;card[M/2].score=score;card[M/2].prob =1;card[M/2].jf=10;}p=0;for(int i=0;i<M+1;i++){if(strcmp(card[i].name,s1)==0){p++;card[i].jf+=5;card[i].lost += 1;card[i].score+=score1;card[i].prob=((double)card[i].win)/((double)(card[i].win+card[i].lost))+0.00001;}}if(p==0){strcpy(card[M/2-1].name,s1);card[M/2-1].win =0;card[M/2-1].lost =1;card[M/2-1].score=score1;card[M/2-1].prob =0.00001;card[M/2-1].jf=5;}PPX ();w=fopen( "d:\\snake.txt" , "wb" );fwrite(card,sizeof(struct game),M+1,w);fclose(w); } void PPX () {int i , j , k;struct game q;for( i = 0 ; i < M ; i ++){k=i;for( j = i+1 ; j < M+1 ; j ++ ){if(card[k].jf*card[k].prob<card[j].jf*card[j].prob)k=j;}q =card[i];card[i]=card[k];card[k]= q;} }int main () {system( "title 雙人貪吃蛇" );system( "color F0" );READ ();MENU ();return 0; }?生成.txt文件保存游戲記錄排行榜
總結
以上是生活随笔為你收集整理的C语言—贪吃蛇双人对战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王者荣耀注销服务器的流程,王者荣耀账号怎
- 下一篇: TM2013自定义消息记录保存目录