扫雷
游戏总结:
首先要绘制界面,打印10*10的游戏界面,然后对游戏界面进行初始化,然后布雷,检测雷周围的数字并打印,若设置20个雷,则最多猜80次,若80次全都没有踩雷,则游获胜,若80次内任意一次点到雷的位置,则游戏失败。
代码入戏:
有三个文件,game.h函数的声明 game.c函数的实现 main.c主体的实现
game.h
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef _MINE_H_
#define _MINE_H_
#include<stdio.h>
#include<time.h>
#include<windows.h>
#include<string.h>
#define ROW 10+2 //提醒用10*10
#define COL 10+2 //提醒用10*10
#define TOTAL 10*10
#define MINE_NUM 20
void SetMine(char mine[][COL],int row, int col);
void ShowBoard(char board[][COL], int row, int col);
char GetMines(char mine[][COL], int row, int col);//char->'0'~'8'
void Game();
#endif
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
int GetRandIndex(int start, int end)
{
return rand() % (end - start + 1);
}
void SetMine(char mine[][COL], int row, int col)
{
srand((unsigned long)time(NULL));
int count = 0;
while (count<MINE_NUM)
{
int x = GetRandIndex(1, 10);
int y = GetRandIndex(1, 10);
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count++;
}
}
}
void ShowBoard(char board[][COL], int row, int col)
{
printf(" ");
int i = 1;
for(i = 1; i <= 10; i++)
{
printf(" %d ", i);
}
printf("\n----");
for (i = 1; i <= 10; i++)
{
printf("---");
}
printf("\n");
for (i = 1; i <= 10; i++)
{
printf("%3d|",i);
int j = 1;
for (j = 1; j <= 10; j++)
{
printf("%2c|", board[i][j]);
}
printf("\n");
int k = 1;
for (k = 1;k <= 11; k++)
{
printf("---");
}
printf("\n");
}
}
//'0'~'8'
char GetMines(char mine[][COL], int row, int col)//char->'0'~'8'
{
return mine[row - 1][col - 1] + mine[row - 1][col] + mine[row - 1][col + 1] \
+ mine[row][col - 1] + mine[row][col + 1] + mine[row + 1][col - 1]\
+ mine[row + 1][col] + mine[row + 1][col + 1] - 7 * '0';
}
void Game()
{
char mine[ROW][COL];//set/judgr mine
char board[ROW][COL];//show
memset(mine,'0',sizeof(mine));
memset(board, '*', sizeof(board));
SetMine(mine, ROW, COL);
int count = TOTAL;
int x = 0;
int y = 0;
while (1)
{
ShowBoard(board,ROW,COL);
printf("请选择坐标: ");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= ROW - 2 && y >= 1 && y <= COL - 2)
{
if (mine[x][y] == '0')
{
char num = GetMines(mine, x, y);
board[x][y] = num;
count--;
if (count <= 20)
{
printf("你赢了!\n");
break;
}
}
else
{
printf("你被炸死了!\n");
ShowBoard(mine, ROW, COL);
break;
}
}
else
{
printf("你输入的坐标有误,请重新输入!\n");
}
}
}
main.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void Menu()
{
printf("************************\n");
printf("********0.Exit**********\n");
printf("********1.Play**********\n");
printf("*****please select******\n");
}
int main()
{
int quit = 0;
int select = 0;
while (!quit)
{
Menu();
scanf("%d", &select);
switch (select)
{
case 1:
Game();
break;
case 2:
printf("游戏退出!\n");
quit = 1;
break;
default:
printf("选择错误,请重新选择!\n");
break;
}
}
system("pause");
return 0;
}
扫雷游戏可以进行优化:第一次下子,不炸死,坐标周围没雷,可以实现展开。