用c语言给我写一个扫雷的小游戏
时间: 2023-05-21 20:02:17 浏览: 149
扫雷小游戏,和window上自带的一模一样。用java编写,可以在各大系统运行.zip
好的,以下是一个简单的扫雷小游戏的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 9
#define COLS 9
#define MINE_NUM 10
void init_board(char board[ROWS][COLS], int rows, int cols, char ch);
void display_board(char board[ROWS][COLS], int rows, int cols);
void set_mine(char board[ROWS][COLS], int rows, int cols, int num);
int get_mine_count(char board[ROWS][COLS], int x, int y);
int main()
{
char board[ROWS][COLS];
int x, y, count = 0;
srand((unsigned int)time(NULL)); // 初始化随机数种子
init_board(board, ROWS, COLS, ' ');
set_mine(board, ROWS, COLS, MINE_NUM);
printf("Welcome to Minesweeper!\n");
display_board(board, ROWS, COLS);
while (1)
{
printf("Please enter the coordinates (x, y): ");
scanf("%d%d", &x, &y);
if (x < 0 || x >= ROWS || y < 0 || y >= COLS)
{
printf("Invalid coordinates, please try again.\n");
continue;
}
if (board[x][y] != ' ')
{
printf("This cell has been revealed, please try again.\n");
continue;
}
count++;
if (board[x][y] == '*')
{
printf("Game over! You stepped on a mine.\n");
board[x][y] = 'X';
display_board(board, ROWS, COLS);
break;
}
else
{
int mine_count = get_mine_count(board, x, y);
board[x][y] = mine_count + '0';
display_board(board, ROWS, COLS);
if (count == ROWS * COLS - MINE_NUM)
{
printf("Congratulations! You win!\n");
break;
}
}
}
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 display_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_mine(char board[ROWS][COLS], int rows, int cols, int num)
{
int i, x, y;
for (i = 0; i < num; i++)
{
do
{
x = rand() % rows;
y = rand() % cols;
} while (board[x][y] == '*');
board[x][y] = '*';
}
}
int get_mine_count(char board[ROWS][COLS], int x, int y)
{
int count = 0, i, j;
for (i = x - 1; i <= x + 1; i++)
{
for (j = y - 1; j <= y + 1; j++)
{
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == '*')
{
count++;
}
}
}
return count;
}
阅读全文