帮我写一个命令行C++扫雷代码
时间: 2023-03-26 10:03:48 浏览: 119
扫雷的c++代码
好的,我可以为您提供一个命令行C语言扫雷代码。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
void init_board(int board[ROWS][COLS], int rows, int cols, int mines);
void print_board(int board[ROWS][COLS], int rows, int cols);
int get_mine_count(int board[ROWS][COLS], int row, int col);
void reveal_board(int board[ROWS][COLS], int rows, int cols, int row, int col);
int is_game_over(int board[ROWS][COLS], int rows, int cols);
int main()
{
int board[ROWS][COLS];
int row, col;
srand(time(NULL));
init_board(board, ROWS, COLS, MINES);
print_board(board, ROWS, COLS);
while (!is_game_over(board, ROWS, COLS))
{
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
if (board[row][col] == -1)
{
printf("You hit a mine! Game over.\n");
break;
}
reveal_board(board, ROWS, COLS, row, col);
print_board(board, ROWS, COLS);
}
return ;
}
void init_board(int board[ROWS][COLS], int rows, int cols, int mines)
{
int i, j, count;
for (i = ; i < rows; i++)
{
for (j = ; j < cols; j++)
{
board[i][j] = ;
}
}
count = ;
while (count < mines)
{
i = rand() % rows;
j = rand() % cols;
if (board[i][j] == )
{
board[i][j] = -1;
count++;
}
}
}
void print_board(int board[ROWS][COLS], int rows, int cols)
{
int i, j;
printf(" ");
for (j = ; j < cols; j++)
{
printf("%d ", j);
}
printf("\n");
for (i = ; i < rows; i++)
{
printf("%d ", i);
for (j = ; j < cols; j++)
{
if (board[i][j] == -1)
{
printf("* ");
}
else
{
printf("%d ", get_mine_count(board, i, j));
}
}
printf("\n");
}
}
int get_mine_count(int board[ROWS][COLS], int row, int col)
{
int count = ;
int i, j;
for (i = row - 1; i <= row + 1; i++)
{
for (j = col - 1; j <= col + 1; j++)
{
if (i >= && i < ROWS && j >= && j < COLS && board[i][j] == -1)
{
count++;
}
}
}
return count;
}
void reveal_board(int board[ROWS][COLS], int rows, int cols, int row, int col)
{
if (row < || row >= rows || col < || col >= cols || board[row][col] != )
{
return;
}
board[row][col] = get_mine_count(board, row, col);
if (board[row][col] == )
{
reveal_board(board, rows, cols, row - 1, col - 1);
reveal_board(board, rows, cols, row - 1, col);
reveal_board(board, rows, cols, row - 1, col + 1);
reveal_board(board, rows, cols, row, col - 1);
reveal_board(board, rows, cols, row, col + 1);
reveal_board(board, rows, cols, row + 1, col - 1);
reveal_board(board, rows, cols, row + 1, col);
reveal_board(board, rows, cols, row + 1, col + 1);
}
}
int is_game_over(int board[ROWS][COLS], int rows, int cols)
{
int i, j;
for (i = ; i < rows; i++)
{
for (j = ; j < cols; j++)
{
if (board[i][j] == )
{
return ;
}
}
}
return 1;
}
阅读全文