话不多说直接淦代码,代码都有详细注释:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#define ROW 9
#define LIN 9
#define ROWS 11
#define LINS 11
#define MINE_COUNT 10
//1.菜单
void menu() {
printf("------------------------扫雷小游戏--------------------------\n\n");
printf("*************************1.play*****************************\n");
printf("*************************2.exit*****************************\n");
printf("------------------------------------------------------------\n");
}
//2.初始化棋盘
void InitBoard(char arr[ROWS][LINS], int row, int lin, char c) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < lin; j++) {
arr[i][j] = c;
}
}
}
//3.打印内部棋盘,用于作者开发时参考
//void Show_board(char arr[ROWS][LINS], int row, int lin) {
// for (int i = 0; i < row; i++) {
// for (int j = 0; j < lin; j++) {
// printf("%c ", arr[i][j]);
// }
// printf("\n");
// }
//}
//4.设置雷的数量
void Setmine(char arr[ROWS][LINS]) {
int mine_num = MINE_COUNT;
while (mine_num > 0) {
int x = rand() % 9 + 1;
int y = rand() % 9 + 1;
if (arr[x][y] == '0') {
arr[x][y] = '1';
mine_num--;
}
}
}
//5.打印棋盘
void Noticeboard(char arr[ROWS][LINS]) {
for (int i = 0; i < ROW+1; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 1; i <= LIN; i++) {
printf("%d ", i);
for (int j= 1; j <= LIN; j++) {
printf("%c ", arr[i][j]);
}
printf("\n");
}
}
//6.计算用户输入的位置周围的雷的个数
int Getmess(char arr[ROWS][LINS], int x, int y) {
return arr[x - 1][y - 1] + arr[x - 1][y] + arr[x - 1][y + 1]
+ arr[x][y - 1]+ arr[x][y + 1]
+ arr[x + 1][y -1] + arr[x + 1][y] + arr[x + 1][y + 1]-8*'0';//char转为int
}
void Startgame(char board[ROWS][LINS], char My_board[ROWS][LINS]) {
printf("请输入横坐标+空格+做坐标\n");
int x = 0;
int y = 0;
int step = 0;//用户的步数
while (step < ROW * LIN - MINE_COUNT) {//用户走的步数:棋盘总数-雷的数量
(void)scanf("%d %d", &x, &y);
if (x <= 9 && x >= 1 && y <= 9 && y >= 1) {
if (My_board[x][y] == '1') {
//踩雷了
printf("boom!游戏结束!!\n");
Noticeboard(My_board);
break;
}
else {
int num = Getmess(My_board, x, y);
//printf("有%d个雷\n", num);
board[x][y] = num + '0';//int转为char
system("cls");
Noticeboard(board);
step++;
}
printf("请输入横坐标+空格+做坐标\n");
}
else {
printf("输入有误!重新输入:\n");
}
}
printf("你真厉害!你赢了~\n");
}
void game() {
//设置两个雷区;
char board[ROWS][LINS];//用户看到的棋盘
char My_board[ROWS][LINS];//内部棋盘
InitBoard(board, ROWS, LINS, '?');//初始化棋盘
//Show_board(board, ROWS, LINS);
InitBoard(My_board, ROWS, LINS, '0');//初始化棋盘
Setmine(My_board);//设置雷
//Show_board(My_board, ROWS, LINS);
Noticeboard(board);//打印棋盘
Startgame(board, My_board);//开始游戏
}
int main() {
srand((unsigned int)time(0));//设置随机数
while (1) {
menu();//打印菜单
int choice;
printf("请输入选择:\n");
(void)scanf("%d", &choice);//用户输入
if (choice == 1) {
printf("play\n");
Sleep(500);
system("cls");
game();
}
else if (choice == 2) {
printf("exit\n");
break;
}
else {
printf("您的输入有误请重新输入:\n");
}
}
return 0;
}
|