用C语言编写一个扫雷游戏
时间: 2023-05-14 07:06:10 浏览: 128
好的,我可以为您提供一个简单的扫雷游戏的 C 语言代码。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
void init_board(char board[ROWS][COLS], int rows, int cols, char ch);
void print_board(char board[ROWS][COLS], int rows, int cols);
void set_mines(char board[ROWS][COLS], int rows, int cols, int num_mines);
void set_numbers(char board[ROWS][COLS], int rows, int cols);
void play_game(char board[ROWS][COLS], char show_board[ROWS][COLS], int rows, int cols);
int main()
{
char board[ROWS][COLS];
char show_board[ROWS][COLS];
srand((unsigned int)time(NULL));
init_board(board, ROWS, COLS, ' ');
init_board(show_board, ROWS, COLS, '*');
set_mines(board, ROWS, COLS, MINES);
set_numbers(board, ROWS, COLS);
print_board(show_board, ROWS, COLS);
play_game(board, show_board, ROWS, COLS);
return 0;
}
void init_board(char board[ROWS][COLS], int rows, int cols, char ch)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
board[i][j] = ch;
}
}
}
void print_board(char board[ROWS][COLS], int rows, int cols)
{
int i, j;
printf(" ");
for (i = 0; i < cols; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 0; i < rows; i++)
{
printf("%d ", i);
for (j = 0; j < cols; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void set_mines(char board[ROWS][COLS], int rows, int cols, int num_mines)
{
int i, j, count = 0;
while (count < num_mines)
{
i = rand() % rows;
j = rand() % cols;
if (board[i][j] != '*')
{
board[i][j] = '*';
count++;
}
}
}
void set_numbers(char board[ROWS][COLS], int rows, int cols)
{
int i, j, count;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (board[i][j] != '*')
{
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 < cols - 1 && board[i - 1][j + 1] == '*')
count++;
if (j > 0 && board[i][j - 1] == '*')
count++;
if (j < cols - 1 && board[i][j + 1] == '*')
count++;
if (i < rows - 1 && j > 0 && board[i + 1][j - 1] == '*')
count++;
if (i < rows - 1 && board[i + 1][j] == '*')
count++;
if (i < rows - 1 && j < cols - 1 && board[i + 1][j + 1] == '*')
count++;
board[i][j] = count + '0';
}
}
}
}
void play_game(char board[ROWS][COLS], char show_board[ROWS][COLS], int rows, int cols)
{
int i, j, x, y, count = 0;
char ch;
while (count < rows * cols - MINES)
{
printf("Enter row and column: ");
scanf("%d %d", &x, &y);
if (board[x][y] == '*')
{
printf("Game over!\n");
print_board(board, rows, cols);
return;
}
else
{
show_board[x][y] = board[x][y];
print_board(show_board, rows, cols);
count++;
}
}
printf("You win!\n");
print_board(board, rows, cols);
}
阅读全文