使用C++写扫雷小游戏代码
时间: 2023-05-12 16:04:38 浏览: 136
C++ 扫雷小游戏纯代码版简易
5星 · 资源好评率100%
以下是使用 C 语言编写的扫雷小游戏代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define MINE_NUM 10
void init_board(char board[ROW][COL], int row, int col, char ch);
void print_board(char board[ROW][COL], int row, int col);
void set_mine(char board[ROW][COL], int row, int col, int num);
int get_mine_count(char board[ROW][COL], int row, int col, int x, int y);
int main()
{
char board[ROW][COL];
int x, y, count = 0;
srand((unsigned int)time(NULL)); // 初始化随机数种子
init_board(board, ROW, COL, ' ');
set_mine(board, ROW, COL, MINE_NUM);
printf("扫雷小游戏开始!\n");
print_board(board, ROW, COL);
while (1) {
printf("请输入要扫描的坐标(x,y):");
scanf("%d,%d", &x, &y);
if (x < 1 || x > ROW || y < 1 || y > COL) {
printf("坐标输入有误,请重新输入!\n");
continue;
}
if (board[x - 1][y - 1] == '*') {
printf("很遗憾,你踩到了地雷,游戏结束!\n");
break;
}
count = get_mine_count(board, ROW, COL, x - 1, y - 1);
board[x - 1][y - 1] = count + '0';
if (count == 0) {
int i, j;
for (i = x - 2; i <= x; i++) {
for (j = y - 2; j <= y; j++) {
if (i >= 0 && i < ROW && j >= 0 && j < COL && board[i][j] == ' ') {
count = get_mine_count(board, ROW, COL, i, j);
board[i][j] = count + '0';
}
}
}
}
print_board(board, ROW, COL);
int i, j, win = 1;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] == ' ') {
win = 0;
break;
}
}
}
if (win) {
printf("恭喜你,扫雷成功!\n");
break;
}
}
return 0;
}
void init_board(char board[ROW][COL], int row, int col, char ch)
{
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
board[i][j] = ch;
}
}
}
void print_board(char board[ROW][COL], int row, int col)
{
int i, j;
printf(" ");
for (i = 1; i <= col; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < row; i++) {
printf("%d ", i + 1);
for (j = 0; j < col; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void set_mine(char board[ROW][COL], int row, int col, int num)
{
int i, j, count =
阅读全文