C++小遊戲(原創)——掃雷
阿新 • • 發佈:2018-12-13
#include<iostream> #include<cmath> #include<ctime> #include<cstring> #include<stdio.h> #include<stdlib.h> #include<windows.h> #include<conio.h> #define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0) using namespace std; int maxn=16; int maxm=30; int square[100][100]; bool flag[100][100]; int move_x[8]={0,0,1,-1,1,1,-1,-1}; int move_y[8]={1,-1,0,0,1,-1,1,-1}; int xxx,yyy; bool gameover=true; /* 用dfs滑鼠點選的那個點,如果是數字,則直接翻開;如果是空格,則進行搜尋。 */ void dfs(int x,int y){ flag[x][y]=false; if(square[x][y]==-1) gameover=false; if(!gameover) return; if(square[x][y]!=0) return; for(int i=0;i<8;i++) { int now_x=move_x[i]+x; int now_y=move_y[i]+y; if(square[now_x][now_y]!=0){ flag[now_x][now_y]=false; } } for(int i=0;i<4;i++) { int now_x=move_x[i]+x; int now_y=move_y[i]+y; if(flag[now_x][now_y]){ flag[now_x][now_y]=false; dfs(now_x,now_y); } } } /* 數第x,y個格子,周圍有多少個雷 */ int count_num(int x,int y) { int sum=0; for(int i=x-1;i<=x+1;i++) for(int j=y-1;j<=y+1;j++) if (square[i][j]==-1) sum++; return sum; } /* 將下面將要輸出的東西改變顏色 */ void SetColor(unsigned short ForeColor=7,unsigned short BackGroundColor=0) { HANDLE hCon=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hCon,ForeColor|BackGroundColor); } /* 初始化,隨機生成一個雷陣 */ void intt(){ srand(time(NULL)); for(int i=0;i<maxn+5;i++) for(int j=0;j<maxm+5;j++) square[i][j]=9; memset(flag,true,sizeof(flag)); int xx=rand() % maxn+1; int yy=rand() % maxm+1; int num=1; while(num<=99) { while(square[xx][yy]==-1||xx==xxx&&yy==yyy) { xx=rand()%maxn+1; yy=rand()%maxm+1; } square[xx][yy]=-1; num++; } for(int i=1;i<=maxn;i++) for(int j=1;j<=maxm;j++) if(square[i][j]!=-1) square[i][j]=count_num(i,j); } /* 列印未被翻開的雷陣 */ void display(){ for(int i=1;i<=maxn;i++) { for(int j=1;j<=maxm;j++) if(flag[i][j]==false) if(square[i][j]==-1) { SetColor(4); cout<<"* "; SetColor(15); } else if (square[i][j]!=0) cout<<square[i][j]<<" ";else cout<<" ";else cout<<"▇"; cout<<endl; } } /* 如果引爆了雷,則翻開所有的雷陣 */ void display_y(){ for(int i=1;i<=maxn;i++) { for(int j=1;j<=maxm;j++) if(square[i][j]==-1) { SetColor(4); cout<<"* "; SetColor(15); } else if (square[i][j]!=0) cout<<square[i][j]<<" ";else cout<<" "; cout<<endl; } } /* 當滑鼠右鍵點選時,翻開雷陣 */ void work(){ while(1) { POINT p; if(KEY_DOWN(MOUSE_EVENT)) { char ch; HWND h=GetForegroundWindow(); GetCursorPos(&p); ScreenToClient(h,&p); xxx=p.y/16+1; yyy=p.x/16+1; dfs(xxx,yyy); system("cls"); display(); } if(gameover==false) { system("cls"); display_y(); cout<<"GAME OVER!!!"<<endl; system("pause"); break; } Sleep(20); // cin>>xxx>>yyy; } } /* 隱藏游標 */ void HideCursor() { CONSOLE_CURSOR_INFO cursor_info = {1, 0}; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); } int main(){ system("color 0F");//設定背景顏色 system("mode con cols=60 lines=19");//設定黑框大小 HideCursor(); intt(); display(); work(); return 0; }