#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
const int WIDTH = 10;
const int HEIGHT = 10;
const int MINE_COUNT = 10;
class MineSweeper {
private:
vector<vector<int>> board;
vector<vector<bool>> revealed;
// 初始化棋盘
void initBoard() {
board.resize(HEIGHT, vector<int>(WIDTH, 0));
revealed.resize(HEIGHT, vector<bool>(WIDTH, false));
// 随机放置地雷
srand(static_cast<unsigned int>(time(nullptr)));
int count = 0;
while (count < MINE_COUNT) {
int x = rand() % WIDTH;
int y = rand() % HEIGHT;
if (board[y][x]!= -1) {
board[y][x] = -1;
count++;
}
}
// 计算每个格子周围的地雷数量
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (board[y][x]!= -1) {
int mineCount = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT && board[ny][nx] == -1) {
mineCount++;
}
}
}
board[y][x] = mineCount;
}
}
}
}
// 打印棋盘
void printBoard() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (revealed[y][x]) {
if (board[y][x] == -1) {
cout << "* ";
} else {
cout << board[y][x] << " ";
}
} else {
cout << "# ";
}
}
cout << endl;
}
}
// 递归揭示空白区域
void revealEmpty(int x, int y) {
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT || revealed[y][x]) {
return;
}
revealed[y][x] = true;
if (board[y][x] == 0) {
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
revealEmpty(x + dx, y + dy);
}
}
}
}
public:
MineSweeper() {
initBoard();
}
void play() {
int x, y;
while (true) {
printBoard();
cout << "PLEASE INPUT (x y): ";
cin >> x >> y;
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
cout << "ERROR!" << endl;
continue;
}
if (board[y][x] == -1) {
cout << "BOOM,YOU LOSE!" << endl;
break;
}
revealed[y][x] = true;
if (board[y][x] == 0) {
revealEmpty(x, y);
}
bool allRevealed = true;
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (board[y][x]!= -1 &&!revealed[y][x]) {
allRevealed = false;
break;
}
}
}
if (allRevealed) {
cout << "YOU WIN!" << endl;
break;
}
}
}
};
int main() {
MineSweeper game;
game.play();
return 0;
}
扫雷小游戏源码
最新推荐文章于 2024-09-27 11:26:03 发布