用c++创造一个扫雷游戏
时间: 2024-01-07 16:04:41 浏览: 24
以下是用C++实现一个简单的扫雷游戏的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int SIZE = 10;
const int NUM_MINES = 10;
void printBoard(const vector<vector<char>>& board) {
for (int i = 0; i < SIZE; i++) for (int j = 0; j < SIZE; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
void placeMines(vector<vector<char>>& board) {
int count = 0;
while (count < NUM_MINES) {
int row = rand() % SIZE;
int col = rand() % SIZE;
if (board[row][col] != '*') {
board[row][col] = '*';
count++;
}
}
}
void calculateNumbers(vector<vector<char>>& board) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] != '*') {
int count = 0;
if (i > 0 && j > 0 && board[i - 1][j - 1] == '*') {
count++;
}
if (i > 0 && board[i - 1][j] == '*') {
count++;
}
if (i > 0 && j < SIZE - 1 && board[i - 1][j + 1] == '*') {
count++;
}
if (j > 0 && board[i][j - 1] == '*') {
count++;
}
if (j < SIZE - 1 && board[i][j + 1] == '*') {
count++;
}
if (i < SIZE - 1 && j > 0 && board[i + 1][j - 1] == '*') {
count++;
}
if (i < SIZE - 1 && board[i + 1][j] == '*') {
count++;
}
if (i < SIZE - 1 && j < SIZE - 1 && board[i + 1][j + 1] == '*') {
count++;
}
board[i][j] = count + '0';
}
}
}
}
int main() {
srand(time(0));
vector<vector<char>> board(SIZE, vector<char>(SIZE, '0'));
placeMines(board);
calculateNumbers(board);
printBoard(board);
return 0;
}
```