用vsc++写一个扫雷程序
时间: 2023-12-03 11:01:52 浏览: 139
好的,下面是一个简单的扫雷程序的代码,使用 Visual Studio C++编写:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROWS = 10;
const int COLS = 10;
const int MINES = 10;
void initBoard(int board[][COLS]) {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = 0;
}
}
}
void placeMines(int board[][COLS]) {
srand(time(nullptr));
int count = 0;
while (count < MINES) {
int row = rand() % ROWS;
int col = rand() % COLS;
if (board[row][col] != -1) {
board[row][col] = -1;
++count;
}
}
}
void printBoard(int board[][COLS], bool showMines = false) {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == -1 && showMines) {
cout << "* ";
} else if (board[row][col] == -2) {
cout << "F ";
} else if (board[row][col] >= 0) {
cout << board[row][col] << " ";
} else {
cout << ". ";
}
}
cout << endl;
}
cout << endl;
}
void updateBoard(int board[][COLS], int row, int col) {
if (board[row][col] == -1) {
// game over
board[row][col] = -3;
printBoard(board, true);
cout << "Game over!" << endl;
exit(0);
} else if (board[row][col] == 0) {
board[row][col] = -2;
printBoard(board);
if (row > 0) updateBoard(board, row - 1, col);
if (row < ROWS - 1) updateBoard(board, row + 1, col);
if (col > 0) updateBoard(board, row, col - 1);
if (col < COLS - 1) updateBoard(board, row, col + 1);
} else {
board[row][col] = board[row][col] + 1;
}
}
int main() {
int board[ROWS][COLS];
initBoard(board);
placeMines(board);
printBoard(board);
while (true) {
cout << "Enter row and col: ";
int row, col;
cin >> row >> col;
updateBoard(board, row, col);
printBoard(board);
}
return 0;
}
```
程序使用二维数组表示地图,-1表示地雷,-2表示插旗,-3表示插错了旗。程序先随机放置地雷,再让玩家插旗,直到所有地雷都被插旗或被挖开。如果玩家挖到地雷,则游戏结束。
阅读全文