使用C++语言写一个扫雷游戏
时间: 2023-12-20 07:04:37 浏览: 69
好的,下面是一个简单的 C++ 扫雷游戏实现,仅供参考:
```c++
#include <iostream>
#include <vector>
#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;
void placeMines() {
int count = 0;
while (count < MINES) {
int row = rand() % ROWS;
int col = rand() % COLS;
if (board[row][col] != -1) {
board[row][col] = -1;
mines.push_back(make_pair(row, col));
count++;
}
}
}
void printBoard(bool reveal) {
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 (reveal || 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 = row - 1; i <= row + 1; i++) {
for (int j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == -1) {
count++;
}
}
}
return count;
}
void revealCell(int row, int col) {
if (revealed[row][col]) {
return;
}
revealed[row][col] = true;
if (board[row][col] == -1) {
return;
}
if (countMines(row, col) == 0) {
for (int i = row - 1; i <= row + 1; i++) {
for (int j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS) {
revealCell(i, j);
}
}
}
}
}
bool checkWin() {
int count = 0;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] != -1 && revealed[i][j]) {
count++;
}
}
}
return count == ROWS * COLS - MINES;
}
int main() {
srand(time(NULL));
placeMines();
printBoard(false);
while (true) {
int row, col;
cout << "Enter row and column: ";
cin >> row >> col;
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
cout << "Invalid input!" << endl;
continue;
}
if (revealed[row][col]) {
cout << "Cell already revealed!" << endl;
continue;
}
revealCell(row, col);
printBoard(false);
if (board[row][col] == -1) {
cout << "Game over!" << endl;
printBoard(true);
break;
}
if (checkWin()) {
cout << "You win!" << endl;
printBoard(true);
break;
}
}
return 0;
}
```
这个实现中,使用了一个二维向量 `board` 来表示扫雷的格子,-1 表示该格子是地雷,其他数字表示周围的地雷数量。还使用了一个二维向量 `revealed` 来表示该格子是否已经被翻开。在游戏开始时,随机放置地雷。每次玩家输入一个坐标,程序会将该格子翻开并显示周围地雷数量,如果该格子是地雷则游戏结束,否则继续进行游戏。如果所有非地雷格子都被翻开,则游戏胜利。
阅读全文