帮我写一个扫雷游戏代码
时间: 2023-10-31 07:04:58 浏览: 36
好的,以下是一个简单的扫雷游戏代码实现,供参考:
```
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
const int BOARD_SIZE = 10;
const int NUM_MINES = 10;
void init_board(vector<vector<char>>& board) {
for (int i = 0; i < BOARD_SIZE; i++) {
vector<char> row;
for (int j = 0; j < BOARD_SIZE; j++) {
row.push_back('.');
}
board.push_back(row);
}
}
void place_mines(vector<vector<char>>& board) {
srand(time(NULL));
int num_mines = 0;
while (num_mines < NUM_MINES) {
int x = rand() % BOARD_SIZE;
int y = rand() % BOARD_SIZE;
if (board[x][y] != '*') {
board[x][y] = '*';
num_mines++;
}
}
}
void print_board(const vector<vector<char>>& board) {
cout << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
cout << j << " ";
}
cout << endl;
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool is_valid(int x, int y) {
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE;
}
int count_adjacent_mines(const vector<vector<char>>& board, int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) {
continue;
}
int new_x = x + i;
int new_y = y + j;
if (is_valid(new_x, new_y) && board[new_x][new_y] == '*') {
count++;
}
}
}
return count;
}
int main() {
vector<vector<char>> board;
init_board(board);
place_mines(board);
print_board(board);
while (true) {
int x, y;
cout << "Enter a row and column to reveal: ";
cin >> x >> y;
if (!is_valid(x, y)) {
cout << "Invalid input." << endl;
continue;
}
if (board[x][y] == '*') {
cout << "Game over!" << endl;
break;
}
int num_adjacent_mines = count_adjacent_mines(board, x, y);
board[x][y] = '0' + num_adjacent_mines;
print_board(board);
}
return 0;
}
```
这个代码实现了一个简单的扫雷游戏,生成了一个大小为 10x10 的游戏板,其中有 10 个地雷。玩家可以输入坐标来选择一个格子,如果是地雷则游戏结束,否则会显示周围地雷的数量(用数字 0-8 表示)。