写一个c++的扫雷游戏的代码
时间: 2023-08-24 21:51:06 浏览: 42
当然可以!以下是一个简单的C++扫雷游戏的代码示例:
```cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int BOARD_SIZE = 10;
const int NUM_MINES = 10;
vector<vector<char>> board(BOARD_SIZE, vector<char>(BOARD_SIZE, '-'));
void placeMines() {
int count = 0;
while (count < NUM_MINES) {
int x = rand() % BOARD_SIZE;
int y = rand() % BOARD_SIZE;
if (board[x][y] != '*') {
board[x][y] = '*';
count++;
}
}
}
bool isValid(int x, int y) {
return (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE);
}
int countAdjacentMines(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int newX = x + i;
int newY = y + j;
if (isValid(newX, newY) && board[newX][newY] == '*') {
count++;
}
}
}
return count;
}
void revealBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == '*') {
cout << "* ";
} else {
int count = countAdjacentMines(i, j);
cout << count << " ";
}
}
cout << endl;
}
}
bool hasWon() {
int count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == '-') {
count++;
}
}
}
return (count == NUM_MINES);
}
void playGame() {
int x, y;
while (!hasWon()) {
cout << "Enter the coordinates (x, y): ";
cin >> x >> y;
if (isValid(x, y) && board[x][y] != '*') {
int count = countAdjacentMines(x, y);
board[x][y] = count + '0';
} else {
cout << "Invalid move! Try again." << endl;
}
revealBoard();
}
cout << "Congratulations! You won the game." << endl;
}
int main() {
srand(time(nullptr)); // Seed the random number generator
placeMines();
playGame();
return 0;
}
```
***