扫雷游戏1.0
可完成的任务
9*9的可放置雷区,通过输入坐标进行排雷,并显示周围雷的数量
以下是详细代码
注:仅个人看法,请大佬指导
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()//开始游戏界面
{
printf("********************\n");
printf("****** 1.go ******\n");
printf("****** 0.back ******\n");
printf("********************\n");
}
void game()
{
//定义棋盘
char mine[ROWS][COLS];
char show[ROWS][COLS];
//初始化棋盘
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
//打印棋盘
DisplayBoard(mine, ROW, COL);
DisplayBoard(show, ROW, COL);
//安雷
Setmine(mine, ROW, COL);
//DisplayBoard(mine, ROW, COL);//测试用
//排雷
Findmine(mine, show, ROW, COL);
}
int main()
{
//开始界面
int input = 0;//模式选择
srand((unsigned int)time(NULL));
do
{
printf("请选择:\n");
menu();//开始游戏界面
scanf("%d", &input);
switch (input)
{
case 1:
game();//游戏开始
break;
case 0:
printf("退出游戏");
break;
default:
printf("选择错误,重新选择\n");
break;
}
}while (input);
return 0;
}
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
//创建两个棋盘
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
int i = 0;
for (i = 0; i < rows;i++)
{
int j = 0;
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
//初始化两个棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
int i = 0;
printf("----------扫雷游戏------------\n");
for (i = 0; i <= col; i++)//打印行列序号
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i<= row; i++)
{
printf("%d ", i);
int j = 0;
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
//安雷
void Setmine(char board[ROWS][COLS], int row, int col)
{
//产生随机数
int count = TOTAL;//雷的数量
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
return (mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] + mine[x][y - 1] + mine[x][y + 1] + mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0');
}
//排雷
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int win = 0;
while (win < row * col - TOTAL)
{
printf("请输入要排查的坐标:>");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (mine[x][y] == '1')//如果此处是雷,游戏结束
{
printf("game over!!!\n");
DisplayBoard(mine, ROW, COL);
break;
}
else//如果此处不是雷,要检查附近这个3*3的矩阵有几个雷
{
int count = GetMineCount(mine, x, y);
show[x][y] = count + '0';
DisplayBoard(show, ROW, COL);
win++;
}
}
else
{
printf("超出范围,请重新输入\n");
}
}
if (win == row * col - TOTAL)
{
printf("you win!!!\n");
DisplayBoard(mine, ROW, COL);
}
}
game.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define TOTAL 10//雷的数量
//初始化棋盘
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);
//打印棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col);
//安雷
void Setmine(char board[ROWS][COLS], int row, int col);
//排雷
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);