帮我写一段扫雷游戏代码
时间: 2023-04-07 07:04:22 浏览: 106
好的,以下是一段简单的扫雷游戏代码:
```
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROWS = 10;
const int COLS = 10;
const int MINES = 10;
vector<vector<int>> board(ROWS, vector<int>(COLS, 0));
vector<vector<bool>> revealed(ROWS, vector<bool>(COLS, false));
vector<pair<int, int>> mines(MINES);
void placeMines() {
srand(time(NULL));
int count = 0;
while (count < MINES) {
int row = rand() % ROWS;
int col = rand() % COLS;
if (board[row][col] != -1) {
board[row][col] = -1;
mines[count] = make_pair(row, col);
count++;
}
}
}
void printBoard() {
cout << " ";
for (int i = 0; i < COLS; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < ROWS; i++) {
cout << i << " ";
for (int j = 0; j < COLS; j++) {
if (revealed[i][j]) {
if (board[i][j] == -1) {
cout << "* ";
} else {
cout << board[i][j] << " ";
}
} else {
cout << "- ";
}
}
cout << endl;
}
}
int countMines(int row, int col) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int r = row + i;
int c = col + j;
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] == -1) {
count++;
}
}
}
return count;
}
void reveal(int row, int col) {
if (board[row][col] == -1) {
cout << "Game over!" << endl;
printBoard();
exit(0);
}
revealed[row][col] = true;
if (countMines(row, col) == 0) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int r = row + i;
int c = col + j;
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && !revealed[r][c]) {
reveal(r, c);
}
}
}
}
}
int main() {
placeMines();
printBoard();
while (true) {
int row, col;
cout << "Enter row and column: ";
cin >> row >> col;
reveal(row, col);
printBoard();
}
return 0;
}
```
这段代码实现了一个简单的扫雷游戏,玩家可以输入行和列来揭开对应的方块,如果揭开的方块是地雷,游戏结束。如果揭开的方块周围没有地雷,会自动揭开周围的方块。
阅读全文