21xrx.com
2025-06-18 17:46:31 Wednesday
登录
文章检索 我的文章 写文章
扫雷C++代码编写
2023-07-07 03:52:09 深夜i     20     0
扫雷游戏 C++编程语言 代码编写 游戏规则 程序设计

扫雷是一款非常经典的游戏,现在随着计算机技术的发展,我们可以通过编写代码来实现扫雷游戏。本文将介绍使用C++编写扫雷游戏代码的方法。

首先,我们需要定义一个二维数组来作为游戏中的地图,其中地图上的每个格子都有三种状态:未翻开、已翻开、已标记。我们可以使用0、1、2来表示这三种状态。同时,还需要定义与地图大小相同的另一个二维数组,用来存储每个格子周围的地雷数量,若当前格子本身就是地雷,则直接将其对应的元素置为-1。

代码如下:

const int MAXN = 100;
int board[MAXN][MAXN]; // 地图
int count[MAXN][MAXN]; // 存储每个格子周围的地雷数量
int dx[8] = 0; // 相邻格子的横坐标偏移量
int dy[8] = 0; // 相邻格子的纵坐标偏移量
int n, m; // 地图的大小
// 初始化游戏地图
void initBoard() {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      board[i][j] = 0;
      count[i][j] = 0;
    }
  }
  // 将地雷随机分布在地图上
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (rand() % 10 == 0) { // 每个格子有1/10的概率布置地雷
        board[i][j] = -1;
        for (int k = 0; k < 8; k++) {
          int x = i + dx[k], y = j + dy[k];
          if (x >= 0 && x < n && y >= 0 && y < m && board[x][y] != -1) {
            count[x][y]++;
          }
        }
      }
    }
  }
}

接下来,我们需要实现翻开格子和标记格子这两个操作。其中,翻开一个格子的效果包括显示周围地雷数量(若是地雷则爆炸)、将该格子的状态从“未翻开”变为“已翻开”、自动翻开周围的空格子。标记一个格子的效果就是将其状态从“未翻开”变为“已标记”。

代码如下:

// 翻开一个格子
void open(int x, int y) {
  if (board[x][y] == -1) // 若是地雷则爆炸
    cout << "You lose!" << endl;
    return;
  
  board[x][y] = 1;
  if (count[x][y] == 0) { // 若周围没有地雷则自动翻开周围的空格子
    for (int k = 0; k < 8; k++) {
      int nx = x + dx[k], ny = y + dy[k];
      if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] == 0) {
        open(nx, ny);
      }
    }
  }
}
// 标记一个格子
void mark(int x, int y) {
  if (board[x][y] == 0) {
    board[x][y] = 2;
  } else if (board[x][y] == 2) {
    board[x][y] = 0;
  }
}

最后,我们需要一个主函数来整合所有的代码:

int main() {
  srand(time(NULL));
  // 初始化地图
  n = m = 10;
  initBoard();
  while (true) {
    // 显示地图
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (board[i][j] == 0)
          cout << "#";
         else if (board[i][j] == 1) {
          if (count[i][j] == 0)
            cout << ".";
           else {
            cout << count[i][j];
          }
        } else if (board[i][j] == 2)
          cout << "P";
        
      }
      cout << endl;
    }
    // 询问操作
    int op, x, y;
    cout << "Please input the operation code (1: open, 2: mark): ";
    cin >> op;
    cout << "Please input the coordinate of the square: ";
    cin >> x >> y;
    if (op == 1) { // 翻开一个格子
      open(x, y);
    } else if (op == 2) { // 标记一个格子
      mark(x, y);
    } else
      cout << "Invalid operation code!" << endl;
    
    // 检查游戏是否结束
    bool win = true;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (board[i][j] != 1 && board[i][j] != -1)
          win = false;
          break;
        
      }
    }
    if (win)
      cout << "You win!" << endl;
      break;
    
  }
  return 0;
}

通过以上代码,我们可以编写出一个简单的扫雷游戏,让玩家在计算机上畅玩。不过需要注意的是,以上代码还有许多不足的地方,比如没有对输入的坐标进行合法性检查等,仅供学习参考。

  
  

评论区