做一个c语言扫雷游戏代码
时间: 2024-04-23 13:15:30 浏览: 69
以下是一个简单的C语言扫雷游戏代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define MINE 10
char board[ROW][COL];
char show[ROW][COL];
void init_board();
void set_mine();
void show_board();
void play_game();
void open(int row, int col);
int main()
{
init_board();
set_mine();
play_game();
return 0;
}
void init_board()
{
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = '0';
show[i][j] = '*';
}
}
}
void set_mine()
{
int i, j, count = 0;
srand((unsigned)time(NULL));
while (count < MINE) {
i = rand() % ROW;
j = rand() % COL;
if (board[i][j] != 'M') {
board[i][j] = 'M';
count++;
}
}
}
void show_board()
{
int i, j;
printf("\n ");
for (i = 0; i < COL; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d ", i + 1);
for (j = 0; j < COL; j++) {
printf("%c ", show[i][j]);
}
printf("\n");
}
}
void play_game()
{
int row, col, count = ROW * COL - MINE;
while (count > 0) {
show_board();
printf("Enter the row and column: ");
scanf("%d%d", &row, &col);
if (row < 1 || row > ROW || col < 1 || col > COL) {
printf("Invalid input!\n");
continue;
}
if (board[row - 1][col - 1] == 'M') {
printf("Game over!\n");
show_board();
return;
}
open(row - 1, col - 1);
count--;
}
printf("You win!\n");
show_board();
}
void open(int row, int col)
{
if (row < 0 || row >= ROW || col < 0 || col >= COL || show[row][col] != '*') {
return;
}
int i, j, count = 0;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROW && j >= 0 && j < COL && board[i][j] == 'M') {
count++;
}
}
}
if (count > 0) {
show[row][col] = count + '0';
} else {
show[row][col] = '/';
open(row - 1, col - 1);
open(row - 1, col);
open(row - 1, col + 1);
open(row, col - 1);
open(row, col + 1);
open(row + 1, col - 1);
open(row + 1, col);
open(row + 1, col + 1);
}
}
```
该代码使用二维数组实现了一个9x9的扫雷游戏,其中包含10个地雷。玩家先输入行和列的坐标,然后程序会根据玩家的输入判断是否命中地雷,如果命中则游戏结束,否则程序会根据玩家的输入进行递归展开周围的格子,直到所有非地雷的格子都被展开,或者命中地雷。最终如果所有非地雷的格子都被展开,则玩家获胜。
阅读全文