利用rand函数随机插雷,简单利用数组;可以通过bfs或dfs实现棋盘的延伸显示
#include <iostream> #include <stdlib.h> #include <time.h> #include <queue> #define ROW 10//定义棋盘大小 #define LOW 10//定义棋盘大小 using namespace std; void menu();//打印菜单 void game();//主体函数 void Initboard(char board[ROW+2][LOW+2],int row,int low);//初始化扫雷表面 void Initqizi(int qizi[ROW+2][LOW+2],int row, int low);//初始化所有格子 void Set(int qizi[ROW + 2][LOW + 2], int row, int low);//插入雷 void Print(char board[ROW + 2][LOW + 2], int row, int low); void Print(int qizi[ROW + 2][LOW + 2], int row, int low);//函数重载打印棋盘以及游戏结束后雷的分布 char Judgement(int qizi[ROW + 2][LOW + 2], int row, int low, int x, int y);//判断周围有几个雷 int Judgewin(char board[ROW+2][LOW+2],int row,int low);//判断玩家是否胜利 int main() { int input; srand((unsigned int)time(NULL));//利用rand函数 do { menu(); cin >> input; switch (input) { case 1:game(); break; case 0:break; default:cout << "input error" << endl; } } while (input); return 0; } void menu() //菜单函数实现 { printf("****************\n"); printf("**** 1.play ****\n"); printf("**** 0.exit ****\n"); printf("****************\n"); } void game() { char board[ROW + 2][LOW + 2] ; int qizi[ROW + 2][LOW + 2]; Initboard(board, ROW, LOW); Initqizi(qizi, ROW, LOW); Set(qizi, ROW, LOW); Print(board, ROW, LOW); while (1) { cout << "please input coordinates:"; int x, y; cin >> x >>y; cout << endl; if (qizi[x][y]) { cout << "game over" << endl; break; } board[x][y]= Judgement(qizi, ROW, LOW, x, y); Print(board, ROW, LOW); if (Judgewin(board, ROW, LOW)) { cout << "palyer win" << endl; break; } } Print(qizi, ROW, LOW); } void Initboard(char board[ROW +2][LOW+2 ], int row, int low) { for (int i = 0; i < row + 2; i++) for (int j = 0; j < low + 2; j++) board[i][j] = '*'; } void Initqizi(int qizi[ROW + 2][LOW + 2], int row, int low) { for (int i = 0; i < row + 2; i++) for (int j = 0; j < low + 2; j++) qizi[i][j] = 0; } void Print(char board[ROW + 2][LOW + 2], int row, int low) { for (int i = 1; i < row + 1; i++) { for (int j = 1; j < low + 1; j++) cout << board[i][j]; cout << endl; } } void Print(int qizi[ROW + 2][LOW + 2], int row, int low) { for (int i = 1; i < row + 1; i++) { for (int j = 1; j < low + 1; j++) cout << qizi[i][j]; cout << endl; } } void Set(int qizi[ROW + 2][LOW + 2], int row, int low) { int count = ROW; while (count--) { int x = rand()% ROW + 1; int y = rand() % ROW + 1; if (qizi[x][y]) continue; qizi[x][y] = 1; } } char Judgement(int qizi[ROW + 2][LOW + 2], int row, int low, int x, int y) { int count = 0; count = qizi[x - 1][y] + qizi[x - 1][y + 1] + qizi[x - 1][y - 1] + qizi[x][y - 1] + qizi[x][y + 1] + qizi[x + 1][y] + qizi[x + 1][y - 1] + qizi[x + 1][y + 1]; char ch = count + '0'; return ch; } int Judgewin(char board[ROW + 2][LOW + 2], int row, int low) { int count = 0; for (int i = 1; i < row - 1; i++) for (int j = 1; j < low - 1; j++) if (board[i][j] != '*') count++; if (count == row * low - row) return 1; return 0; }