用c++写扫雷游戏代码
时间: 2023-04-04 10:01:09 浏览: 156
C++扫雷游戏源代码.zip
好的,我可以回答这个问题。以下是一个简单的扫雷游戏代码示例:
#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(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 ;
}
void init_board(char board[ROWS][COLS], int rows, int cols, char ch)
{
int i, j;
for (i = ; i < rows; i++) {
for (j = ; j < cols; j++) {
board[i][j] = ch;
}
}
}
void print_board(char board[ROWS][COLS], int rows, int cols)
{
int i, j;
printf(" ");
for (i = ; i < cols; i++) {
printf("%d ", i);
}
printf("\n");
for (i = ; i < rows; i++) {
printf("%d ", i);
for (j = ; 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 = ;
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 = ; i < rows; i++) {
for (j = ; j < cols; j++) {
if (board[i][j] == '*') {
continue;
}
count = ;
if (i > && j > && board[i-1][j-1] == '*') {
count++;
}
if (i > && board[i-1][j] == '*') {
count++;
}
if (i > && j < cols-1 && board[i-1][j+1] == '*') {
count++;
}
if (j > && board[i][j-1] == '*') {
count++;
}
if (j < cols-1 && board[i][j+1] == '*') {
count++;
}
if (i < rows-1 && j > && 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 + '';
}
}
}
void play_game(char board[ROWS][COLS], char show_board[ROWS][COLS], int rows, int cols)
{
int i, j, x, y, count = ;
char ch;
while (count < rows * cols - MINES) {
printf("请输入坐标(x,y)和操作(扫雷:S 标记:M):");
scanf("%d%d %c", &x, &y, &ch);
if (x < || x >= rows || y < || y >= cols) {
printf("坐标不合法,请重新输入!\n");
continue;
}
if (show_board[x][y] != '-') {
printf("该位置已经操作过,请重新输入!\n");
continue;
}
if (ch == 'S') {
if (board[x][y] == '*') {
printf("你踩到地雷了,游戏结束!\n");
print_board(board, rows, cols);
return;
} else {
show_board[x][y] = board[x][y];
count++;
}
} else if (ch == 'M') {
show_board[x][y] = 'M';
} else {
printf("操作不合法,请重新输入!\n");
continue;
}
print_board(show_board, rows, cols);
}
printf("恭喜你,扫雷成功!\n");
print_board(board, rows, cols);
}
阅读全文